メインコンテンツにスキップ

ポリシーサブセットの読み込み

フィルタされたポリシー管理をサポートするアダプタもあります。 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モデルを使用します。 この場合、フィルタはポリシーを単一ドメインに制限します。 "domain1" 以外のドメインのポリシー行は、ロードされたポリシーから省略されます。

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.