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
This commit is contained in:
Christoph Haas 2026-03-22 23:28:28 +01:00
parent 68285d861a
commit 2834657125
13 changed files with 474 additions and 812 deletions

View file

@ -1,12 +1,12 @@
package handlers
import (
"encoding/json"
"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"
@ -29,17 +29,17 @@ func NewAuthHandler(database *db.DB, jwtManager *auth.JWTManager, emailService *
}
type LoginRequest struct {
Username string `json:"username"`
Password string `json:"password"`
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required"`
}
type ChangePasswordRequest struct {
OldPassword string `json:"oldPassword"`
NewPassword string `json:"newPassword"`
OldPassword string `json:"oldPassword" binding:"required"`
NewPassword string `json:"newPassword" binding:"required,min=8"`
}
type ForgotPasswordRequest struct {
Identifier string `json:"identifier"`
Identifier string `json:"identifier" binding:"required"`
}
type UserResponse struct {
@ -49,34 +49,24 @@ type UserResponse struct {
Domains []string `json:"domains"`
}
func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
func (h *AuthHandler) Login(c *gin.Context) {
var req LoginRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
Error(w, http.StatusBadRequest, "invalid request body")
if err := c.ShouldBindJSON(&req); err != nil {
Error(c, http.StatusBadRequest, "invalid request body")
return
}
if req.Username == "" || req.Password == "" {
Error(w, http.StatusBadRequest, "username and password required")
return
}
ip := getClientIP(r)
ip := getClientIP(c)
if isLockedOut(ip, req.Username, h.db) {
Error(w, http.StatusTooManyRequests, "too many failed attempts, try again later")
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(w, http.StatusUnauthorized, "invalid credentials")
Error(c, http.StatusUnauthorized, "invalid credentials")
return
}
@ -91,11 +81,11 @@ func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request) {
token, err := h.jwtManager.GenerateToken(user.ID, user.Username, user.Role, 24*time.Hour)
if err != nil {
Error(w, http.StatusInternalServerError, "failed to generate token")
Error(c, http.StatusInternalServerError, "failed to generate token")
return
}
Success(w, map[string]interface{}{
Success(c, map[string]interface{}{
"token": token,
"user": UserResponse{
ID: user.ID,
@ -106,21 +96,16 @@ func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request) {
})
}
func (h *AuthHandler) Me(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
authCtx := GetAuthContext(r)
func (h *AuthHandler) Me(c *gin.Context) {
authCtx := GetAuthContext(c)
if authCtx == nil {
Error(w, http.StatusUnauthorized, "not authenticated")
Error(c, http.StatusUnauthorized, "not authenticated")
return
}
user, err := h.db.GetImcUserByID(authCtx.UserID)
if err != nil || user == nil {
Error(w, http.StatusNotFound, "user not found")
Error(c, http.StatusNotFound, "user not found")
return
}
@ -131,7 +116,7 @@ func (h *AuthHandler) Me(w http.ResponseWriter, r *http.Request) {
domainNames[i] = d.Name
}
Success(w, UserResponse{
Success(c, UserResponse{
ID: user.ID,
Username: user.Username,
Role: user.Role,
@ -139,27 +124,22 @@ func (h *AuthHandler) Me(w http.ResponseWriter, r *http.Request) {
})
}
func (h *AuthHandler) ForgotPassword(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
func (h *AuthHandler) ForgotPassword(c *gin.Context) {
var req ForgotPasswordRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
Error(w, http.StatusBadRequest, "invalid request")
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(w, http.StatusBadRequest, "identifier required")
Error(c, http.StatusBadRequest, "identifier required")
return
}
user, err := h.db.GetImcUserByUsername(req.Identifier)
if err != nil {
Success(w, map[string]string{
Success(c, map[string]string{
"message": "If the account exists, a password reset link will be sent",
})
return
@ -170,77 +150,62 @@ func (h *AuthHandler) ForgotPassword(w http.ResponseWriter, r *http.Request) {
if err := h.db.CreatePasswordResetToken(user.ID, token, expiresAt); err != nil {
log.Printf("Failed to create password reset token: %v", err)
Error(w, http.StatusInternalServerError, "failed to create reset token")
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(w, http.StatusInternalServerError, "failed to send email")
Error(c, http.StatusInternalServerError, "failed to send email")
return
}
Success(w, map[string]string{
Success(c, map[string]string{
"message": "If the account exists, a password reset link will be sent",
})
}
func (h *AuthHandler) ChangePassword(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
authCtx := GetAuthContext(r)
func (h *AuthHandler) ChangePassword(c *gin.Context) {
authCtx := GetAuthContext(c)
if authCtx == nil {
Error(w, http.StatusUnauthorized, "authentication required")
Error(c, http.StatusUnauthorized, "authentication required")
return
}
var req ChangePasswordRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
Error(w, http.StatusBadRequest, "invalid request")
return
}
if req.OldPassword == "" || req.NewPassword == "" {
Error(w, http.StatusBadRequest, "old and new password required")
return
}
if len(req.NewPassword) < 8 {
Error(w, http.StatusBadRequest, "password must be at least 8 characters")
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(w, http.StatusNotFound, "user not found")
Error(c, http.StatusNotFound, "user not found")
return
}
if !auth.CheckPassword(req.OldPassword, user.PasswordHash) {
Error(w, http.StatusUnauthorized, "current password is incorrect")
Error(c, http.StatusUnauthorized, "current password is incorrect")
return
}
newHash, err := auth.HashPassword(req.NewPassword)
if err != nil {
Error(w, http.StatusInternalServerError, "failed to hash password")
Error(c, http.StatusInternalServerError, "failed to hash password")
return
}
err = h.db.UpdateImcUserPassword(user.ID, newHash)
if err != nil {
Error(w, http.StatusInternalServerError, "failed to update password")
Error(c, http.StatusInternalServerError, "failed to update password")
return
}
Success(w, map[string]string{"message": "password updated successfully"})
Success(c, map[string]string{"message": "password updated successfully"})
}
func (h *AuthHandler) Logout(w http.ResponseWriter, r *http.Request) {
Success(w, map[string]string{"message": "logged out"})
func (h *AuthHandler) Logout(c *gin.Context) {
Success(c, map[string]string{"message": "logged out"})
}
func isLockedOut(ip, identifier string, database *db.DB) bool {
@ -276,13 +241,10 @@ func clearFailedAttempts(identifier, ip string, database *db.DB) {
Update("successful", true)
}
func getClientIP(r *http.Request) string {
forwarded := r.Header.Get("X-Forwarded-For")
func getClientIP(c *gin.Context) string {
forwarded := c.GetHeader("X-Forwarded-For")
if forwarded != "" {
return strings.Split(forwarded, ",")[0]
}
if idx := strings.LastIndex(r.RemoteAddr, ":"); idx != -1 {
return r.RemoteAddr[:idx]
}
return r.RemoteAddr
return c.ClientIP()
}