package auth

import (
	"bwallet/pkg/errno"
	"bwallet/pkg/handler"
	"bwallet/pkg/rbac"
	"bwallet/pkg/util"
	"github.com/gin-gonic/gin"
	_ "github.com/go-sql-driver/mysql"
)

func Casbin() gin.HandlerFunc {
	return func(c *gin.Context) {
		// Initialize a Xorm adapter with MySQL database.
		//a, _ := gormadapter.NewAdapter("mysql", "root:fVkWkJZoOQcpunqC@tcp(172.16.101.45:3306)/pc_manage", true)
		// e, err := casbin.NewEnforcer("./conf/model.conf", "./conf/policy.csv")

		claim := c.MustGet("userClaim").(*util.Claims)
		path := c.Request.URL.Path
		method := c.Request.Method
		username := claim.UserInfo.Username

		//a, _ := gormadapter.NewAdapter("mysql", "root:fVkWkJZoOQcpunqC@tcp(172.16.101.45:3306)/pc_manage", true)
		//e, err := casbin.NewEnforcer("./conf/model.conf", a)
		//if err != nil {
		//	handler.SendResponse(c, errno.InternalServerError, nil)
		//	c.Abort()
		//	return
		//}
		//sub := "alice" // the user that wants to access a resource.
		//obj := "data1" // the resource that is going to be accessed.
		//act := "read"  // the operation that the user performs on the resource.
		//added, err := e.AddPolicy("alice", "data1", "read")
		//added, err := rbac.Ef.AddPolicy(username, path, method)

		//added,err := rbac.Ef.AddGroupingPolicy("alice", "admin")
		//fmt.Println(added)
		//c.Next()
		//if err != nil {
		//	fmt.Println("添加权限错误，错误内容：", err)
		//}
		//ok, err := e.Enforce(sub, obj, act)

		ok, err := rbac.Ef.Enforce(username, path, method)
		if err != nil {
			handler.SendResponse(c, errno.InternalServerError, nil)
			c.Abort()
			return
		}

		if ok != true {
			handler.SendResponse(c, errno.PermissionDenied, nil)
			c.Abort()
			return
		}

		c.Next()

	}
}
