Files
Charon/backend/internal/api/middleware/auth.go
GitHub Actions 7ca5a11572 Add ImportSuccessModal tests, enhance AuthContext for token management, and improve useImport hook
- Implement tests for ImportSuccessModal to verify rendering and functionality.
- Update AuthContext to store authentication token in localStorage and manage token state.
- Modify useImport hook to capture and expose commit results, preventing unnecessary refetches.
- Enhance useCertificates hook to support optional refetch intervals.
- Update Dashboard to conditionally poll certificates based on pending status.
- Integrate ImportSuccessModal into ImportCaddy for user feedback on import completion.
- Adjust Login component to utilize returned token for authentication.
- Refactor CrowdSecConfig tests for improved readability and reliability.
- Add debug_db.py script for inspecting the SQLite database.
- Update integration and test scripts for better configuration and error handling.
- Introduce Trivy scan script for vulnerability assessment of Docker images.
2025-12-12 00:05:15 +00:00

63 lines
1.4 KiB
Go

package middleware
import (
"net/http"
"strings"
"github.com/Wikid82/charon/backend/internal/services"
"github.com/gin-gonic/gin"
)
func AuthMiddleware(authService *services.AuthService) gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
// Try cookie first for browser flows
if cookie, err := c.Cookie("auth_token"); err == nil && cookie != "" {
authHeader = "Bearer " + cookie
}
}
if authHeader == "" {
// Try query param (token passthrough)
if token := c.Query("token"); token != "" {
authHeader = "Bearer " + token
}
}
if authHeader == "" {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Authorization header required"})
return
}
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
claims, err := authService.ValidateToken(tokenString)
if err != nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
return
}
c.Set("userID", claims.UserID)
c.Set("role", claims.Role)
c.Next()
}
}
func RequireRole(role string) gin.HandlerFunc {
return func(c *gin.Context) {
userRole, exists := c.Get("role")
if !exists {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
return
}
if userRole.(string) != role && userRole.(string) != "admin" {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "Forbidden"})
return
}
c.Next()
}
}