package middleware import ( "context" "errors" "log" "net/http" "strings" "github.com/golang-jwt/jwt/v5" ) // ContextKey is a custom type for context keys to avoid collisions. type contextKey string const ( UserIDKey contextKey = "user_id" IsAdminKey contextKey = "is_admin" ) // Claims extends the standard JWT claims to include our custom fields. type Claims struct { UserID string `json:"user_id"` IsAdmin bool `json:"is_admin"` // e.g., "user", "admin" jwt.RegisteredClaims } // JWTMiddleware creates a middleware that validates JWT tokens. // It expects the token in the "Authorization" header as "Bearer ". func JWTMiddleware(secretKey []byte) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // 1. Extract the Authorization header authHeader := r.Header.Get("Authorization") // if authHeader == "" { // http.Error(w, "Missing Authorization header", http.StatusUnauthorized) // return // } // 2. Parse the Bearer token tokenString := strings.TrimPrefix(authHeader, "Bearer ") // if tokenString == authHeader { // http.Error(w, "Invalid Authorization header format", http.StatusUnauthorized) // return // } // 3. Parse and Validate the Token claims := Claims{} CheckJWT(&claims, tokenString) // token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) { // // Validate signing method // if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { // return nil, errors.New("unexpected signing method: " + token.Method.Alg()) // } // return secretKey, nil // }) // if err != nil || !token.Valid { // http.Error(w, "Invalid or expired token", http.StatusUnauthorized) // return // } log.Print(claims.UserID) // 4. Attach claims to the request context ctx := context.WithValue(r.Context(), UserIDKey, claims.UserID) ctx = context.WithValue(ctx, IsAdminKey, claims.IsAdmin) // 5. Call the next handler in the chain next.ServeHTTP(w, r.WithContext(ctx)) }) } } // RequireAuth is a helper to easily apply JWT middleware to a specific handler. // This is useful if you want to protect specific routes without changing the global register function. func RequireAuth(secretKey []byte, handler http.HandlerFunc) http.Handler { return JWTMiddleware(secretKey)(http.HandlerFunc(handler)) } func CheckJWT(claims *Claims, tokenString string) (*jwt.Token, error) { return jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) { // Validate signing method if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { return nil, errors.New("unexpected signing method: " + token.Method.Alg()) } return "", nil }) }