Files
apocapoc-api/internal/infrastructure/http/auth_middleware.go
T
david e87b7df979 Rename project to apocapoc-api
Update module name and all imports from habit-tracker-api to apocapoc-api.
This reflects the project's new branding as part of the apocapoc ecosystem
(apocapoc-api, apocapoc-web, apocapoc-android).
2025-11-26 11:21:17 +01:00

47 lines
1.1 KiB
Go

package http
import (
"context"
"net/http"
"strings"
"apocapoc-api/internal/infrastructure/auth"
)
type contextKey string
const UserIDKey contextKey = "userID"
func AuthMiddleware(jwtService *auth.JWTService) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
respondError(w, http.StatusUnauthorized, "Missing authorization header")
return
}
parts := strings.Split(authHeader, " ")
if len(parts) != 2 || parts[0] != "Bearer" {
respondError(w, http.StatusUnauthorized, "Invalid authorization header format")
return
}
tokenString := parts[1]
claims, err := jwtService.ValidateToken(tokenString)
if err != nil {
respondError(w, http.StatusUnauthorized, "Invalid or expired token")
return
}
ctx := context.WithValue(r.Context(), UserIDKey, claims.UserID)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
func GetUserIDFromContext(ctx context.Context) (string, bool) {
userID, ok := ctx.Value(UserIDKey).(string)
return userID, ok
}