goweb/initialization/casbin.go
2021-08-22 00:13:00 +08:00

34 lines
1.1 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package initialization
import (
"fmt"
"github.com/casbin/casbin/v2"
"github.com/casbin/casbin/v2/model"
gormAdapter "github.com/casbin/gorm-adapter/v3"
"goweb/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
}