Перейти к основному контенту

Загрузка подмножества политик

Некоторые адаптеры поддерживают управление отфильтрованной политикой. This means that the policy loaded by Casbin is a subset of the policy stored in the database based on a given filter. This allows for efficient policy enforcement in large, multi-tenant environments where parsing the entire policy becomes a performance bottleneck.

Чтобы использовать фильтрованные политики с поддерживаемым адаптером, просто вызовите метод LoadFilteredPolicy. Допустимый формат для параметра фильтра зависит от используемого адаптера. Для предотвращения случайных потерь данных метод SavePolicy отключен при загрузке фильтрованной политики.

Например, следующий фрагмент кода использует встроенный фильтрованный файловый адаптер и модель RBAC с доменами. В этом случае фильтр ограничивает политику одним доменом. Любые строки политики для доменов, отличных от «домена1» исключены из загруженной политики:

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

enforcer, _ := casbin.NewEnforcer()

adapter := fileadapter.NewFilteredAdapter("examples/rbac_with_domains_policy.csv")
enforcer.InitWithAdapter("examples/rbac_with_domains_model.conf", adapter)

filter := &fileadapter.Filter{
P: []string{"", "domain1"},
G: []string{"", "", "domain1"},
}
enforcer.LoadFilteredPolicy(filter)

// The loaded policy now only contains the entries pertaining to "domain1".

There is another method that supports the subset loading feature: LoadIncrementalFilteredPolicy. LoadIncrementalFilteredPolicy is similar to LoadFilteredPolicy, but it does not clear the previously loaded policy. It only appends the filtered policy to the existing policy.