Model Storage
Casbin 中的模型是 只读加载 的:它们定义访问控制逻辑,在运行时被视为静态的。没有把模型保存或更新到存储中的 API。
有三种方式加载模型:
从 CONF 文件加载
从 .conf 文件加载是最常用的方式,也便于分享和讨论模型。
[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 = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act
在创建 enforcer 时使用:
e := casbin.NewEnforcer("examples/rbac_model.conf", "examples/rbac_policy.csv")
从代码加载
也可以在代码中构建模型,而不使用文件:
import (
"github.com/casbin/casbin/v3"
"github.com/casbin/casbin/v3/model"
"github.com/casbin/casbin/v3/persist/file-adapter"
)
// Build the model in Go.
m := model.NewModel()
m.AddDef("r", "r", "sub, obj, act")
m.AddDef("p", "p", "sub, obj, act")
m.AddDef("g", "g", "_, _")
m.AddDef("e", "e", "some(where (p.eft == allow))")
m.AddDef("m", "m", "g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act")
// Load the policy rules from the .CSV file adapter.
// Replace it with your adapter to avoid using files.
a := fileadapter.NewAdapter("examples/rbac_policy.csv")
// Create the enforcer.
e := casbin.NewEnforcer(m, a)
从字符串加载
还可以从字符串(例如来自配置或数据库)加载模型:
import (
"github.com/casbin/casbin/v3"
"github.com/casbin/casbin/v3/model"
)
// Model text (e.g. from config).
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 = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act
`
m, _ := model.NewModelFromString(text)
// Load the policy rules from the .CSV file adapter.
// Replace it with your adapter to avoid using files.
a := fileadapter.NewAdapter("examples/rbac_policy.csv")
// Create the enforcer.
e := casbin.NewEnforcer(m, a)