package api import ( "context" "net/http" "github.com/jacek/pamietnik/backend/internal/auth" ) type contextKey string const ctxUserID contextKey = "user_id" const sessionCookieName = "session" // RequireAuth is a middleware that validates the session cookie. func RequireAuth(authStore *auth.Store) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { cookie, err := r.Cookie(sessionCookieName) if err != nil { writeError(w, http.StatusUnauthorized, "UNAUTHORIZED", "login required") return } sess, err := authStore.GetSession(r.Context(), cookie.Value) if err != nil { writeError(w, http.StatusUnauthorized, "UNAUTHORIZED", "invalid or expired session") return } ctx := context.WithValue(r.Context(), ctxUserID, sess.UserID) next.ServeHTTP(w, r.WithContext(ctx)) }) } } func userIDFromContext(ctx context.Context) string { v, _ := ctx.Value(ctxUserID).(string) return v } func contextWithUserID(ctx context.Context, userID string) context.Context { return context.WithValue(ctx, ctxUserID, userID) }