Files
starter/internal/middleware/utils.go
limitcool b7628c770b 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.
2025-06-17 23:09:02 +08:00

106 lines
2.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package middleware
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
func GetUserID(c *gin.Context) uint {
userID, exists := c.Get("user_id")
if !exists {
return 0
}
// 尝试转换为float64
if id, ok := userID.(float64); ok {
return uint(id)
}
// 尝试转换为uint
if id, ok := userID.(uint); ok {
return id
}
// 尝试转换为int64
if id, ok := userID.(int64); ok {
return uint(id)
}
return 0
}
// GetUserIDInt64 从上下文中获取用户IDint64类型
func GetUserIDInt64(c *gin.Context) int64 {
userID, exists := c.Get("user_id")
if !exists {
return 0
}
// 尝试转换为float64
if id, ok := userID.(float64); ok {
return int64(id)
}
// 尝试转换为uint
if id, ok := userID.(uint); ok {
return int64(id)
}
// 尝试转换为int64
if id, ok := userID.(int64); ok {
return id
}
return 0
}
// GetUserIDString 从上下文中获取用户ID字符串类型
func GetUserIDString(c *gin.Context) string {
id := GetUserID(c)
if id == 0 {
return ""
}
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
}