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

Adapters

Casbinでは、ポリシーのストレージはアダプタ(別名Casbinのミドルウェア)として実装されています。 Casbinのユーザーは、アダプタを使用してストレージからポリシーのルールをロード(別名 LoadPolicy())したり、それにポリシーのルールを保存(別名 SavePolicy())することができます。 軽量を保つため、メインライブラリにはアダプタのコードを入れていません。

サポートされているアダプタ

Casbinのアダプタの完全なリストは以下の通りです。 新しいアダプタに対する第三者からの貢献は歓迎されます、私たちに知らせてください、そして私たちはそれをこのリストに入れます:

AdapterTypeAuthorAutoSaveDescription
File Adapter (built-in)FileCasbinFor .CSV (Comma-Separated Values) files
Filtered File Adapter (built-in)File@faceless-saintFor .CSV (Comma-Separated Values) files with policy subset loading support
SQL AdapterSQL@Blank-XuMySQL, PostgreSQL, SQL Server, SQLite3 are supported in master branch and Oracle is supported in oracle branch by database/sql
Xorm AdapterORMCasbinMySQL, PostgreSQL, TiDB, SQLite, SQL Server, Oracle are supported by Xorm
GORM AdapterORMCasbinMySQL, PostgreSQL, Sqlite3, SQL Server are supported by GORM
GORM Adapter ExORMCasbinMySQL, PostgreSQL, Sqlite3, SQL Server are supported by GORM
Ent AdapterORMCasbinMySQL, MariaDB, PostgreSQL, SQLite, Gremlin-based graph databases are supported by ent ORM
Beego ORM AdapterORMCasbinMySQL, PostgreSQL, Sqlite3 are supported by Beego ORM
SQLX AdapterORM@memweyMySQL, PostgreSQL, SQLite, Oracle are supported by SQLX
Sqlx AdapterORM@Blank-XuMySQL, PostgreSQL, SQL Server, SQLite3 are supported in master branch and Oracle is supported in oracle branch by sqlx
GF ORM AdapterORM@vance-liuMySQL, SQLite, PostgreSQL, Oracle, SQL Server are supported by GoFrame ORM
GoFrame ORM AdapterORM@kotlin2018MySQL, SQLite, PostgreSQL, Oracle, SQL Server are supported by GoFrame ORM
gf-adapterORM@zcycMySQL, SQLite, PostgreSQL, Oracle, SQL Server are supported by GoFrame ORM
Gdb AdapterORM@jxo-meMySQL, SQLite, PostgreSQL, Oracle, SQL Server are supported by GoFrame ORM
GoFrame V2 AdapterORM@hailazMySQL, SQLite, PostgreSQL, Oracle, SQL Server are supported by GoFrame ORM
Bun AdapterORM@JunNishimuraMySQL, SQLite, PostgreSQL, SQL Server are supported by Bun ORM
Filtered PostgreSQL AdapterSQLCasbinFor PostgreSQL
Filtered pgx AdapterSQL@pckhoiPostgreSQL is supported by pgx
PostgreSQL AdapterSQL@cychiuaeFor PostgreSQL
RQLite AdapterSQLEDOMO SystemsFor RQLite
MongoDB AdapterNoSQLCasbinFor MongoDB based on MongoDB Go Driver
RethinkDB AdapterNoSQL@adityapandey9For RethinkDB
Cassandra AdapterNoSQLCasbinFor Apache Cassandra DB
DynamoDB AdapterNoSQLHOOQFor Amazon DynamoDB
DynacasbinNoSQLNewbMiaoFor Amazon DynamoDB
ArangoDB AdapterNoSQL@adamwasilaFor ArangoDB
Amazon S3 AdapterCloudSolutoFor Minio and Amazon S3
Go CDK AdapterCloud@bartventerAdapter based on Go Cloud Dev Kit that supports: Amazon DynamoDB, Azure CosmosDB, GCP Firestore, MongoDB, In-Memory
Azure Cosmos DB AdapterCloud@spacycoderFor Microsoft Azure Cosmos DB
GCP Firestore AdapterCloud@reedomFor Google Cloud Platform Firestore
GCP Cloud Storage AdapterCloudquramiFor Google Cloud Platform Cloud Storage
GCP Cloud Spanner AdapterCloud@flowerinthenightFor Google Cloud Platform Cloud Spanner
Consul AdapterKV store@ankitm123For HashiCorp Consul
Redis Adapter (Redigo)KV storeCasbinFor Redis
Redis Adapter (go-redis)KV store@mlsenFor Redis
Etcd AdapterKV store@sebastianliuFor etcd
BoltDB AdapterKV store@spezaFor Bolt
Bolt AdapterKV store@wirepairFor Bolt
BadgerDB AdapterKV store@initsFor BadgerDB
Protobuf AdapterStreamCasbinFor Google Protocol Buffers
JSON AdapterStringCasbinFor JSON
String AdapterString@qiangmzsxFor String
HTTP File AdapterHTTP@h4ckednekoFor http.FileSystem
FileSystem AdapterFile@nauconFor fs.FS and embed.FS
メモ
  1. casbin.NewEnforcer()が明示的または暗黙的なアダプタとともに呼び出されると、ポリシーは自動的にロードされます。
  2. ストレージからポリシーのルールを再ロードするためにe.LoadPolicy()を呼び出すことができます。
  3. アダプタがAuto-Save機能をサポートしていない場合、ポリシーを追加または削除したときにポリシーのルールが自動的にストレージに保存されることはありません。 すべてのポリシーのルールを保存するためには、SavePolicy()を手動で呼び出す必要があります。

