feat: #337 unify types for auth module
This commit was merged in pull request #338.
This commit is contained in:
@@ -2,24 +2,29 @@ package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"me-fit/service"
|
||||
|
||||
"net/http"
|
||||
"me-fit/types"
|
||||
)
|
||||
|
||||
type ContextKey string
|
||||
|
||||
var SessionKey ContextKey = "session"
|
||||
var UserKey ContextKey = "user"
|
||||
|
||||
func Authenticate(service service.Auth) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
|
||||
sessionId := getSessionID(r)
|
||||
session, _ := service.SignInSession(sessionId)
|
||||
session, user, _ := service.SignInSession(sessionId)
|
||||
|
||||
if session != nil {
|
||||
ctx := context.WithValue(r.Context(), SessionKey, session)
|
||||
|
||||
ctx = context.WithValue(ctx, UserKey, user)
|
||||
ctx = context.WithValue(ctx, SessionKey, session)
|
||||
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
} else {
|
||||
@@ -29,23 +34,22 @@ func Authenticate(service service.Auth) func(http.Handler) http.Handler {
|
||||
}
|
||||
}
|
||||
|
||||
func GetUser(r *http.Request) *service.User {
|
||||
|
||||
session := GetSession(r)
|
||||
if session == nil {
|
||||
func GetUser(r *http.Request) *types.User {
|
||||
obj := r.Context().Value(UserKey)
|
||||
if obj == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return session.User
|
||||
return obj.(*types.User)
|
||||
}
|
||||
|
||||
func GetSession(r *http.Request) *service.Session {
|
||||
func GetSession(r *http.Request) *types.Session {
|
||||
obj := r.Context().Value(SessionKey)
|
||||
if obj == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return obj.(*service.Session)
|
||||
return obj.(*types.Session)
|
||||
}
|
||||
|
||||
func getSessionID(r *http.Request) string {
|
||||
|
||||
Reference in New Issue
Block a user