auth.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package middleware
  2. import (
  3. "context"
  4. "net/http"
  5. "git.linuxforward.com/byop/byop-engine/auth"
  6. "github.com/gin-gonic/gin"
  7. "github.com/golang-jwt/jwt/v5"
  8. )
  9. // JWT secret key - in production, this should be loaded from environment variables
  10. var jwtSecret = []byte("your-secret-key-here")
  11. // Claims represents the JWT claims
  12. type Claims struct {
  13. UserID string `json:"user_id"`
  14. Role string `json:"role"`
  15. jwt.RegisteredClaims
  16. }
  17. // Auth middleware that accepts the auth service as dependency
  18. func Auth(authService auth.Service) gin.HandlerFunc {
  19. return func(c *gin.Context) {
  20. // Get token from request
  21. token := extractTokenFromHeader(c)
  22. if token == "" {
  23. c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization header required"})
  24. c.Abort()
  25. return
  26. }
  27. // Validate token using the auth service
  28. clientID, err := authService.ValidateToken(c.Request.Context(), token)
  29. if err != nil {
  30. c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
  31. c.Abort()
  32. return
  33. }
  34. // Set client ID in context for later use
  35. c.Set("clientID", clientID)
  36. c.Next()
  37. }
  38. }
  39. // GetUserIDFromContext retrieves the user ID from the request context
  40. func GetUserIDFromContext(ctx context.Context) string {
  41. userID, ok := ctx.Value("user_id").(string)
  42. if !ok {
  43. return ""
  44. }
  45. return userID
  46. }
  47. // GetRoleFromContext retrieves the user role from the request context
  48. func GetRoleFromContext(ctx context.Context) string {
  49. role, ok := ctx.Value("role").(string)
  50. if !ok {
  51. return ""
  52. }
  53. return role
  54. }
  55. // IsAdmin checks if the user in the context has admin role
  56. func IsAdmin(ctx context.Context) bool {
  57. role := GetRoleFromContext(ctx)
  58. return role == "admin"
  59. }
  60. // extractTokenFromHeader gets the JWT token from the Authorization header
  61. func extractTokenFromHeader(c *gin.Context) string {
  62. authHeader := c.GetHeader("Authorization")
  63. if authHeader == "" {
  64. return ""
  65. }
  66. // Check if the header has the format "Bearer <token>"
  67. if len(authHeader) > 7 && authHeader[:7] == "Bearer " {
  68. return authHeader[7:]
  69. }
  70. return ""
  71. }