mirror of
https://github.com/limitcool/starter.git
synced 2025-10-18 06:00:36 +08:00
Refactor user handler and middleware for improved error handling and logging
- Consolidated user ID retrieval and permission checks into helper functions. - Updated UserHandler to utilize BaseHandler for common database and configuration access. - Enhanced logging for user-related operations, including login, registration, and password changes. - Removed redundant context handling in middleware and improved readability. - Introduced FileUtil for file URL generation and management, encapsulating file-related logic. - Refactored FileRepo and UserRepo to streamline database operations and error handling. - Deleted unused request_id middleware and integrated its functionality into request_logger. - Removed legacy test runner script to simplify testing process.
This commit is contained in:
@@ -4,6 +4,9 @@ import (
|
||||
"fmt"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/limitcool/starter/internal/api/response"
|
||||
"github.com/limitcool/starter/internal/pkg/errorx"
|
||||
"github.com/limitcool/starter/internal/pkg/logger"
|
||||
)
|
||||
|
||||
// GetUserID 从上下文中获取用户ID
|
||||
@@ -64,3 +67,39 @@ func GetUserIDString(c *gin.Context) string {
|
||||
}
|
||||
return fmt.Sprintf("%d", id)
|
||||
}
|
||||
|
||||
// CheckUserLogin 检查用户是否已登录,如果未登录则返回错误响应
|
||||
func CheckUserLogin(c *gin.Context) bool {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
_, exists := c.Get("user_id")
|
||||
if !exists {
|
||||
logger.WarnContext(ctx, "用户ID不存在")
|
||||
response.Error(c, errorx.ErrUserNoLogin)
|
||||
c.Abort()
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// CheckAdminPermission 检查用户是否为管理员,如果不是则返回错误响应
|
||||
func CheckAdminPermission(c *gin.Context) bool {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
// 先检查是否已登录
|
||||
if !CheckUserLogin(c) {
|
||||
return false
|
||||
}
|
||||
|
||||
// 检查用户是否为管理员
|
||||
isAdmin, ok := c.Get("is_admin")
|
||||
if !ok || !isAdmin.(bool) {
|
||||
logger.WarnContext(ctx, "用户不是管理员", "is_admin", isAdmin)
|
||||
response.Error(c, errorx.ErrUserNoLogin.WithMsg("用户无权限"))
|
||||
c.Abort()
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
Reference in New Issue
Block a user