add auth middleware

This commit is contained in:
2026-02-23 16:39:04 -05:00
parent af9c23c521
commit 11eb192e2a
4 changed files with 89 additions and 5 deletions
+41
View File
@@ -0,0 +1,41 @@
package middleware
import (
"context"
"go-weather/services"
"net/http"
"strings"
)
type contextKey string
const ClaimsKey contextKey = "claims"
func AuthMiddleware(authService *services.AuthService) 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 == "" {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
claims, err := authService.ValidateToken(tokenString)
if err != nil {
http.Error(w, "invalid token", http.StatusUnauthorized)
return
}
ctx := context.WithValue(r.Context(), ClaimsKey, claims)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
func GetClaims(r *http.Request) *services.Claims {
if claims, ok := r.Context().Value(ClaimsKey).(*services.Claims); ok {
return claims
}
return nil
}