1
0

middleware.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package auth
  2. import (
  3. "net/http"
  4. "strings"
  5. )
  6. // AuthMiddleware extracts and validates JWT tokens from requests
  7. func AuthMiddleware(next http.Handler) http.Handler {
  8. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  9. authHeader := r.Header.Get("Authorization")
  10. if authHeader == "" {
  11. // No token, proceed without user in context
  12. next.ServeHTTP(w, r)
  13. return
  14. }
  15. // Extract Bearer token
  16. parts := strings.SplitN(authHeader, " ", 2)
  17. if len(parts) != 2 || strings.ToLower(parts[0]) != "bearer" {
  18. // Invalid header format, proceed without user
  19. next.ServeHTTP(w, r)
  20. return
  21. }
  22. tokenString := parts[1]
  23. claims, err := ValidateToken(tokenString)
  24. if err != nil {
  25. // Invalid token, proceed without user
  26. next.ServeHTTP(w, r)
  27. return
  28. }
  29. // Add user to context
  30. user := &UserContext{
  31. ID: claims.UserID,
  32. Email: claims.Email,
  33. Roles: claims.Roles,
  34. Permissions: claims.Permissions,
  35. }
  36. ctx := WithUser(r.Context(), user)
  37. next.ServeHTTP(w, r.WithContext(ctx))
  38. })
  39. }