63 lines
1.1 KiB
Go
63 lines
1.1 KiB
Go
package middleware
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
|
|
"me-fit/service"
|
|
"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, user, _ := service.SignInSession(sessionId)
|
|
|
|
if session != nil {
|
|
|
|
ctx = context.WithValue(ctx, UserKey, user)
|
|
ctx = context.WithValue(ctx, SessionKey, session)
|
|
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
} else {
|
|
next.ServeHTTP(w, r)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func GetUser(r *http.Request) *types.User {
|
|
obj := r.Context().Value(UserKey)
|
|
if obj == nil {
|
|
return nil
|
|
}
|
|
|
|
return obj.(*types.User)
|
|
}
|
|
|
|
func GetSession(r *http.Request) *types.Session {
|
|
obj := r.Context().Value(SessionKey)
|
|
if obj == nil {
|
|
return nil
|
|
}
|
|
|
|
return obj.(*types.Session)
|
|
}
|
|
|
|
func getSessionID(r *http.Request) string {
|
|
cookie, err := r.Cookie("id")
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
|
|
return cookie.Value
|
|
}
|