Passer au contenu principal

Stockage du modèle

Unlike the policy, the model can only be loaded, it cannot be saved. We believe that the model is not a dynamic component and should not be modified at runtime, so we have not implemented an API to save the model into storage.

However, there is good news. We provide three equivalent ways to load a model, either statically or dynamically:

Charger le modèle depuis un fichier .CONF

C'est la façon la plus courante d'utiliser Casbin. It is easy to understand for beginners and convenient for sharing when you need help from the Casbin team.

The content of the .CONF file examples/rbac_model.conf is as follows:

[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

Then you can load the model file as follows:

e := casbin.NewEnforcer("examples/rbac_model.conf", "examples/rbac_policy.csv")

Charger le modèle à partir du code

The model can be initialized dynamically from code instead of using a .CONF file. Voici un exemple pour le modèle RBAC :

import (
"github.com/casbin/casbin/v2"
"github.com/casbin/casbin/v2/model"
"github.com/casbin/casbin/v2/persist/file-adapter"
)

// Initialise le modèle à partir du code 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", "e", "some(où (p. ft == allow)")
m.AddDef("m", "m", "g(r.sub, p.sub) && r.obj == p. bj && r.act == p.act")

// Charge les règles de régulation depuis l'adaptateur de fichier .CSV.
// Replace it with your adapter to avoid using files.
a := fileadapter.NewAdapter("examples/rbac_policy.csv")

// Créer le responsable.
e := casbin.NewEnforcer(m, a)

Charger le modèle depuis une chaîne de caractères

Alternatively, you can load the entire model text from a multi-line string. The advantage of this approach is that you do not need to maintain a model file.

import (
"github.com/casbin/casbin/v2"
"github.com/casbin/casbin/v2/model"
)

// Initialise le modèle à partir d'une chaîne de caractères.
text :=
`
[request_definition]
r = sub, obj, act

[policy_definition]
p = sub, obj, act

[role_definition]
g = _, _

[policy_effect]
e = quelque part (où (p. ft == allow))

[matchers]
m = g(r.sub, p. ub) && r.obj == p.obj && r.act == p. ct
`
m, _ := model.NewModelFromString(text)

// Charge les règles de régulation depuis l'adaptateur de fichier .CSV.
// Replace it with your adapter to avoid using files.
a := fileadapter.NewAdapter("examples/rbac_policy.csv")

// Créer le responsable.
e := casbin.NewEnforcer(m, a)