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,11 +1,10 @@
package handlers
import (
"encoding/json"
"net/http"
"strconv"
"strings"
"github.com/gin-gonic/gin"
"github.com/imc-vibe/backend/internal/db"
)
@ -18,143 +17,115 @@ func NewAliasHandler(database *db.DB) *AliasHandler {
}
type CreateAliasRequest struct {
Source string `json:"source"`
Destination string `json:"destination"`
Source string `json:"source" binding:"required"`
Destination string `json:"destination" binding:"required"`
}
func (h *AliasHandler) List(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
domainName := extractDomainNameFromPath(r.URL.Path)
func (h *AliasHandler) List(c *gin.Context) {
domainName := c.Param("name")
if domainName == "" {
Error(w, http.StatusBadRequest, "domain name required")
Error(c, http.StatusBadRequest, "domain name required")
return
}
authCtx := GetAuthContext(r)
authCtx := GetAuthContext(c)
if authCtx == nil {
Error(w, http.StatusUnauthorized, "authentication required")
Error(c, http.StatusUnauthorized, "authentication required")
return
}
canAccess, _ := h.db.CanAccessDomain(authCtx.UserID, domainName, authCtx.IsAdmin())
if !canAccess {
Error(w, http.StatusForbidden, "access denied")
Error(c, http.StatusForbidden, "access denied")
return
}
domain, err := h.db.GetDomainByName(domainName)
if err != nil {
Error(w, http.StatusNotFound, "domain not found")
Error(c, http.StatusNotFound, "domain not found")
return
}
aliases, err := h.db.GetAliasesByDomain(domain.ID)
if err != nil {
Error(w, http.StatusInternalServerError, "database error")
Error(c, http.StatusInternalServerError, "database error")
return
}
Success(w, aliases)
Success(c, aliases)
}
func (h *AliasHandler) Create(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
domainName := extractDomainNameFromPath(r.URL.Path)
func (h *AliasHandler) Create(c *gin.Context) {
domainName := c.Param("name")
if domainName == "" {
Error(w, http.StatusBadRequest, "domain name required")
Error(c, http.StatusBadRequest, "domain name required")
return
}
authCtx := GetAuthContext(r)
authCtx := GetAuthContext(c)
if authCtx == nil {
Error(w, http.StatusUnauthorized, "authentication required")
Error(c, http.StatusUnauthorized, "authentication required")
return
}
canAccess, _ := h.db.CanAccessDomain(authCtx.UserID, domainName, authCtx.IsAdmin())
if !canAccess {
Error(w, http.StatusForbidden, "access denied")
Error(c, http.StatusForbidden, "access denied")
return
}
domain, err := h.db.GetDomainByName(domainName)
if err != nil {
Error(w, http.StatusNotFound, "domain not found")
Error(c, http.StatusNotFound, "domain not found")
return
}
var req CreateAliasRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
Error(w, http.StatusBadRequest, "invalid request body")
return
}
if req.Source == "" || req.Destination == "" {
Error(w, http.StatusBadRequest, "source and destination required")
if err := c.ShouldBindJSON(&req); err != nil {
Error(c, http.StatusBadRequest, "invalid request body")
return
}
alias, err := h.db.CreateAliasInDomain(req.Source, req.Destination, domain.ID)
if err != nil {
Error(w, http.StatusInternalServerError, "failed to create alias")
Error(c, http.StatusInternalServerError, "failed to create alias")
return
}
Created(w, alias)
Created(c, alias)
}
func (h *AliasHandler) Delete(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodDelete {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
pathParts := strings.Split(r.URL.Path, "/")
var domainName, idStr string
for i, part := range pathParts {
if part == "domains" && i+1 < len(pathParts) {
domainName = pathParts[i+1]
}
if part == "aliases" && i+1 < len(pathParts) {
idStr = pathParts[i+1]
}
}
func (h *AliasHandler) Delete(c *gin.Context) {
domainName := c.Param("name")
idStr := c.Param("id")
if domainName == "" || idStr == "" {
Error(w, http.StatusBadRequest, "invalid path")
Error(c, http.StatusBadRequest, "domain name and alias id required")
return
}
authCtx := GetAuthContext(r)
authCtx := GetAuthContext(c)
if authCtx == nil {
Error(w, http.StatusUnauthorized, "authentication required")
Error(c, http.StatusUnauthorized, "authentication required")
return
}
canAccess, _ := h.db.CanAccessDomain(authCtx.UserID, domainName, authCtx.IsAdmin())
if !canAccess {
Error(w, http.StatusForbidden, "access denied")
Error(c, http.StatusForbidden, "access denied")
return
}
id, err := strconv.ParseUint(idStr, 10, 64)
if err != nil {
Error(w, http.StatusBadRequest, "invalid alias id")
Error(c, http.StatusBadRequest, "invalid alias id")
return
}
if err := h.db.DeleteAlias(uint(id)); err != nil {
Error(w, http.StatusInternalServerError, "failed to delete alias")
Error(c, http.StatusInternalServerError, "failed to delete alias")
return
}
NoContent(w)
NoContent(c)
}

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()
}

View file

@ -1,10 +1,10 @@
package handlers
import (
"encoding/json"
"net/http"
"strings"
"strconv"
"github.com/gin-gonic/gin"
"github.com/imc-vibe/backend/internal/db"
)
@ -17,7 +17,7 @@ func NewDomainHandler(database *db.DB) *DomainHandler {
}
type CreateDomainRequest struct {
Name string `json:"name"`
Name string `json:"name" binding:"required"`
}
type DomainPermissions struct {
@ -27,22 +27,17 @@ type DomainPermissions struct {
CanManage bool `json:"canManage"`
}
func (h *DomainHandler) List(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
authCtx := GetAuthContext(r)
func (h *DomainHandler) List(c *gin.Context) {
authCtx := GetAuthContext(c)
if authCtx == nil {
Error(w, http.StatusUnauthorized, "authentication required")
Error(c, http.StatusUnauthorized, "authentication required")
return
}
isAdmin := authCtx.IsAdmin()
domains, err := h.db.GetUserAccessibleDomains(authCtx.UserID, isAdmin)
if err != nil {
Error(w, http.StatusInternalServerError, "database error")
Error(c, http.StatusInternalServerError, "database error")
return
}
@ -59,144 +54,119 @@ func (h *DomainHandler) List(w http.ResponseWriter, r *http.Request) {
}
}
Success(w, domainStats)
Success(c, domainStats)
}
func (h *DomainHandler) Get(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
domainName := extractDomainName(r.URL.Path)
func (h *DomainHandler) Get(c *gin.Context) {
domainName := c.Param("name")
if domainName == "" {
Error(w, http.StatusBadRequest, "domain name required")
Error(c, http.StatusBadRequest, "domain name required")
return
}
domain, err := h.db.GetDomainByName(domainName)
if err != nil {
Error(w, http.StatusNotFound, "domain not found")
Error(c, http.StatusNotFound, "domain not found")
return
}
authCtx := GetAuthContext(r)
authCtx := GetAuthContext(c)
if authCtx == nil {
Error(w, http.StatusUnauthorized, "authentication required")
Error(c, http.StatusUnauthorized, "authentication required")
return
}
canAccess, _ := h.db.CanAccessDomain(authCtx.UserID, domainName, authCtx.IsAdmin())
if !canAccess {
Error(w, http.StatusForbidden, "access denied")
Error(c, http.StatusForbidden, "access denied")
return
}
Success(w, domain)
Success(c, domain)
}
func (h *DomainHandler) Create(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
authCtx := GetAuthContext(r)
func (h *DomainHandler) Create(c *gin.Context) {
authCtx := GetAuthContext(c)
if authCtx == nil || !authCtx.IsAdmin() {
Error(w, http.StatusForbidden, "admin access required")
Error(c, http.StatusForbidden, "admin access required")
return
}
var req CreateDomainRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
Error(w, http.StatusBadRequest, "invalid request body")
return
}
if req.Name == "" {
Error(w, http.StatusBadRequest, "domain name required")
if err := c.ShouldBindJSON(&req); err != nil {
Error(c, http.StatusBadRequest, "invalid request body")
return
}
existing, err := h.db.GetDomainByName(req.Name)
if err == nil && existing != nil {
Error(w, http.StatusConflict, "domain already exists")
Error(c, http.StatusConflict, "domain already exists")
return
}
domain, err := h.db.CreateDomain(req.Name)
if err != nil {
Error(w, http.StatusInternalServerError, "failed to create domain")
Error(c, http.StatusInternalServerError, "failed to create domain")
return
}
Created(w, domain)
Created(c, domain)
}
func (h *DomainHandler) Delete(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodDelete {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
authCtx := GetAuthContext(r)
func (h *DomainHandler) Delete(c *gin.Context) {
authCtx := GetAuthContext(c)
if authCtx == nil || !authCtx.IsAdmin() {
Error(w, http.StatusForbidden, "admin access required")
Error(c, http.StatusForbidden, "admin access required")
return
}
domainName := extractDomainName(r.URL.Path)
domainName := c.Param("name")
if domainName == "" {
Error(w, http.StatusBadRequest, "domain name required")
Error(c, http.StatusBadRequest, "domain name required")
return
}
domain, err := h.db.GetDomainByName(domainName)
if err != nil {
Error(w, http.StatusNotFound, "domain not found")
Error(c, http.StatusNotFound, "domain not found")
return
}
if err := h.db.DeleteDomain(domain.ID); err != nil {
Error(w, http.StatusInternalServerError, "failed to delete domain")
Error(c, http.StatusInternalServerError, "failed to delete domain")
return
}
NoContent(w)
NoContent(c)
}
func (h *DomainHandler) GetPermissions(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
authCtx := GetAuthContext(r)
func (h *DomainHandler) GetPermissions(c *gin.Context) {
authCtx := GetAuthContext(c)
if authCtx == nil {
Error(w, http.StatusUnauthorized, "authentication required")
Error(c, http.StatusUnauthorized, "authentication required")
return
}
if !authCtx.IsAdmin() {
Error(w, http.StatusForbidden, "admin access required")
Error(c, http.StatusForbidden, "admin access required")
return
}
domainName := extractDomainName(r.URL.Path)
domainName := c.Param("name")
if domainName == "" {
Error(w, http.StatusBadRequest, "domain name required")
Error(c, http.StatusBadRequest, "domain name required")
return
}
domain, err := h.db.GetDomainByName(domainName)
if err != nil {
Error(w, http.StatusNotFound, "domain not found")
Error(c, http.StatusNotFound, "domain not found")
return
}
users, err := h.db.GetUsersForDomain(domain.ID)
if err != nil {
Error(w, http.StatusInternalServerError, "database error")
Error(c, http.StatusInternalServerError, "database error")
return
}
@ -210,107 +180,74 @@ func (h *DomainHandler) GetPermissions(w http.ResponseWriter, r *http.Request) {
}
}
Success(w, permissions)
Success(c, permissions)
}
func (h *DomainHandler) AddPermission(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
authCtx := GetAuthContext(r)
func (h *DomainHandler) AddPermission(c *gin.Context) {
authCtx := GetAuthContext(c)
if authCtx == nil || !authCtx.IsAdmin() {
Error(w, http.StatusForbidden, "admin access required")
Error(c, http.StatusForbidden, "admin access required")
return
}
domainName := extractDomainName(r.URL.Path)
domainName := c.Param("name")
if domainName == "" {
Error(w, http.StatusBadRequest, "domain name required")
Error(c, http.StatusBadRequest, "domain name required")
return
}
domain, err := h.db.GetDomainByName(domainName)
if err != nil {
Error(w, http.StatusNotFound, "domain not found")
Error(c, http.StatusNotFound, "domain not found")
return
}
var req struct {
UserID uint `json:"userId"`
UserID uint `json:"userId" binding:"required"`
}
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
}
if err := h.db.AddUserToDomain(req.UserID, domain.ID); err != nil {
Error(w, http.StatusInternalServerError, "failed to add user to domain")
Error(c, http.StatusInternalServerError, "failed to add user to domain")
return
}
Success(w, map[string]string{"message": "user added to domain"})
Success(c, map[string]string{"message": "user added to domain"})
}
func (h *DomainHandler) RemovePermission(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodDelete {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
authCtx := GetAuthContext(r)
func (h *DomainHandler) RemovePermission(c *gin.Context) {
authCtx := GetAuthContext(c)
if authCtx == nil || !authCtx.IsAdmin() {
Error(w, http.StatusForbidden, "admin access required")
Error(c, http.StatusForbidden, "admin access required")
return
}
domainName := extractDomainName(r.URL.Path)
domainName := c.Param("name")
if domainName == "" {
Error(w, http.StatusBadRequest, "domain name required")
Error(c, http.StatusBadRequest, "domain name required")
return
}
domain, err := h.db.GetDomainByName(domainName)
if err != nil {
Error(w, http.StatusNotFound, "domain not found")
Error(c, http.StatusNotFound, "domain not found")
return
}
userID := extractIDFromPath(r.URL.Path)
if err := h.db.RemoveUserFromDomain(userID, domain.ID); err != nil {
Error(w, http.StatusInternalServerError, "failed to remove user from domain")
userIDStr := c.Param("userId")
userID, err := strconv.ParseUint(userIDStr, 10, 64)
if err != nil {
Error(c, http.StatusBadRequest, "invalid user id")
return
}
NoContent(w)
}
func extractDomainName(path string) string {
parts := strings.Split(strings.TrimPrefix(path, "/api/"), "/")
if len(parts) >= 2 && parts[1] != "" {
return parts[1]
if err := h.db.RemoveUserFromDomain(uint(userID), domain.ID); err != nil {
Error(c, http.StatusInternalServerError, "failed to remove user from domain")
return
}
return ""
}
func extractIDFromPath(path string) uint {
parts := strings.Split(path, "/")
for i := len(parts) - 1; i >= 0; i-- {
if idStr := parts[i]; idStr != "" {
var id uint
for _, c := range idStr {
if c >= '0' && c <= '9' {
id = id*10 + uint(c-'0')
} else {
break
}
}
if id > 0 {
return id
}
}
}
return 0
NoContent(c)
}

View file

@ -4,6 +4,7 @@ import (
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"github.com/imc-vibe/backend/internal/mail"
)
@ -13,26 +14,21 @@ func NewLogsHandler() *LogsHandler {
return &LogsHandler{}
}
func (h *LogsHandler) List(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
func (h *LogsHandler) List(c *gin.Context) {
hours := 1
if h := r.URL.Query().Get("hours"); h != "" {
if h := c.Query("hours"); h != "" {
if n, err := strconv.Atoi(h); err == nil && n > 0 {
hours = n
}
}
filter := r.URL.Query().Get("filter")
filter := c.Query("filter")
entries, err := mail.GetLogs(hours, filter)
if err != nil {
Error(w, http.StatusServiceUnavailable, "log service not available")
Error(c, http.StatusServiceUnavailable, "log service not available")
return
}
Success(w, entries)
Success(c, entries)
}

View file

@ -1,34 +1,32 @@
package handlers
import (
"context"
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/imc-vibe/backend/internal/auth"
)
type contextKey string
const AuthContextKey = "auth"
const AuthContextKey contextKey = "auth"
func AuthMiddleware(jwtManager *auth.JWTManager, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("Authorization")
func AuthMiddleware(jwtManager *auth.JWTManager) gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
http.Error(w, `{"error":"authorization header required"}`, http.StatusUnauthorized)
c.AbortWithStatusJSON(http.StatusUnauthorized, Response{Error: "authorization header required"})
return
}
parts := strings.SplitN(authHeader, " ", 2)
if len(parts) != 2 || strings.ToLower(parts[0]) != "bearer" {
http.Error(w, `{"error":"invalid authorization header format"}`, http.StatusUnauthorized)
c.AbortWithStatusJSON(http.StatusUnauthorized, Response{Error: "invalid authorization header format"})
return
}
claims, err := jwtManager.ValidateToken(parts[1])
if err != nil {
http.Error(w, `{"error":"invalid token"}`, http.StatusUnauthorized)
c.AbortWithStatusJSON(http.StatusUnauthorized, Response{Error: "invalid token"})
return
}
@ -38,13 +36,13 @@ func AuthMiddleware(jwtManager *auth.JWTManager, next http.Handler) http.Handler
Role: auth.Role(claims.Role),
}
ctx := context.WithValue(r.Context(), AuthContextKey, authCtx)
next.ServeHTTP(w, r.WithContext(ctx))
})
c.Set(AuthContextKey, authCtx)
c.Next()
}
}
func GetAuthContext(r *http.Request) *auth.Context {
if ctx := r.Context().Value(AuthContextKey); ctx != nil {
func GetAuthContext(c *gin.Context) *auth.Context {
if ctx, exists := c.Get(AuthContextKey); exists {
if authCtx, ok := ctx.(*auth.Context); ok {
return authCtx
}
@ -52,21 +50,13 @@ func GetAuthContext(r *http.Request) *auth.Context {
return nil
}
func RequireAdmin(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authCtx := GetAuthContext(r)
func RequireAdmin() gin.HandlerFunc {
return func(c *gin.Context) {
authCtx := GetAuthContext(c)
if authCtx == nil || !authCtx.IsAdmin() {
http.Error(w, `{"error":"admin access required"}`, http.StatusForbidden)
c.AbortWithStatusJSON(http.StatusForbidden, Response{Error: "admin access required"})
return
}
next.ServeHTTP(w, r)
})
}
func extractID(path string) string {
parts := strings.Split(path, "/")
if len(parts) > 0 {
return parts[len(parts)-1]
c.Next()
}
return ""
}

View file

@ -4,6 +4,7 @@ import (
"log"
"net/http"
"github.com/gin-gonic/gin"
"github.com/imc-vibe/backend/internal/mail"
)
@ -13,48 +14,33 @@ func NewQueueHandler() *QueueHandler {
return &QueueHandler{}
}
func (h *QueueHandler) List(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
func (h *QueueHandler) List(c *gin.Context) {
entries, err := mail.GetQueue()
if err != nil {
log.Printf("Queue error: %v", err)
Error(w, http.StatusServiceUnavailable, "failed to get queue: "+err.Error())
Error(c, http.StatusServiceUnavailable, "failed to get queue: "+err.Error())
return
}
Success(w, entries)
Success(c, entries)
}
func (h *QueueHandler) Requeue(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
id := extractID(r.URL.Path)
func (h *QueueHandler) Requeue(c *gin.Context) {
id := c.Param("id")
if err := mail.RequeueMail(id); err != nil {
Error(w, http.StatusInternalServerError, "failed to requeue mail")
Error(c, http.StatusInternalServerError, "failed to requeue mail")
return
}
Success(w, map[string]string{"message": "mail requeued"})
Success(c, map[string]string{"message": "mail requeued"})
}
func (h *QueueHandler) Delete(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodDelete {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
id := extractID(r.URL.Path)
func (h *QueueHandler) Delete(c *gin.Context) {
id := c.Param("id")
if err := mail.DeleteFromQueue(id); err != nil {
Error(w, http.StatusInternalServerError, "failed to delete from queue")
Error(c, http.StatusInternalServerError, "failed to delete from queue")
return
}
NoContent(w)
NoContent(c)
}

View file

@ -1,8 +1,7 @@
package handlers
import (
"encoding/json"
"net/http"
"github.com/gin-gonic/gin"
)
type Response struct {
@ -16,26 +15,22 @@ type Meta struct {
Page int `json:"page,omitempty"`
}
func JSON(w http.ResponseWriter, status int, data interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(Response{Data: data})
func JSON(c *gin.Context, status int, data interface{}) {
c.JSON(status, Response{Data: data})
}
func Error(w http.ResponseWriter, status int, message string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(Response{Error: message})
func Error(c *gin.Context, status int, message string) {
c.JSON(status, Response{Error: message})
}
func Success(w http.ResponseWriter, data interface{}) {
JSON(w, http.StatusOK, data)
func Success(c *gin.Context, data interface{}) {
JSON(c, 200, data)
}
func Created(w http.ResponseWriter, data interface{}) {
JSON(w, http.StatusCreated, data)
func Created(c *gin.Context, data interface{}) {
JSON(c, 201, data)
}
func NoContent(w http.ResponseWriter) {
w.WriteHeader(http.StatusNoContent)
func NoContent(c *gin.Context) {
c.Status(204)
}

View file

@ -1,8 +1,7 @@
package handlers
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/imc-vibe/backend/internal/db"
)
@ -21,12 +20,7 @@ type Stats struct {
QueueSize int `json:"queueSize"`
}
func (h *StatsHandler) Get(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
func (h *StatsHandler) Get(c *gin.Context) {
domains, err := h.db.GetAllDomains()
if err != nil {
domains = []db.DomainStats{}
@ -49,5 +43,5 @@ func (h *StatsHandler) Get(w http.ResponseWriter, r *http.Request) {
QueueSize: 0,
}
Success(w, stats)
Success(c, stats)
}

View file

@ -1,12 +1,10 @@
package handlers
import (
"encoding/json"
"net/http"
"strconv"
"strings"
"github.com/imc-vibe/backend/internal/auth"
"github.com/gin-gonic/gin"
"github.com/imc-vibe/backend/internal/db"
)
@ -19,8 +17,8 @@ func NewUserHandler(database *db.DB) *UserHandler {
}
type CreateUserRequest struct {
Email string `json:"email"`
Password string `json:"password"`
Email string `json:"email" binding:"required"`
Password string `json:"password" binding:"required"`
Quota int64 `json:"quota"`
}
@ -29,130 +27,110 @@ type UpdateUserRequest struct {
Quota int64 `json:"quota,omitempty"`
}
func (h *UserHandler) List(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
domainName := extractDomainNameFromPath(r.URL.Path)
func (h *UserHandler) List(c *gin.Context) {
domainName := c.Param("name")
if domainName == "" {
Error(w, http.StatusBadRequest, "domain name required")
Error(c, http.StatusBadRequest, "domain name required")
return
}
authCtx := GetAuthContext(r)
authCtx := GetAuthContext(c)
if authCtx == nil {
Error(w, http.StatusUnauthorized, "authentication required")
Error(c, http.StatusUnauthorized, "authentication required")
return
}
canAccess, _ := h.db.CanAccessDomain(authCtx.UserID, domainName, authCtx.IsAdmin())
if !canAccess {
Error(w, http.StatusForbidden, "access denied")
Error(c, http.StatusForbidden, "access denied")
return
}
domain, err := h.db.GetDomainByName(domainName)
if err != nil {
Error(w, http.StatusNotFound, "domain not found")
Error(c, http.StatusNotFound, "domain not found")
return
}
users, err := h.db.GetUsersByDomain(domain.ID)
if err != nil {
Error(w, http.StatusInternalServerError, "database error")
Error(c, http.StatusInternalServerError, "database error")
return
}
Success(w, users)
Success(c, users)
}
func (h *UserHandler) Get(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
func (h *UserHandler) Get(c *gin.Context) {
domainName := c.Param("name")
idStr := c.Param("id")
if domainName == "" || idStr == "" {
Error(c, http.StatusBadRequest, "domain name and user id required")
return
}
parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/api/domains/"), "/")
if len(parts) < 4 {
Error(w, http.StatusBadRequest, "invalid path")
return
}
domainName := parts[0]
authCtx := GetAuthContext(r)
authCtx := GetAuthContext(c)
if authCtx == nil {
Error(w, http.StatusUnauthorized, "authentication required")
Error(c, http.StatusUnauthorized, "authentication required")
return
}
canAccess, _ := h.db.CanAccessDomain(authCtx.UserID, domainName, authCtx.IsAdmin())
if !canAccess {
Error(w, http.StatusForbidden, "access denied")
Error(c, http.StatusForbidden, "access denied")
return
}
idStr := parts[3]
id, err := strconv.ParseUint(idStr, 10, 64)
if err != nil {
Error(w, http.StatusBadRequest, "invalid user id")
Error(c, http.StatusBadRequest, "invalid user id")
return
}
user, err := h.db.GetUserByID(uint(id))
if err != nil {
Error(w, http.StatusNotFound, "user not found")
Error(c, http.StatusNotFound, "user not found")
return
}
Success(w, user)
Success(c, user)
}
func (h *UserHandler) Create(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
domainName := extractDomainNameFromPath(r.URL.Path)
func (h *UserHandler) Create(c *gin.Context) {
domainName := c.Param("name")
if domainName == "" {
Error(w, http.StatusBadRequest, "domain name required")
Error(c, http.StatusBadRequest, "domain name required")
return
}
authCtx := GetAuthContext(r)
authCtx := GetAuthContext(c)
if authCtx == nil {
Error(w, http.StatusUnauthorized, "authentication required")
Error(c, http.StatusUnauthorized, "authentication required")
return
}
canAccess, _ := h.db.CanAccessDomain(authCtx.UserID, domainName, authCtx.IsAdmin())
if !canAccess {
Error(w, http.StatusForbidden, "access denied")
Error(c, http.StatusForbidden, "access denied")
return
}
domain, err := h.db.GetDomainByName(domainName)
if err != nil {
Error(w, http.StatusNotFound, "domain not found")
Error(c, http.StatusNotFound, "domain not found")
return
}
var req CreateUserRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
Error(w, http.StatusBadRequest, "invalid request body")
return
}
if req.Email == "" || req.Password == "" {
Error(w, http.StatusBadRequest, "email and password required")
if err := c.ShouldBindJSON(&req); err != nil {
Error(c, http.StatusBadRequest, "invalid request body")
return
}
existing, _ := h.db.GetUserByEmail(req.Email)
if existing != nil {
Error(w, http.StatusConflict, "user already exists")
Error(c, http.StatusConflict, "user already exists")
return
}
@ -160,145 +138,117 @@ func (h *UserHandler) Create(w http.ResponseWriter, r *http.Request) {
user, err := h.db.CreateUserInDomain(req.Email, passwordHash, req.Quota, domain.ID)
if err != nil {
Error(w, http.StatusInternalServerError, "failed to create user")
Error(c, http.StatusInternalServerError, "failed to create user")
return
}
Created(w, user)
Created(c, user)
}
func (h *UserHandler) Update(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPut {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
func (h *UserHandler) Update(c *gin.Context) {
domainName := c.Param("name")
idStr := c.Param("id")
if domainName == "" || idStr == "" {
Error(c, http.StatusBadRequest, "domain name and user id required")
return
}
parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/api/domains/"), "/")
if len(parts) < 4 {
Error(w, http.StatusBadRequest, "invalid path")
return
}
domainName := parts[0]
authCtx := GetAuthContext(r)
authCtx := GetAuthContext(c)
if authCtx == nil {
Error(w, http.StatusUnauthorized, "authentication required")
Error(c, http.StatusUnauthorized, "authentication required")
return
}
canAccess, _ := h.db.CanAccessDomain(authCtx.UserID, domainName, authCtx.IsAdmin())
if !canAccess {
Error(w, http.StatusForbidden, "access denied")
Error(c, http.StatusForbidden, "access denied")
return
}
idStr := parts[3]
id, err := strconv.ParseUint(idStr, 10, 64)
if err != nil {
Error(w, http.StatusBadRequest, "invalid user id")
Error(c, http.StatusBadRequest, "invalid user id")
return
}
user, err := h.db.GetUserByID(uint(id))
if err != nil {
Error(w, http.StatusNotFound, "user not found")
Error(c, http.StatusNotFound, "user not found")
return
}
var req UpdateUserRequest
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")
return
}
if req.Password != "" {
passwordHash := "{BLF-CRYPT}" + req.Password
if err := h.db.UpdateUserPassword(user.ID, passwordHash); err != nil {
Error(w, http.StatusInternalServerError, "failed to update password")
Error(c, http.StatusInternalServerError, "failed to update password")
return
}
}
if req.Quota >= 0 {
if err := h.db.UpdateUserQuota(user.ID, req.Quota); err != nil {
Error(w, http.StatusInternalServerError, "failed to update quota")
Error(c, http.StatusInternalServerError, "failed to update quota")
return
}
}
Success(w, map[string]string{"message": "user updated"})
Success(c, map[string]string{"message": "user updated"})
}
func (h *UserHandler) Delete(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodDelete {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
func (h *UserHandler) Delete(c *gin.Context) {
domainName := c.Param("name")
idStr := c.Param("id")
if domainName == "" || idStr == "" {
Error(c, http.StatusBadRequest, "domain name and user id required")
return
}
parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/api/domains/"), "/")
if len(parts) < 4 {
Error(w, http.StatusBadRequest, "invalid path")
return
}
domainName := parts[0]
authCtx := GetAuthContext(r)
authCtx := GetAuthContext(c)
if authCtx == nil {
Error(w, http.StatusUnauthorized, "authentication required")
Error(c, http.StatusUnauthorized, "authentication required")
return
}
canAccess, _ := h.db.CanAccessDomain(authCtx.UserID, domainName, authCtx.IsAdmin())
if !canAccess {
Error(w, http.StatusForbidden, "access denied")
Error(c, http.StatusForbidden, "access denied")
return
}
idStr := parts[3]
id, err := strconv.ParseUint(idStr, 10, 64)
if err != nil {
Error(w, http.StatusBadRequest, "invalid user id")
Error(c, http.StatusBadRequest, "invalid user id")
return
}
if err := h.db.DeleteUser(uint(id)); err != nil {
Error(w, http.StatusInternalServerError, "failed to delete user")
Error(c, http.StatusInternalServerError, "failed to delete user")
return
}
NoContent(w)
NoContent(c)
}
func (h *UserHandler) ListAll(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
authCtx := GetAuthContext(r)
func (h *UserHandler) ListAll(c *gin.Context) {
authCtx := GetAuthContext(c)
if authCtx == nil || !authCtx.IsAdmin() {
Error(w, http.StatusForbidden, "admin access required")
Error(c, http.StatusForbidden, "admin access required")
return
}
users, err := h.db.GetAllMailUsers()
if err != nil {
Error(w, http.StatusInternalServerError, "database error")
Error(c, http.StatusInternalServerError, "database error")
return
}
Success(w, users)
Success(c, users)
}
func extractDomainNameFromPath(path string) string {
parts := strings.Split(strings.TrimPrefix(path, "/api/"), "/")
if len(parts) >= 2 && parts[0] == "domains" && parts[1] != "" {
if idx := strings.Index(parts[1], "/"); idx > 0 {
return parts[1][:idx]
}
return parts[1]
}
return ""
}
var _ = auth.RoleAdmin