Some checks failed
Deploy to NAS / deploy (push) Failing after 4s
Remove submodule tracking; backend is now a plain directory in the repo. Also update deploy workflow: remove --recurse-submodules. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
44 lines
1.1 KiB
Go
44 lines
1.1 KiB
Go
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)
|
|
}
|