package initialization import ( "fmt" "github.com/casbin/casbin/v2" "github.com/casbin/casbin/v2/model" gormAdapter "github.com/casbin/gorm-adapter/v3" "go_api_tmpl/global" ) // Casbin 初始化Casbin的RABC模型 func Casbin() { // Initialize casbin adapter adapter, err := gormAdapter.NewAdapterByDBUseTableName(global.MySQLConn, "", "t_role_rule") if err != nil { panic(fmt.Sprintf("failed to initialize casbin adapter: %v", err)) } // 初始化模型 model := model.NewModel() model.AddDef("r", "r", "sub, obj, act") model.AddDef("p", "p", "sub, obj, act") model.AddDef("g", "g", "_, _") model.AddDef("e", "e", "some(where (p.eft == allow))") // 匹配规则(下面的规则适用与根据Gin的Route的Path和Method做校验,最后那个r.sub == 1是用来判断超级管理员的) model.AddDef("m", "m", "g(r.sub, p.sub) && keyMatch2(r.obj, p.obj) && regexMatch(r.act, p.act) || r.sub == \"1\"") enf, err := casbin.NewEnforcer(model, adapter) if err != nil { panic(fmt.Sprintf("failed to create casbin enforcer: %v", err)) } global.Enforcer = enf }