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.

37 lines
784 B

1 month ago
package middleware
import (
"net/http"
1 month ago
"gofaster/internal/auth/repository"
1 month ago
"github.com/gin-gonic/gin"
"gorm.io/gorm"
1 month ago
)
var permRepo *repository.PermissionRepo
// 初始化权限仓库(可以在main.go中调用)
func InitPermissionMiddleware(db *gorm.DB) {
permRepo = repository.NewPermissionRepo(db)
}
1 month ago
func PermissionMiddleware(permission string) gin.HandlerFunc {
return func(c *gin.Context) {
userID, exists := c.Get("user_id")
if !exists {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "未认证"})
return
}
// 检查用户是否有该权限
hasPerm := permRepo.CheckUserPermission(userID.(uint), permission)
1 month ago
if !hasPerm {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "没有权限"})
return
}
c.Next()
}
}