Files
golang-api-starter/internal/middleware/auth.go
2025-11-29 16:59:02 -06:00

57 lines
1.4 KiB
Go

package middleware
import (
"context"
"errors"
"log"
"net/http"
"strings"
"git.kling.dev/jared/WorkoutTrackerAPI/internal/auth"
)
type contextKey string
const (
UserIDKey contextKey = "user_id"
EmailKey contextKey = "email"
)
func ValidateJWT(jwtManager auth.JWTManager) func(http.HandlerFunc) http.HandlerFunc {
return func(next http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("Starting ValidateJWT handler")
auth_header := r.Header.Get("Authorization")
if auth_header == "" {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("Missing authorization header"))
return
}
parts := strings.Split(auth_header, " ")
if len(parts) != 2 || strings.ToLower(strings.Trim(parts[0], " ")) != "bearer" {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("Invalid authorization header format"))
return
}
tokenString := parts[1]
claims, err := jwtManager.ValidateToken(tokenString)
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
if errors.Is(err, auth.ErrExpiredToken) {
w.Write([]byte("Token has expired"))
return
}
w.Write([]byte("Invalid token"))
return
}
ctx := context.WithValue(r.Context(), UserIDKey, claims.Subject)
ctx = context.WithValue(ctx, EmailKey, claims.Email)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}