Complete GORM to sqlc migration
- Remove GORM dependency, use sqlc for type-safe SQL queries - Update all handlers to use sqlc patterns (context, value types) - Fix N+1 query problem in domain listing with JOIN query - Enable SQL query logging in debug mode (USE_EMBEDDED=false) - Add comprehensive comments for non-Go developers
This commit is contained in:
parent
dad96978e0
commit
c4e3a31b69
9 changed files with 94 additions and 97 deletions
|
|
@ -1,7 +1,6 @@
|
|||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
|
|
|||
|
|
@ -49,8 +49,6 @@ func (h *AuthHandler) Login(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
ip := h.getClientIP(c)
|
||||
|
||||
user, err := h.db.GetImcUserByUsername(c.Request.Context(), req.Username)
|
||||
if err != nil || !auth.CheckPassword(req.Password, user.PasswordHash) {
|
||||
Error(c, http.StatusUnauthorized, "invalid credentials")
|
||||
|
|
|
|||
|
|
@ -1,9 +1,6 @@
|
|||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strconv"
|
||||
|
|
@ -33,15 +30,10 @@ func (h *DomainHandler) List(c *gin.Context) {
|
|||
}
|
||||
|
||||
isAdmin := authCtx.IsAdmin()
|
||||
domains, err := h.db.GetUserAccessibleDomains(c.Request.Context(), authCtx.UserID, isAdmin)
|
||||
if err != nil {
|
||||
Error(c, http.StatusInternalServerError, "database error")
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
|
||||
// If admin, use optimized single-query method.
|
||||
if isAdmin {
|
||||
domainStats, err := h.db.GetAllDomainsWithCounts(c.Request.Context())
|
||||
domainStats, err := h.db.GetAllDomainsWithCounts(ctx)
|
||||
if err != nil {
|
||||
Error(c, http.StatusInternalServerError, "database error")
|
||||
return
|
||||
|
|
@ -50,11 +42,16 @@ func (h *DomainHandler) List(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
// For non-admins, build stats from their accessible domains.
|
||||
domains, err := h.db.GetUserAccessibleDomains(ctx, uint32(authCtx.UserID), isAdmin)
|
||||
if err != nil {
|
||||
Error(c, http.StatusInternalServerError, "database error")
|
||||
return
|
||||
}
|
||||
|
||||
domainStats := make([]db.DomainStats, len(domains))
|
||||
for i, d := range domains {
|
||||
userCount, _ := h.db.CountUsersByDomain(c.Request.Context(), d.ID)
|
||||
aliasCount, _ := h.db.CountAliasesByDomain(c.Request.Context(), d.ID)
|
||||
userCount, _ := h.db.CountUsersByDomain(ctx, d.ID)
|
||||
aliasCount, _ := h.db.CountAliasesByDomain(ctx, d.ID)
|
||||
domainStats[i] = db.DomainStats{
|
||||
ID: d.ID,
|
||||
Name: d.Name,
|
||||
|
|
@ -73,7 +70,8 @@ func (h *DomainHandler) Get(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
domain, err := h.db.GetDomainByName(c.Request.Context(), domainName)
|
||||
ctx := c.Request.Context()
|
||||
domain, err := h.db.GetDomainByName(ctx, domainName)
|
||||
if err != nil {
|
||||
Error(c, http.StatusNotFound, "domain not found")
|
||||
return
|
||||
|
|
@ -85,7 +83,7 @@ func (h *DomainHandler) Get(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
canAccess, _ := h.db.CanAccessDomain(authCtx.UserID, domainName, authCtx.IsAdmin())
|
||||
canAccess, _ := h.db.CanAccessDomain(ctx, uint32(authCtx.UserID), domainName, authCtx.IsAdmin())
|
||||
if !canAccess {
|
||||
Error(c, http.StatusForbidden, "access denied")
|
||||
return
|
||||
|
|
@ -113,19 +111,20 @@ func (h *DomainHandler) Create(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
existing, err := h.db.GetDomainByName(name)
|
||||
if err == nil && existing != nil {
|
||||
ctx := c.Request.Context()
|
||||
_, err := h.db.GetDomainByName(ctx, name)
|
||||
if err == nil {
|
||||
Error(c, http.StatusConflict, "domain already exists")
|
||||
return
|
||||
}
|
||||
|
||||
domain, err := h.db.CreateDomain(name)
|
||||
err = h.db.CreateDomain(ctx, name)
|
||||
if err != nil {
|
||||
Error(c, http.StatusInternalServerError, "failed to create domain")
|
||||
return
|
||||
}
|
||||
|
||||
Created(c, domain)
|
||||
Created(c, map[string]string{"message": "domain created"})
|
||||
}
|
||||
|
||||
func validateDomainName(name string) error {
|
||||
|
|
@ -181,13 +180,15 @@ func (h *DomainHandler) Delete(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
domain, err := h.db.GetDomainByName(domainName)
|
||||
ctx := c.Request.Context()
|
||||
domain, err := h.db.GetDomainByName(ctx, domainName)
|
||||
if err != nil {
|
||||
Error(c, http.StatusNotFound, "domain not found")
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.db.DeleteDomain(domain.ID); err != nil {
|
||||
err = h.db.DeleteDomain(ctx, domain.ID)
|
||||
if err != nil {
|
||||
Error(c, http.StatusInternalServerError, "failed to delete domain")
|
||||
return
|
||||
}
|
||||
|
|
@ -196,20 +197,15 @@ func (h *DomainHandler) Delete(c *gin.Context) {
|
|||
}
|
||||
|
||||
type DomainPermissions struct {
|
||||
DomainID uint `json:"domainId"`
|
||||
DomainID uint32 `json:"domainId"`
|
||||
DomainName string `json:"domainName"`
|
||||
UserID uint `json:"userId"`
|
||||
UserID uint32 `json:"userId"`
|
||||
CanManage bool `json:"canManage"`
|
||||
}
|
||||
|
||||
func (h *DomainHandler) GetPermissions(c *gin.Context) {
|
||||
authCtx := GetAuthContext(c)
|
||||
if authCtx == nil {
|
||||
Error(c, http.StatusUnauthorized, "authentication required")
|
||||
return
|
||||
}
|
||||
|
||||
if !authCtx.IsAdmin() {
|
||||
if authCtx == nil || !authCtx.IsAdmin() {
|
||||
Error(c, http.StatusForbidden, "admin access required")
|
||||
return
|
||||
}
|
||||
|
|
@ -220,13 +216,14 @@ func (h *DomainHandler) GetPermissions(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
domain, err := h.db.GetDomainByName(domainName)
|
||||
ctx := c.Request.Context()
|
||||
domain, err := h.db.GetDomainByName(ctx, domainName)
|
||||
if err != nil {
|
||||
Error(c, http.StatusNotFound, "domain not found")
|
||||
return
|
||||
}
|
||||
|
||||
users, err := h.db.GetUsersForDomain(domain.ID)
|
||||
users, err := h.db.GetUsersForDomain(ctx, domain.ID)
|
||||
if err != nil {
|
||||
Error(c, http.StatusInternalServerError, "database error")
|
||||
return
|
||||
|
|
@ -258,21 +255,23 @@ func (h *DomainHandler) AddPermission(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
domain, err := h.db.GetDomainByName(domainName)
|
||||
ctx := c.Request.Context()
|
||||
domain, err := h.db.GetDomainByName(ctx, domainName)
|
||||
if err != nil {
|
||||
Error(c, http.StatusNotFound, "domain not found")
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
UserID uint `json:"userId" binding:"required"`
|
||||
UserID uint32 `json:"userId" binding:"required"`
|
||||
}
|
||||
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 {
|
||||
err = h.db.AddUserToDomain(ctx, req.UserID, domain.ID)
|
||||
if err != nil {
|
||||
Error(c, http.StatusInternalServerError, "failed to add user to domain")
|
||||
return
|
||||
}
|
||||
|
|
@ -293,7 +292,8 @@ func (h *DomainHandler) RemovePermission(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
domain, err := h.db.GetDomainByName(domainName)
|
||||
ctx := c.Request.Context()
|
||||
domain, err := h.db.GetDomainByName(ctx, domainName)
|
||||
if err != nil {
|
||||
Error(c, http.StatusNotFound, "domain not found")
|
||||
return
|
||||
|
|
@ -306,7 +306,8 @@ func (h *DomainHandler) RemovePermission(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
if err := h.db.RemoveUserFromDomain(uint(userID), domain.ID); err != nil {
|
||||
err = h.db.RemoveUserFromDomain(ctx, uint32(userID), domain.ID)
|
||||
if err != nil {
|
||||
Error(c, http.StatusInternalServerError, "failed to remove user from domain")
|
||||
return
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,19 +21,21 @@ type Stats struct {
|
|||
}
|
||||
|
||||
func (h *StatsHandler) Get(c *gin.Context) {
|
||||
domains, err := h.db.GetAllDomains()
|
||||
ctx := c.Request.Context()
|
||||
|
||||
domains, err := h.db.GetAllDomains(ctx)
|
||||
if err != nil {
|
||||
domains = []db.DomainStats{}
|
||||
domains = nil
|
||||
}
|
||||
|
||||
users, err := h.db.GetAllMailUsers()
|
||||
users, err := h.db.GetAllMailUsers(ctx)
|
||||
if err != nil {
|
||||
users = []db.VirtualUser{}
|
||||
users = nil
|
||||
}
|
||||
|
||||
aliases, err := h.db.GetAllAliases()
|
||||
aliases, err := h.db.GetAllAliases(ctx)
|
||||
if err != nil {
|
||||
aliases = []db.AliasWithDomain{}
|
||||
aliases = nil
|
||||
}
|
||||
|
||||
stats := Stats{
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ type UpdateUserRequest struct {
|
|||
}
|
||||
|
||||
type UserWithQuota struct {
|
||||
ID uint `json:"id"`
|
||||
ID uint32 `json:"id"`
|
||||
Email string `json:"email"`
|
||||
Quota int64 `json:"quota"`
|
||||
UsedQuota *int64 `json:"usedQuota"`
|
||||
|
|
@ -51,19 +51,20 @@ func (h *UserHandler) List(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
canAccess, _ := h.db.CanAccessDomain(authCtx.UserID, domainName, authCtx.IsAdmin())
|
||||
ctx := c.Request.Context()
|
||||
canAccess, _ := h.db.CanAccessDomain(ctx, uint32(authCtx.UserID), domainName, authCtx.IsAdmin())
|
||||
if !canAccess {
|
||||
Error(c, http.StatusForbidden, "access denied")
|
||||
return
|
||||
}
|
||||
|
||||
domain, err := h.db.GetDomainByName(domainName)
|
||||
domain, err := h.db.GetDomainByName(ctx, domainName)
|
||||
if err != nil {
|
||||
Error(c, http.StatusNotFound, "domain not found")
|
||||
return
|
||||
}
|
||||
|
||||
users, err := h.db.GetUsersByDomain(domain.ID)
|
||||
users, err := h.db.GetUsersByDomain(ctx, domain.ID)
|
||||
if err != nil {
|
||||
Error(c, http.StatusInternalServerError, "database error")
|
||||
return
|
||||
|
|
@ -71,16 +72,17 @@ func (h *UserHandler) List(c *gin.Context) {
|
|||
|
||||
result := make([]UserWithQuota, len(users))
|
||||
for i, user := range users {
|
||||
quota := user.Quota.Int64
|
||||
result[i] = UserWithQuota{
|
||||
ID: user.ID,
|
||||
Email: user.Email,
|
||||
Quota: user.Quota,
|
||||
Quota: quota,
|
||||
}
|
||||
|
||||
quota, err := mail.GetQuota(user.Email)
|
||||
if err == nil && quota != nil {
|
||||
result[i].Quota = quota.Limit
|
||||
result[i].UsedQuota = "a.Used
|
||||
mailQuota, err := mail.GetQuota(user.Email)
|
||||
if err == nil && mailQuota != nil {
|
||||
result[i].Quota = mailQuota.Limit
|
||||
result[i].UsedQuota = &mailQuota.Used
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -102,7 +104,8 @@ func (h *UserHandler) Get(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
canAccess, _ := h.db.CanAccessDomain(authCtx.UserID, domainName, authCtx.IsAdmin())
|
||||
ctx := c.Request.Context()
|
||||
canAccess, _ := h.db.CanAccessDomain(ctx, uint32(authCtx.UserID), domainName, authCtx.IsAdmin())
|
||||
if !canAccess {
|
||||
Error(c, http.StatusForbidden, "access denied")
|
||||
return
|
||||
|
|
@ -114,7 +117,7 @@ func (h *UserHandler) Get(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
user, err := h.db.GetUserByID(uint(id))
|
||||
user, err := h.db.GetUserByID(ctx, uint32(id))
|
||||
if err != nil {
|
||||
Error(c, http.StatusNotFound, "user not found")
|
||||
return
|
||||
|
|
@ -136,13 +139,14 @@ func (h *UserHandler) Create(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
canAccess, _ := h.db.CanAccessDomain(authCtx.UserID, domainName, authCtx.IsAdmin())
|
||||
ctx := c.Request.Context()
|
||||
canAccess, _ := h.db.CanAccessDomain(ctx, uint32(authCtx.UserID), domainName, authCtx.IsAdmin())
|
||||
if !canAccess {
|
||||
Error(c, http.StatusForbidden, "access denied")
|
||||
return
|
||||
}
|
||||
|
||||
domain, err := h.db.GetDomainByName(domainName)
|
||||
domain, err := h.db.GetDomainByName(ctx, domainName)
|
||||
if err != nil {
|
||||
Error(c, http.StatusNotFound, "domain not found")
|
||||
return
|
||||
|
|
@ -154,28 +158,27 @@ func (h *UserHandler) Create(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
// Validate email local part (before @)
|
||||
if err := validateEmailLocalPart(req.Email); err != nil {
|
||||
Error(c, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
existing, _ := h.db.GetUserByEmail(req.Email)
|
||||
if existing != nil {
|
||||
_, err = h.db.GetUserByEmail(ctx, req.Email)
|
||||
if err == nil {
|
||||
Error(c, http.StatusConflict, "user already exists")
|
||||
return
|
||||
}
|
||||
|
||||
passwordHash := "{BLF-CRYPT}" + req.Password
|
||||
|
||||
user, err := h.db.CreateUserInDomain(req.Email, passwordHash, req.Quota, domain.ID)
|
||||
err = h.db.CreateUser(ctx, domain.ID, req.Email, passwordHash, req.Quota)
|
||||
if err != nil {
|
||||
log.Printf("CreateUserInDomain error: email=%s, domain=%s, err=%v", req.Email, domainName, err)
|
||||
log.Printf("CreateUser error: email=%s, domain=%s, err=%v", req.Email, domainName, err)
|
||||
Error(c, http.StatusInternalServerError, "failed to create user")
|
||||
return
|
||||
}
|
||||
|
||||
Created(c, user)
|
||||
Created(c, map[string]string{"message": "user created"})
|
||||
}
|
||||
|
||||
func (h *UserHandler) Update(c *gin.Context) {
|
||||
|
|
@ -193,7 +196,8 @@ func (h *UserHandler) Update(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
canAccess, _ := h.db.CanAccessDomain(authCtx.UserID, domainName, authCtx.IsAdmin())
|
||||
ctx := c.Request.Context()
|
||||
canAccess, _ := h.db.CanAccessDomain(ctx, uint32(authCtx.UserID), domainName, authCtx.IsAdmin())
|
||||
if !canAccess {
|
||||
Error(c, http.StatusForbidden, "access denied")
|
||||
return
|
||||
|
|
@ -205,7 +209,7 @@ func (h *UserHandler) Update(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
user, err := h.db.GetUserByID(uint(id))
|
||||
user, err := h.db.GetUserByID(ctx, uint32(id))
|
||||
if err != nil {
|
||||
Error(c, http.StatusNotFound, "user not found")
|
||||
return
|
||||
|
|
@ -219,14 +223,14 @@ func (h *UserHandler) Update(c *gin.Context) {
|
|||
|
||||
if req.Password != "" {
|
||||
passwordHash := "{BLF-CRYPT}" + req.Password
|
||||
if err := h.db.UpdateUserPassword(user.ID, passwordHash); err != nil {
|
||||
if err := h.db.UpdateUserPassword(ctx, user.ID, passwordHash); err != nil {
|
||||
Error(c, http.StatusInternalServerError, "failed to update password")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if req.Quota >= 0 {
|
||||
if err := h.db.UpdateUserQuota(user.ID, req.Quota); err != nil {
|
||||
if err := h.db.UpdateUserQuota(ctx, user.ID, req.Quota); err != nil {
|
||||
Error(c, http.StatusInternalServerError, "failed to update quota")
|
||||
return
|
||||
}
|
||||
|
|
@ -250,7 +254,8 @@ func (h *UserHandler) Delete(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
canAccess, _ := h.db.CanAccessDomain(authCtx.UserID, domainName, authCtx.IsAdmin())
|
||||
ctx := c.Request.Context()
|
||||
canAccess, _ := h.db.CanAccessDomain(ctx, uint32(authCtx.UserID), domainName, authCtx.IsAdmin())
|
||||
if !canAccess {
|
||||
Error(c, http.StatusForbidden, "access denied")
|
||||
return
|
||||
|
|
@ -262,7 +267,8 @@ func (h *UserHandler) Delete(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
if err := h.db.DeleteUser(uint(id)); err != nil {
|
||||
err = h.db.DeleteUser(ctx, uint32(id))
|
||||
if err != nil {
|
||||
Error(c, http.StatusInternalServerError, "failed to delete user")
|
||||
return
|
||||
}
|
||||
|
|
@ -283,17 +289,14 @@ func validateEmailLocalPart(email string) error {
|
|||
return &ValidationError{Message: "username must be between 1 and 64 characters"}
|
||||
}
|
||||
|
||||
// RFC 5321: local-part cannot start or end with a dot
|
||||
if strings.HasPrefix(localPart, ".") || strings.HasSuffix(localPart, ".") {
|
||||
return &ValidationError{Message: "username cannot start or end with a dot"}
|
||||
}
|
||||
|
||||
// RFC 5321: local-part cannot contain consecutive dots
|
||||
if strings.Contains(localPart, "..") {
|
||||
return &ValidationError{Message: "username cannot contain consecutive dots"}
|
||||
}
|
||||
|
||||
// Check valid characters (RFC 5321: letters, digits, and special chars !#$%&'*+/=?^_`{|}~-)
|
||||
if !emailLocalPartRegex.MatchString(localPart) {
|
||||
return &ValidationError{Message: "username contains invalid characters"}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue