Files
go-weather/middleware/auth.go
T
2026-02-23 16:39:04 -05:00

42 lines
990 B
Go

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
}