ここではいくつかの例を提供します:

ファイルアダプタ(内蔵)

以下は、内蔵のファイルアダプタからエンフォーサーを初期化する方法を示しています:

import "github.com/casbin/casbin"

e := casbin.NewEnforcer("examples/basic_model.conf", "examples/basic_policy.csv")

これは次のと同じです:

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

a := fileadapter.NewAdapter("examples/basic_policy.csv")
e := casbin.NewEnforcer("examples/basic_model.conf", a)

MySQLアダプタ

以下は、MySQLデータベースからエンフォーサーを初期化する方法を示しています。 それはrootと空のパスワードで127.0.0.1:3306のMySQL DBに接続します。

import (
"github.com/casbin/casbin"
"github.com/casbin/mysql-adapter"
)

a := mysqladapter.NewAdapter("mysql", "root:@tcp(127.0.0.1:3306)/")
e := casbin.NewEnforcer("examples/basic_model.conf", a)

独自のストレージアダプタを使用する

以下のように独自のアダプタを使用することができます:

import (
"github.com/casbin/casbin"
"github.com/your-username/your-repo"
)

a := yourpackage.NewAdapter(params)
e := casbin.NewEnforcer("examples/basic_model.conf", a)

異なるアダプタ間での移行/変換

AからBへのアダプタを変換したい場合、次のように行うことができます:

1.Aからメモリへのポリシーのロード

e, _ := NewEnforcer(m, A)

または

e.SetAdapter(A)
e.LoadPolicy()

2.あなたのアダプタをAからBに変換する

e.SetAdapter(B)

3.メモリからBへのポリシーの保存

e.SavePolicy()

ランタイムでのロード/セーブ

初期化後にモデルをリロードしたり、ポリシーをリロードしたり、ポリシーを保存したい場合もあります:

// Reload the model from the model CONF file.
e.LoadModel()

// Reload the policy from file/database.
e.LoadPolicy()

// Save the current policy (usually after changed with Casbin API) back to file/database.
e.SavePolicy()

AutoSave

There is a feature called Auto-Save for adapters. When an adapter supports Auto-Save, it means it can support adding a single policy rule to the storage, or removing a single policy rule from the storage. This is unlike SavePolicy(), because the latter will delete all policy rules in the storage and save all policy rules from Casbin enforcer to the storage. So it may suffer performance issue when the number of policy rules is large.

When the adapter supports Auto-Save, you can switch this option via Enforcer.EnableAutoSave() function. The option is enabled by default (if the adapter supports it).

メモ
  1. The Auto-Save feature is optional. An adapter can choose to implement it or not.
  2. Auto-Save only works for a Casbin enforcer when the adapter the enforcer uses supports it.
  3. See the AutoSave column in the above adapter list to see if Auto-Save is supported by an adapter.

Here's an example about how to use Auto-Save:

import (
"github.com/casbin/casbin"
"github.com/casbin/xorm-adapter"
_ "github.com/go-sql-driver/mysql"
)

// By default, the AutoSave option is enabled for an enforcer.
a := xormadapter.NewAdapter("mysql", "mysql_username:mysql_password@tcp(127.0.0.1:3306)/")
e := casbin.NewEnforcer("examples/basic_model.conf", a)

