You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
105 lines
2.4 KiB
Go
105 lines
2.4 KiB
Go
package casbin
|
|
|
|
import (
|
|
"git.noahlan.cn/noahlan/ntool-biz/core/config"
|
|
"git.noahlan.cn/noahlan/ntool/nlog"
|
|
"github.com/casbin/casbin/v2"
|
|
"github.com/casbin/casbin/v2/model"
|
|
"github.com/casbin/casbin/v2/persist"
|
|
entadapter "github.com/casbin/ent-adapter"
|
|
rediswatcher "github.com/casbin/redis-watcher/v2"
|
|
redis2 "github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
type CasbinConf struct {
|
|
ModelText string `json:"ModelText,optional"`
|
|
}
|
|
|
|
func (l CasbinConf) NewCasbin(dbType, dsn string) (*casbin.Enforcer, error) {
|
|
adapter, err := entadapter.NewAdapter(dbType, dsn)
|
|
if err != nil {
|
|
nlog.Errorf("NCasbin new ent-adapter err: %v", err)
|
|
return nil, err
|
|
}
|
|
text := l.ModelText
|
|
if l.ModelText == "" {
|
|
text = `
|
|
[request_definition]
|
|
r = sub, obj, act
|
|
|
|
[policy_definition]
|
|
p = sub, obj, act
|
|
|
|
[role_definition]
|
|
g = _, _
|
|
|
|
[policy_effect]
|
|
e = some(where (p.eft == allow))
|
|
|
|
[matchers]
|
|
m = r.sub == p.sub && keyMatch2(r.obj,p.obj) && r.act == p.act
|
|
`
|
|
}
|
|
|
|
m, err := model.NewModelFromString(text)
|
|
if err != nil {
|
|
nlog.Errorf("NCasbin new Model err: %v", err)
|
|
return nil, err
|
|
}
|
|
|
|
enforcer, err := casbin.NewEnforcer(m, adapter)
|
|
if err != nil {
|
|
nlog.Errorf("NCasbin NewEnforcer err: %v", err)
|
|
return nil, err
|
|
}
|
|
|
|
err = enforcer.LoadPolicy()
|
|
if err != nil {
|
|
nlog.Errorf("NCasbin LoadPolicy err: %v", err)
|
|
return nil, err
|
|
}
|
|
|
|
return enforcer, nil
|
|
}
|
|
|
|
func (l CasbinConf) MustNewCasbin(dbType, dsn string) *casbin.Enforcer {
|
|
csb, err := l.NewCasbin(dbType, dsn)
|
|
nlog.Must(err)
|
|
|
|
return csb
|
|
}
|
|
|
|
// MustNewRedisWatcher returns redis watcher. If there are errors, it will exist.
|
|
// f function will be called if the policies are updated.
|
|
func (l CasbinConf) MustNewRedisWatcher(c config.RedisConf, f func(string2 string)) persist.Watcher {
|
|
w, err := rediswatcher.NewWatcher(c.Addr, rediswatcher.WatcherOptions{
|
|
Options: redis2.Options{
|
|
Network: c.Network,
|
|
Password: c.Password,
|
|
},
|
|
Channel: "/casbin",
|
|
IgnoreSelf: false,
|
|
})
|
|
nlog.Must(err)
|
|
|
|
err = w.SetUpdateCallback(f)
|
|
nlog.Must(err)
|
|
|
|
return w
|
|
}
|
|
|
|
// MustNewCasbinWithRedisWatcher returns Casbin Enforcer with Redis watcher.
|
|
func (l CasbinConf) MustNewCasbinWithRedisWatcher(dbType, dsn string, c config.RedisConf) *casbin.Enforcer {
|
|
cbn := l.MustNewCasbin(dbType, dsn)
|
|
w := l.MustNewRedisWatcher(c, func(data string) {
|
|
rediswatcher.DefaultUpdateCallback(cbn)(data)
|
|
})
|
|
err := cbn.SetWatcher(w)
|
|
nlog.Must(err)
|
|
|
|
err = cbn.SavePolicy()
|
|
nlog.Must(err)
|
|
|
|
return cbn
|
|
}
|