2026-04-27 23:20:24 +08:00
|
|
|
package middleware
|
2026-03-14 02:09:38 +08:00
|
|
|
|
|
|
|
|
import (
|
2026-03-17 00:47:17 +08:00
|
|
|
"slices"
|
2026-03-14 02:09:38 +08:00
|
|
|
"strings"
|
|
|
|
|
|
2026-04-22 16:01:59 +08:00
|
|
|
"with_you/internal/service"
|
2026-03-14 02:09:38 +08:00
|
|
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// RequireRole 要求特定角色的中间件
|
|
|
|
|
func RequireRole(casbinService service.CasbinService, requiredRoles ...string) gin.HandlerFunc {
|
|
|
|
|
return func(c *gin.Context) {
|
|
|
|
|
userID, exists := c.Get("user_id")
|
|
|
|
|
if !exists {
|
|
|
|
|
c.AbortWithStatusJSON(401, gin.H{
|
|
|
|
|
"code": "UNAUTHORIZED",
|
|
|
|
|
"message": "请先登录",
|
|
|
|
|
})
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
userRoles, err := casbinService.GetRolesForUser(c.Request.Context(), userID.(string))
|
|
|
|
|
if err != nil {
|
|
|
|
|
c.AbortWithStatusJSON(500, gin.H{
|
|
|
|
|
"code": "INTERNAL_ERROR",
|
|
|
|
|
"message": "获取用户角色失败",
|
|
|
|
|
})
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 检查用户是否拥有任一所需角色
|
2026-03-17 00:47:17 +08:00
|
|
|
hasRole := slices.ContainsFunc(requiredRoles, func(required string) bool {
|
|
|
|
|
return slices.Contains(userRoles, required)
|
|
|
|
|
})
|
2026-03-14 02:09:38 +08:00
|
|
|
|
|
|
|
|
if !hasRole {
|
|
|
|
|
c.AbortWithStatusJSON(403, gin.H{
|
|
|
|
|
"code": "FORBIDDEN",
|
|
|
|
|
"message": "需要以下角色之一: " + strings.Join(requiredRoles, ", "),
|
|
|
|
|
})
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
c.Next()
|
|
|
|
|
}
|
|
|
|
|
}
|