Files
Charon/backend/internal/api/handlers/auth_handler.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

74 lines
1.9 KiB
Go

package handlers
import (
"net/http"
"github.com/Wikid82/CaddyProxyManagerPlus/backend/internal/services"
"github.com/gin-gonic/gin"
)
type AuthHandler struct {
authService *services.AuthService
}
func NewAuthHandler(authService *services.AuthService) *AuthHandler {
return &AuthHandler{authService: authService}
}
type LoginRequest struct {
Email string `json:"email" binding:"required,email"`
Password string `json:"password" binding:"required"`
}
func (h *AuthHandler) Login(c *gin.Context) {
var req LoginRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
token, err := h.authService.Login(req.Email, req.Password)
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
return
}
// Set cookie
c.SetCookie("auth_token", token, 3600*24, "/", "", false, true) // Secure should be true in prod
c.JSON(http.StatusOK, gin.H{"token": token})
}
type RegisterRequest struct {
Email string `json:"email" binding:"required,email"`
Password string `json:"password" binding:"required,min=8"`
Name string `json:"name" binding:"required"`
}
func (h *AuthHandler) Register(c *gin.Context) {
var req RegisterRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
user, err := h.authService.Register(req.Email, req.Password, req.Name)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusCreated, user)
}
func (h *AuthHandler) Logout(c *gin.Context) {
c.SetCookie("auth_token", "", -1, "/", "", false, true)
c.JSON(http.StatusOK, gin.H{"message": "Logged out"})
}
func (h *AuthHandler) Me(c *gin.Context) {
userID, _ := c.Get("userID")
role, _ := c.Get("role")
c.JSON(http.StatusOK, gin.H{"user_id": userID, "role": role})
}