Initial commit
This commit is contained in:
commit
b6014c6ffc
47 files changed
+4329
No files matched your search
@@ -0,0 +1,42 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type contextKey string
|
||||
|
||||
const userIDContextKey contextKey = "userID"
|
||||
|
||||
// RequireAuth reads the session cookie, verifies the JWT, and injects the
|
||||
// internal user ID into the request context. Responds 401 if missing/invalid.
|
||||
// This is the only route guard the app needs — every non-auth API route is
|
||||
// wrapped with it.
|
||||
func RequireAuth(jwtSecret string) 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 {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
claims, err := ParseSessionJWT(jwtSecret, cookie.Value)
|
||||
if err != nil {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := context.WithValue(r.Context(), userIDContextKey, claims.Subject)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// UserIDFromContext returns the authenticated user's internal UUID. Only
|
||||
// valid on requests that passed through RequireAuth.
|
||||
func UserIDFromContext(ctx context.Context) (string, bool) {
|
||||
id, ok := ctx.Value(userIDContextKey).(string)
|
||||
return id, ok
|
||||
}
|
||||
Reference in new issue
Block a user