refactor(server): decouple services and improve architecture
- Introduce interfaces for all major services (JWT, PostAI, Comment, Message, Notification, QRCodeLogin, Upload, Vote, etc.) to support dependency inversion. - Move query parameters from `internal/dto` to a new `internal/query` package to separate request payloads from data transfer objects. - Refactor `internal/router` to use embedded `RouterDeps` for cleaner dependency management. - Decouple handlers from repositories by injecting services instead of direct repository access, ensuring proper layering. - Improve database initialization by moving it from `internal/model` to `internal/database`. - Optimize message decryption by implementing a more efficient `BatchDecrypt` method in `MessageEncryptor` using a worker pool. - Enhance error handling and security by implementing fail-fast checks for encryption key length during startup. - Clean up unused code, including the `avatar` package and several unused DTOs.
This commit is contained in:
@@ -9,63 +9,6 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// CasbinAuth Casbin 权限中间件
|
||||
// 需要在 Auth 中间件之后使用
|
||||
func CasbinAuth(casbinService service.CasbinService) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
// 获取请求路径和方法
|
||||
path := c.Request.URL.Path
|
||||
method := c.Request.Method
|
||||
|
||||
// 从上下文获取用户ID (由 Auth 中间件设置)
|
||||
userID, exists := c.Get("user_id")
|
||||
|
||||
// 如果用户未登录,检查是否是公开路由
|
||||
if !exists {
|
||||
// 对于未登录用户,使用匿名角色检查权限
|
||||
allowed, err := casbinService.Enforce(c.Request.Context(), "anonymous", path, method)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(500, gin.H{
|
||||
"code": "INTERNAL_ERROR",
|
||||
"message": "权限检查失败",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if !allowed {
|
||||
c.AbortWithStatusJSON(401, gin.H{
|
||||
"code": "UNAUTHORIZED",
|
||||
"message": "请先登录",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
// 检查用户权限
|
||||
allowed, err := casbinService.EnforceForUser(c.Request.Context(), userID.(string), path, method)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(500, gin.H{
|
||||
"code": "INTERNAL_ERROR",
|
||||
"message": "权限检查失败",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if !allowed {
|
||||
c.AbortWithStatusJSON(403, gin.H{
|
||||
"code": "FORBIDDEN",
|
||||
"message": "权限不足",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// RequireRole 要求特定角色的中间件
|
||||
func RequireRole(casbinService service.CasbinService, requiredRoles ...string) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
|
||||
Reference in New Issue
Block a user