This commit is contained in:
2024-12-05 23:24:39 +01:00
parent b9d50d986f
commit fe2d7c0fd4
16 changed files with 228 additions and 181 deletions

View File

@@ -0,0 +1,38 @@
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 getSessionID(r *http.Request) string {
cookie, err := r.Cookie("id")
if err != nil {
return ""
}
return cookie.Name
}