imc-vibe/backend/internal/api/handlers/auth.go
Christoph Haas 2834657125 Switch from net/http to gin-gonic web framework
- Added gin-gonic v1.10.0 dependency
- Refactored router.go: clean route groups with middleware chains
- Refactored all handlers to use gin.Context instead of http.ResponseWriter/*http.Request
- Simplified response helpers (JSON, Error, Success, Created, NoContent)
- Clean auth middleware using Gin's c.Set() for context
- Cleaner route definitions with path parameters (e.g., /domains/:name/users/:id)
- Admin routes moved to /api/admin group with RequireAdmin middleware
2026-03-22 23:28:28 +01:00

250 lines
6.2 KiB
Go

package handlers
import (
"log"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/imc-vibe/backend/internal/auth"
"github.com/imc-vibe/backend/internal/db"
"github.com/imc-vibe/backend/internal/mail"
)
const MaxLoginAttempts = 5
type AuthHandler struct {
db *db.DB
jwtManager *auth.JWTManager
emailService *mail.EmailService
}
func NewAuthHandler(database *db.DB, jwtManager *auth.JWTManager, emailService *mail.EmailService) *AuthHandler {
return &AuthHandler{
db: database,
jwtManager: jwtManager,
emailService: emailService,
}
}
type LoginRequest struct {
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required"`
}
type ChangePasswordRequest struct {
OldPassword string `json:"oldPassword" binding:"required"`
NewPassword string `json:"newPassword" binding:"required,min=8"`
}
type ForgotPasswordRequest struct {
Identifier string `json:"identifier" binding:"required"`
}
type UserResponse struct {
ID uint `json:"id"`
Username string `json:"username"`
Role string `json:"role"`
Domains []string `json:"domains"`
}
func (h *AuthHandler) Login(c *gin.Context) {
var req LoginRequest
if err := c.ShouldBindJSON(&req); err != nil {
Error(c, http.StatusBadRequest, "invalid request body")
return
}
ip := getClientIP(c)
if isLockedOut(ip, req.Username, h.db) {
Error(c, http.StatusTooManyRequests, "too many failed attempts, try again later")
return
}
user, err := h.db.GetImcUserByUsername(req.Username)
if err != nil || user == nil || !auth.CheckPassword(req.Password, user.PasswordHash) {
recordFailedAttempt(req.Username, ip, h.db)
Error(c, http.StatusUnauthorized, "invalid credentials")
return
}
clearFailedAttempts(req.Username, ip, h.db)
domains, _ := h.db.GetUserAccessibleDomains(user.ID, user.Role == "admin")
domainNames := make([]string, len(domains))
for i, d := range domains {
domainNames[i] = d.Name
}
token, err := h.jwtManager.GenerateToken(user.ID, user.Username, user.Role, 24*time.Hour)
if err != nil {
Error(c, http.StatusInternalServerError, "failed to generate token")
return
}
Success(c, map[string]interface{}{
"token": token,
"user": UserResponse{
ID: user.ID,
Username: user.Username,
Role: user.Role,
Domains: domainNames,
},
})
}
func (h *AuthHandler) Me(c *gin.Context) {
authCtx := GetAuthContext(c)
if authCtx == nil {
Error(c, http.StatusUnauthorized, "not authenticated")
return
}
user, err := h.db.GetImcUserByID(authCtx.UserID)
if err != nil || user == nil {
Error(c, http.StatusNotFound, "user not found")
return
}
domains, _ := h.db.GetUserAccessibleDomains(user.ID, user.Role == "admin")
domainNames := make([]string, len(domains))
for i, d := range domains {
domainNames[i] = d.Name
}
Success(c, UserResponse{
ID: user.ID,
Username: user.Username,
Role: user.Role,
Domains: domainNames,
})
}
func (h *AuthHandler) ForgotPassword(c *gin.Context) {
var req ForgotPasswordRequest
if err := c.ShouldBindJSON(&req); err != nil {
Error(c, http.StatusBadRequest, "invalid request")
return
}
req.Identifier = strings.TrimSpace(strings.ToLower(req.Identifier))
if req.Identifier == "" {
Error(c, http.StatusBadRequest, "identifier required")
return
}
user, err := h.db.GetImcUserByUsername(req.Identifier)
if err != nil {
Success(c, map[string]string{
"message": "If the account exists, a password reset link will be sent",
})
return
}
token := mail.GenerateToken()
expiresAt := time.Now().Add(1 * time.Hour)
if err := h.db.CreatePasswordResetToken(user.ID, token, expiresAt); err != nil {
log.Printf("Failed to create password reset token: %v", err)
Error(c, http.StatusInternalServerError, "failed to create reset token")
return
}
if err := h.emailService.SendPasswordReset(user.Username, token); err != nil {
log.Printf("Failed to send password reset email: %v", err)
Error(c, http.StatusInternalServerError, "failed to send email")
return
}
Success(c, map[string]string{
"message": "If the account exists, a password reset link will be sent",
})
}
func (h *AuthHandler) ChangePassword(c *gin.Context) {
authCtx := GetAuthContext(c)
if authCtx == nil {
Error(c, http.StatusUnauthorized, "authentication required")
return
}
var req ChangePasswordRequest
if err := c.ShouldBindJSON(&req); err != nil {
Error(c, http.StatusBadRequest, "invalid request")
return
}
user, err := h.db.GetImcUserByID(authCtx.UserID)
if err != nil || user == nil {
Error(c, http.StatusNotFound, "user not found")
return
}
if !auth.CheckPassword(req.OldPassword, user.PasswordHash) {
Error(c, http.StatusUnauthorized, "current password is incorrect")
return
}
newHash, err := auth.HashPassword(req.NewPassword)
if err != nil {
Error(c, http.StatusInternalServerError, "failed to hash password")
return
}
err = h.db.UpdateImcUserPassword(user.ID, newHash)
if err != nil {
Error(c, http.StatusInternalServerError, "failed to update password")
return
}
Success(c, map[string]string{"message": "password updated successfully"})
}
func (h *AuthHandler) Logout(c *gin.Context) {
Success(c, map[string]string{"message": "logged out"})
}
func isLockedOut(ip, identifier string, database *db.DB) bool {
var count int64
cutoff := time.Now().Add(-15 * time.Minute)
database.Model(&db.ImcLoginAttempt{}).
Where("ip_address = ? AND attempted_at > ? AND successful = false", ip, cutoff).
Count(&count)
if count >= MaxLoginAttempts {
return true
}
database.Model(&db.ImcLoginAttempt{}).
Where("email = ? AND attempted_at > ? AND successful = false", identifier, cutoff).
Count(&count)
return count >= MaxLoginAttempts
}
func recordFailedAttempt(identifier, ip string, database *db.DB) {
database.Create(&db.ImcLoginAttempt{
Email: identifier,
IPAddress: ip,
Successful: false,
})
}
func clearFailedAttempts(identifier, ip string, database *db.DB) {
database.Model(&db.ImcLoginAttempt{}).
Where("email = ? OR ip_address = ?", identifier, ip).
Update("successful", true)
}
func getClientIP(c *gin.Context) string {
forwarded := c.GetHeader("X-Forwarded-For")
if forwarded != "" {
return strings.Split(forwarded, ",")[0]
}
return c.ClientIP()
}