package middleware

import (
	"github.com/gin-gonic/gin"
	"testData/global"
	"testData/model"
	"testData/model/response"
	"testData/service"
	"testData/utils"
)

func CasbinHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		user, _ := utils.JWTGetUser(c)
		// 获取请求的PATH
		obj := c.Request.URL.Path
		// 获取请求方法
		act := c.Request.Method
		// 获取用户的角色
		//sub := user.RoleId
		var isExist bool
		var u *model.User
		global.BaseDB.Where("user_id = ?", user.UserId).Preload("Role").Find(&u)
		for _, v := range u.Role {
			sub := v.RoleId
			e := service.CasbinServiceApp.Casbin()
			// 判断策略中是否存在
			success, _ := e.Enforce(sub, obj, act)
			if success {
				isExist = true
			}
		}
		if isExist {
			c.Next()
		} else {
			response.FailWithDetailed(gin.H{}, "权限不足", c)
			c.Abort()
			return
		}
		//if success {
		//	c.Next()
		//} else {
		//	response.FailWithDetailed(gin.H{}, "权限不足", c)
		//	c.Abort()
		//	return
		//}
	}
}
