Files
go-weather/middleware/auth.go
T
2026-02-24 10:42:36 -05:00

40 lines
903 B
Go

package middleware
import (
"context"
"go-weather/services"
"net/http"
)
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) {
cookie, err := r.Cookie("token")
if err != nil {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
claims, err := authService.ValidateToken(cookie.Value)
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
}