Model Storage
Models in Casbin are load-only: they define your access control logic and are treated as static at runtime. There is no API to save or update the model in storage.
You can load a model in three ways:
Load from a CONF file
Loading from a .conf file is the usual approach and makes it easy to share and discuss models.
Example: examples/rbac_model.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
Use it when creating the enforcer:
e := casbin.NewEnforcer("examples/rbac_model.conf", "examples/rbac_policy.csv")
Load from code
You can build the model in code instead of using a file:
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)
Load from a string
You can also load the model from a string (e.g. from config or a database):
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)