123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136 |
- package middleware
- import (
- "context"
- "fmt"
- "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, role, err := authService.ValidateToken(c.Request.Context(), token)
- if err != nil {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
- c.Abort()
- return
- }
- fmt.Println("Client ID from token:", clientID)
- fmt.Println("Role from token:", role)
- // Set client ID and role in context for later use
- c.Set("clientID", clientID)
- c.Set("user_id", clientID) // Set user_id for backward compatibility
- c.Set("role", role)
- 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)
- fmt.Println("Role from context:", role)
- 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 ""
- }
- // AdminAuth middleware checks if the user has admin role
- func AdminAuth(authService auth.Service) gin.HandlerFunc {
- 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, role, err := authService.ValidateToken(c.Request.Context(), token)
- if err != nil {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
- c.Abort()
- return
- }
- // Check if the user has admin role
- if role != "admin" {
- c.JSON(http.StatusForbidden, gin.H{"error": "Admin access required"})
- c.Abort()
- return
- }
- // Set client ID and role in context for later use
- c.Set("clientID", clientID)
- c.Set("user_id", clientID) // Set user_id for backward compatibility
- c.Set("role", role)
- c.Next()
- }
- }
|