Files
Charon/backend/internal/api/middleware/optional_auth.go
GitHub Actions 3632d0d88c fix: user roles to use UserRole type and update related tests
- Changed user role representation from string to UserRole type in User model.
- Updated role assignments in various services and handlers to use the new UserRole constants.
- Modified middleware to handle UserRole type for role checks.
- Refactored tests to align with the new UserRole type.
- Added migration function to convert legacy "viewer" roles to "passthrough".
- Ensured all role checks and assignments are consistent across the application.
2026-03-03 03:10:02 +00:00

45 lines
861 B
Go

package middleware
import (
"github.com/Wikid82/charon/backend/internal/services"
"github.com/gin-gonic/gin"
)
// OptionalAuth applies best-effort authentication for downstream middleware without blocking requests.
func OptionalAuth(authService *services.AuthService) gin.HandlerFunc {
return func(c *gin.Context) {
if authService == nil {
c.Next()
return
}
if bypass, exists := c.Get("emergency_bypass"); exists {
if bypassActive, ok := bypass.(bool); ok && bypassActive {
c.Next()
return
}
}
if _, exists := c.Get("role"); exists {
c.Next()
return
}
tokenString, ok := extractAuthToken(c)
if !ok {
c.Next()
return
}
user, _, err := authService.AuthenticateToken(tokenString)
if err != nil {
c.Next()
return
}
c.Set("userID", user.ID)
c.Set("role", string(user.Role))
c.Next()
}
}