You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"gofaster/internal/auth/repository"
|
|
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"gorm.io/gorm"
|
|
|
|
)
|
|
|
|
|
|
|
|
var permRepo *repository.PermissionRepo
|
|
|
|
|
|
|
|
// 初始化权限仓库(可以在main.go中调用)
|
|
|
|
func InitPermissionMiddleware(db *gorm.DB) {
|
|
|
|
permRepo = repository.NewPermissionRepo(db)
|
|
|
|
}
|
|
|
|
|
|
|
|
func PermissionMiddleware(permission string) gin.HandlerFunc {
|
|
|
|
return func(c *gin.Context) {
|
|
|
|
// 使用安全的GetUserID函数
|
|
|
|
userID, exists := GetUserID(c)
|
|
|
|
if !exists {
|
|
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "未认证"})
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// 检查用户是否有该权限
|
|
|
|
hasPerm := permRepo.CheckUserPermission(userID, permission)
|
|
|
|
if !hasPerm {
|
|
|
|
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "没有权限"})
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
c.Next()
|
|
|
|
}
|
|
|
|
}
|