auth.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. // debugMode is a flag to enable or disable debug logging
  10. var debug = true
  11. // JWT secret key - in production, this should be loaded from environment variables
  12. var jwtSecret = []byte("your-secret-key-here")
  13. // Claims represents the JWT claims
  14. type Claims struct {
  15. UserID string `json:"user_id"`
  16. Role string `json:"role"`
  17. jwt.RegisteredClaims
  18. }
  19. // Auth middleware that accepts the auth service as dependency
  20. func Auth(authService auth.Service) gin.HandlerFunc {
  21. if debug {
  22. return func(c *gin.Context) {
  23. c.Set("clientID", "debug_user")
  24. c.Set("user_id", "debug_user")
  25. c.Set("role", "admin")
  26. c.Next()
  27. }
  28. }
  29. return func(c *gin.Context) {
  30. // Get token from request
  31. token := extractTokenFromHeader(c)
  32. if token == "" {
  33. c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization header required"})
  34. c.Abort()
  35. return
  36. }
  37. // Validate token using the auth service
  38. clientID, err := authService.ValidateToken(c.Request.Context(), token)
  39. if err != nil {
  40. c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
  41. c.Abort()
  42. return
  43. }
  44. // Set client ID in context for later use
  45. c.Set("clientID", clientID)
  46. c.Next()
  47. }
  48. }
  49. // GetUserIDFromContext retrieves the user ID from the request context
  50. func GetUserIDFromContext(ctx context.Context) string {
  51. userID, ok := ctx.Value("user_id").(string)
  52. if !ok {
  53. return ""
  54. }
  55. return userID
  56. }
  57. // GetRoleFromContext retrieves the user role from the request context
  58. func GetRoleFromContext(ctx context.Context) string {
  59. role, ok := ctx.Value("role").(string)
  60. if !ok {
  61. return ""
  62. }
  63. return role
  64. }
  65. // IsAdmin checks if the user in the context has admin role
  66. func IsAdmin(ctx context.Context) bool {
  67. role := GetRoleFromContext(ctx)
  68. return role == "admin"
  69. }
  70. // extractTokenFromHeader gets the JWT token from the Authorization header
  71. func extractTokenFromHeader(c *gin.Context) string {
  72. authHeader := c.GetHeader("Authorization")
  73. if authHeader == "" {
  74. return ""
  75. }
  76. // Check if the header has the format "Bearer <token>"
  77. if len(authHeader) > 7 && authHeader[:7] == "Bearer " {
  78. return authHeader[7:]
  79. }
  80. return ""
  81. }