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