// Disable the AutoSave option.
e.EnableAutoSave(false)

// Because AutoSave is disabled, the policy change only affects the policy in Casbin enforcer,
// it doesn't affect the policy in the storage.
e.AddPolicy(...)
e.RemovePolicy(...)

// Enable the AutoSave option.
e.EnableAutoSave(true)

// Because AutoSave is enabled, the policy change not only affects the policy in Casbin enforcer,
// but also affects the policy in the storage.
e.AddPolicy(...)
e.RemovePolicy(...)

For more examples, please see: https://github.com/casbin/xorm-adapter/blob/master/adapter_test.go

How to write an adapter

All adapters should implement the Adapter interface by providing at least two mandatory methods:LoadPolicy(model model.Model) error and SavePolicy(model model.Model) error.

The other three functions are optional. They should be implemented if the adapter supports the Auto-Save feature.

MethodTypeDescription
LoadPolicy()mandatoryLoad all policy rules from the storage
SavePolicy()mandatorySave all policy rules to the storage
AddPolicy()optionalAdd a policy rule to the storage
RemovePolicy()optionalストレージからポリシールールを削除する
RemoveFilteredPolicy()オプショナルフィルターに一致するポリシールールをストレージから削除する
メモ

アダプタが Auto-Save をサポートしていない場合、3つのオプショナルな関数に対して空の実装を提供する必要があります。 Golangの例は次の通りです:

// AddPolicy adds a policy rule to the storage.
func (a *Adapter) AddPolicy(sec string, ptype string, rule []string) error {
return errors.New("not implemented")
}

// RemovePolicy removes a policy rule from the storage.
func (a *Adapter) RemovePolicy(sec string, ptype string, rule []string) error {
return errors.New("not implemented")
}

// RemoveFilteredPolicy removes policy rules that match the filter from the storage.
func (a *Adapter) RemoveFilteredPolicy(sec string, ptype string, fieldIndex int, fieldValues ...string) error {
return errors.New("not implemented")
}

Casbinエンフォーサーは、これら3つのオプショナルな関数を呼び出す際の not implemented エラーを無視します。

アダプターの書き方についての詳細があります。

  • データ構造。 アダプタは、少なくとも6列の読み取りをサポートする必要があります。
  • データベース名。 デフォルトのデータベース名は casbin であるべきです。
  • テーブル名。 デフォルトのテーブル名は casbin_rule であるべきです。
  • Ptype列。 この列の名前は ptype であるべきで、p_typePtype ではない。
  • テーブル定義は (id int primary key, ptype varchar, v0 varchar, v1 varchar, v2 varchar, v3 varchar, v4 varchar, v5 varchar) であるべきです。
  • ユニークキーインデックスは ptype,v0,v1,v2,v3,v4,v5 の列に作成されるべきです。
  • LoadFilteredPolicyfilter をパラメータとして必要とします。 フィルタは次のようなものであるべきです。
{
"p":[ [ "alice" ], [ "bob" ] ],
"g":[ [ "", "book_group" ], [ "", "pen_group" ] ],
"g2":[ [ "alice" ] ]
}

DBの作成は誰が責任を持つのですか?

慣習として、アダプタは存在しない場合は自動的に casbin という名前のデータベースを作成し、ポリシーのストレージとして使用できるべきです。 参考実装としてXormアダプタを使用してください:https://github.com/casbin/xorm-adapter

コンテキストアダプタ

ContextAdapter はCasbinアダプタに対してコンテキストを意識したインターフェースを提供します。

コンテキストを通じて、アダプタAPIのタイムアウト制御などの機能を実装することができます

gormadapter はコンテキストを持つアダプタをサポートしており、以下はコンテキストを使用して実装されたタイムアウト制御です

ca, _ := NewContextAdapter("mysql", "root:@tcp(127.0.0.1:3306)/", "casbin")
// Limited time 300s
ctx, cancel := context.WithTimeout(context.Background(), 300*time.Microsecond)
defer cancel()

err := ca.AddPolicyCtx(ctx, "p", "p", []string{"alice", "data1", "read"})
if err != nil {
panic(err)
}

コンテキストアダプタの書き方

ContextAdapter APIは通常の Adapter APIよりもコンテキスト処理のレイヤーが一つ多く、通常のAdapter APIを実装する基礎の上で、自分自身のコンテキスト処理ロジックをカプセル化することができます

A simple reference to the gormadapter: context_adapter.go