Files
Charon/backend/internal/api/middleware/auth.go
Wikid82 945b18ab3e feat: Implement User Authentication and Fix Frontend Startup
- Implemented Issue #9: User Authentication & Authorization
  - Added User model fields (FailedLoginAttempts, LockedUntil, LastLogin)
  - Created AuthService with JWT support, bcrypt hashing, and account lockout
  - Added AuthMiddleware and AuthHandler
  - Registered auth routes in backend
  - Created AuthContext and RequireAuth component in frontend
  - Implemented Login page and integrated with backend
- Fixed 'Blank Page' issue in local Docker environment
  - Added QueryClientProvider to main.tsx
  - Installed missing lucide-react dependency
  - Fixed TypeScript linting errors in SetupGuard.tsx
- Updated docker-entrypoint.sh to use 127.0.0.1 for reliable Caddy checks
- Verified with local Docker build
2025-11-19 19:44:22 -05:00

56 lines
1.3 KiB
Go

package middleware
import (
"net/http"
"strings"
"github.com/Wikid82/CaddyProxyManagerPlus/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
cookie, err := c.Cookie("auth_token")
if err == nil {
authHeader = "Bearer " + cookie
}
}
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()
}
}