1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- package middleware
- import (
- "context"
- "net/http"
- "git.linuxforward.com/byop/byop-engine/auth"
- "github.com/gin-gonic/gin"
- "github.com/golang-jwt/jwt/v5"
- )
- // debugMode is a flag to enable or disable debug logging
- var debug = true
- // JWT secret key - in production, this should be loaded from environment variables
- var jwtSecret = []byte("your-secret-key-here")
- // Claims represents the JWT claims
- type Claims struct {
- UserID string `json:"user_id"`
- Role string `json:"role"`
- jwt.RegisteredClaims
- }
- // Auth middleware that accepts the auth service as dependency
- func Auth(authService auth.Service) gin.HandlerFunc {
- if debug {
- return func(c *gin.Context) {
- c.Set("clientID", "debug_user")
- c.Set("user_id", "debug_user")
- c.Set("role", "admin")
- c.Next()
- }
- }
- return func(c *gin.Context) {
- // Get token from request
- token := extractTokenFromHeader(c)
- if token == "" {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization header required"})
- c.Abort()
- return
- }
- // Validate token using the auth service
- clientID, err := authService.ValidateToken(c.Request.Context(), token)
- if err != nil {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
- c.Abort()
- return
- }
- // Set client ID in context for later use
- c.Set("clientID", clientID)
- c.Next()
- }
- }
- // GetUserIDFromContext retrieves the user ID from the request context
- func GetUserIDFromContext(ctx context.Context) string {
- userID, ok := ctx.Value("user_id").(string)
- if !ok {
- return ""
- }
- return userID
- }
- // GetRoleFromContext retrieves the user role from the request context
- func GetRoleFromContext(ctx context.Context) string {
- role, ok := ctx.Value("role").(string)
- if !ok {
- return ""
- }
- return role
- }
- // IsAdmin checks if the user in the context has admin role
- func IsAdmin(ctx context.Context) bool {
- role := GetRoleFromContext(ctx)
- return role == "admin"
- }
- // extractTokenFromHeader gets the JWT token from the Authorization header
- func extractTokenFromHeader(c *gin.Context) string {
- authHeader := c.GetHeader("Authorization")
- if authHeader == "" {
- return ""
- }
- // Check if the header has the format "Bearer <token>"
- if len(authHeader) > 7 && authHeader[:7] == "Bearer " {
- return authHeader[7:]
- }
- return ""
- }
|