Adapters
在Casbin中,策略存储是作为一个适配器(也称为Casbin的中间件)来实现的。 Casbin用户可以使用适配器从存储中加载策略规则(也称为LoadPolicy()
),或者将策略规则保存到存储中(也称为SavePolicy()
)。 为了保持轻量级,我们没有将适配器代码放在主库中。
支持的适配器
下面提供了Casbin适配器的完整列表。 欢迎任何第三方对新适配器的贡献,请通知我们,我们会将其放入此列表:
- Go
- Java
- Node.js
- PHP
- Python
- .NET
- Rust
- Ruby
- Swift
- Lua
Adapter | Type | Author | AutoSave | Description |
---|---|---|---|---|
File Adapter (built-in) | File | Casbin | ❌ | For .CSV (Comma-Separated Values) files |
Filtered File Adapter (built-in) | File | @faceless-saint | ❌ | For .CSV (Comma-Separated Values) files with policy subset loading support |
SQL Adapter | SQL | @Blank-Xu | ✅ | MySQL, PostgreSQL, SQL Server, SQLite3 are supported in master branch and Oracle is supported in oracle branch by database/sql |
Xorm Adapter | ORM | Casbin | ✅ | MySQL, PostgreSQL, TiDB, SQLite, SQL Server, Oracle are supported by Xorm |
GORM Adapter | ORM | Casbin | ✅ | MySQL, PostgreSQL, Sqlite3, SQL Server are supported by GORM |
GORM Adapter Ex | ORM | Casbin | ✅ | MySQL, PostgreSQL, Sqlite3, SQL Server are supported by GORM |
Ent Adapter | ORM | Casbin | ✅ | MySQL, MariaDB, PostgreSQL, SQLite, Gremlin-based graph databases are supported by ent ORM |
Beego ORM Adapter | ORM | Casbin | ✅ | MySQL, PostgreSQL, Sqlite3 are supported by Beego ORM |
SQLX Adapter | ORM | @memwey | ✅ | MySQL, PostgreSQL, SQLite, Oracle are supported by SQLX |
Sqlx Adapter | ORM | @Blank-Xu | ✅ | MySQL, PostgreSQL, SQL Server, SQLite3 are supported in master branch and Oracle is supported in oracle branch by sqlx |
GF ORM Adapter | ORM | @vance-liu | ✅ | MySQL, SQLite, PostgreSQL, Oracle, SQL Server are supported by GoFrame ORM |
GoFrame ORM Adapter | ORM | @kotlin2018 | ✅ | MySQL, SQLite, PostgreSQL, Oracle, SQL Server are supported by GoFrame ORM |
gf-adapter | ORM | @zcyc | ✅ | MySQL, SQLite, PostgreSQL, Oracle, SQL Server are supported by GoFrame ORM |
Gdb Adapter | ORM | @jxo-me | ✅ | MySQL, SQLite, PostgreSQL, Oracle, SQL Server are supported by GoFrame ORM |
GoFrame V2 Adapter | ORM | @hailaz | ✅ | MySQL, SQLite, PostgreSQL, Oracle, SQL Server are supported by GoFrame ORM |
Bun Adapter | ORM | @JunNishimura | ✅ | MySQL, SQLite, PostgreSQL, SQL Server are supported by Bun ORM |
Filtered PostgreSQL Adapter | SQL | Casbin | ✅ | For PostgreSQL |
Filtered pgx Adapter | SQL | @pckhoi | ✅ | PostgreSQL is supported by pgx |
PostgreSQL Adapter | SQL | @cychiuae | ✅ | For PostgreSQL |
RQLite Adapter | SQL | EDOMO Systems | ✅ | For RQLite |
MongoDB Adapter | NoSQL | Casbin | ✅ | For MongoDB based on MongoDB Go Driver |
RethinkDB Adapter | NoSQL | @adityapandey9 | ✅ | For RethinkDB |
Cassandra Adapter | NoSQL | Casbin | ❌ | For Apache Cassandra DB |
DynamoDB Adapter | NoSQL | HOOQ | ❌ | For Amazon DynamoDB |
Dynacasbin | NoSQL | NewbMiao | ✅ | For Amazon DynamoDB |
ArangoDB Adapter | NoSQL | @adamwasila | ✅ | For ArangoDB |
Amazon S3 Adapter | Cloud | Soluto | ❌ | For Minio and Amazon S3 |
Go CDK Adapter | Cloud | @bartventer | ✅ | Adapter based on Go Cloud Dev Kit that supports: Amazon DynamoDB, Azure CosmosDB, GCP Firestore, MongoDB, In-Memory |
Azure Cosmos DB Adapter | Cloud | @spacycoder | ✅ | For Microsoft Azure Cosmos DB |
GCP Firestore Adapter | Cloud | @reedom | ❌ | For Google Cloud Platform Firestore |
GCP Cloud Storage Adapter | Cloud | qurami | ❌ | For Google Cloud Platform Cloud Storage |
GCP Cloud Spanner Adapter | Cloud | @flowerinthenight | ✅ | For Google Cloud Platform Cloud Spanner |
Consul Adapter | KV store | @ankitm123 | ❌ | For HashiCorp Consul |
Redis Adapter (Redigo) | KV store | Casbin | ✅ | For Redis |
Redis Adapter (go-redis) | KV store | @mlsen | ✅ | For Redis |
Etcd Adapter | KV store | @sebastianliu | ❌ | For etcd |
BoltDB Adapter | KV store | @speza | ✅ | For Bolt |
Bolt Adapter | KV store | @wirepair | ❌ | For Bolt |
BadgerDB Adapter | KV store | @inits | ✅ | For BadgerDB |
Protobuf Adapter | Stream | Casbin | ❌ | For Google Protocol Buffers |
JSON Adapter | String | Casbin | ❌ | For JSON |
String Adapter | String | @qiangmzsx | ❌ | For String |
HTTP File Adapter | HTTP | @h4ckedneko | ❌ | For http.FileSystem |
FileSystem Adapter | File | @naucon | ❌ | For fs.FS and embed.FS |
Adapter | Type | Author | AutoSave | Description |
---|---|---|---|---|
File Adapter (built-in) | File | Casbin | ❌ | For .CSV (Comma-Separated Values) files |
JDBC Adapter | JDBC | Casbin | ✅ | MySQL, Oracle, PostgreSQL, DB2, Sybase, SQL Server are supported by JDBC |
Hibernate Adapter | ORM | Casbin | ✅ | Oracle, DB2, SQL Server, Sybase, MySQL, PostgreSQL are supported by Hibernate |
MyBatis Adapter | ORM | Casbin | ✅ | MySQL, Oracle, PostgreSQL, DB2, Sybase, SQL Server (the same as JDBC) are supported by MyBatis 3 |
Hutool Adapter | ORM | @mapleafgo | ✅ | MySQL, Oracle, PostgreSQL, SQLite are supported by Hutool |
MongoDB Adapter | NoSQL | Casbin | ✅ | MongoDB is supported by mongodb-driver-sync |
DynamoDB Adapter | NoSQL | Casbin | ❌ | For Amazon DynamoDB |
Redis Adapter | KV store | Casbin | ✅ | For Redis |
Adapter | Type | Author | AutoSave | Description |
---|---|---|---|---|
File Adapter (built-in) | File | Casbin | ❌ | For .CSV (Comma-Separated Values) files |
Filtered File Adapter (built-in) | File | Casbin | ❌ | For .CSV (Comma-Separated Values) files with policy subset loading support |
String Adapter (built-in) | String | @calebfaruki | ❌ | For String |
Basic Adapter | Native ORM | Casbin | ✅ | pg, mysql, mysql2, sqlite3, oracledb, mssql are supported by the adapter itself |
Sequelize Adapter | ORM | Casbin | ✅ | MySQL, PostgreSQL, SQLite, Microsoft SQL Server are supported by Sequelize |
TypeORM Adapter | ORM | Casbin | ✅ | MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, WebSQL, MongoDB are supported by TypeORM |
Prisma Adapter | ORM | Casbin | ✅ | MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, AWS Aurora, Azure SQL are supported by Prisma |
Knex Adapter | ORM | knex | ✅ | MSSQL, MySQL, PostgreSQL, SQLite3, Oracle are supported by Knex.js |
Objection.js Adapter | ORM | @willsoto | ✅ | MSSQL, MySQL, PostgreSQL, SQLite3, Oracle are supported by Objection.js |
MikroORM Adapter | ORM | @baisheng | ✅ | MongoDB, MySQL, MariaDB, PostgreSQL, SQLite are supported by MikroORM |
Node PostgreSQL Native Adapter | SQL | @touchifyapp | ✅ | PostgreSQL adapter with advanced policy subset loading support and improved performances built with node-postgres. |
Mongoose Adapter | NoSQL | elastic.io and Casbin | ✅ | MongoDB is supported by Mongoose |
Mongoose Adapter (No-Transaction) | NoSQL | minhducck | ✅ | MongoDB is supported by Mongoose |
Node MongoDB Native Adapter | NoSQL | NathanBhanji | ✅ | For Node MongoDB Native |
Node MongoDB Native Adapter | NoSQL | @juicycleff | ✅ | For Node MongoDB Native |
DynamoDB Adapter | NoSQL | @fospitia | ✅ | For Amazon DynamoDB |
Couchbase Adapter | NoSQL | @MarkMYoung | ✅ | For Couchbase |
Redis Adapter | KV store | Casbin | ❌ | For Redis |
Redis Adapter | KV store | @NandaKishorJeripothula | ❌ | For Redis |
Adapter | Type | Author | AutoSave | Description |
---|---|---|---|---|
File Adapter (built-in) | File | Casbin | ❌ | For .CSV (Comma-Separated Values) files |
Database Adapter | ORM | Casbin | ✅ | MySQL, PostgreSQL, SQLite, Microsoft SQL Server are supported by techone/database |
Zend Db Adapter | ORM | Casbin | ✅ | MySQL, PostgreSQL, SQLite, Oracle, IBM DB2, Microsoft SQL Server, Other PDO Driver are supported by zend-db |
Doctrine DBAL Adapter (Recommend) | ORM | Casbin | ✅ | Powerful PHP database abstraction layer (DBAL) with many features for database schema introspection and management. |
Medoo Adapter | ORM | Casbin | ✅ | Medoo is a lightweight PHP Database Framework to Accelerate Development, supports all SQL databases, including MySQL , MSSQL , SQLite , MariaDB , PostgreSQL , Sybase , Oracle and more. |
Laminas-db Adapter | ORM | Casbin | ✅ | MySQL, PostgreSQL, Oracle, IBM DB2, Microsoft SQL Server, PDO, etc. are supported by laminas-db |
Zend-db Adapter | ORM | Casbin | ✅ | MySQL, PostgreSQL, Oracle, IBM DB2, Microsoft SQL Server, PDO, etc. are supported by zend-db |
ThinkORM Adapter (ThinkPHP) | ORM | Casbin | ✅ | MySQL, PostgreSQL, SQLite, Oracle, Microsoft SQL Server, MongoDB are supported by ThinkORM |
Redis Adapter | KV store | @nsnake | ❌ | For Redis |
Adapter | Type | Author | AutoSave | Description |
---|---|---|---|---|
File Adapter (built-in) | File | Casbin | ❌ | For .CSV (Comma-Separated Values) files |
Django ORM Adapter | ORM | Casbin | ✅ | PostgreSQL, MariaDB, MySQL, Oracle, SQLite, IBM DB2, Microsoft SQL Server, Firebird, ODBC are supported by Django ORM |
SQLObject Adapter | ORM | Casbin | ✅ | PostgreSQL, MySQL, SQLite, Microsoft SQL Server, Firebird, Sybase, MAX DB, pyfirebirdsql are supported by SQLObject |
SQLAlchemy Adapter | ORM | Casbin | ✅ | PostgreSQL, MySQL, SQLite, Oracle, Microsoft SQL Server, Firebird, Sybase are supported by SQLAlchemy |
Async SQLAlchemy Adapter | ORM | Casbin | ✅ | PostgreSQL, MySQL, SQLite, Oracle, Microsoft SQL Server, Firebird, Sybase are supported by SQLAlchemy |
Async Databases Adapter | ORM | Casbin | ✅ | PostgreSQL, MySQL, SQLite, Oracle, Microsoft SQL Server, Firebird, Sybase are supported by Databases |
Peewee Adapter | ORM | @shblhy | ✅ | PostgreSQL, MySQL, SQLite are supported by Peewee |
MongoEngine Adapter | ORM | @zhangbailong945 | ❌ | MongoDB is supported by MongoEngine |
Pony ORM Adapter | ORM | @drorvinkler | ✅ | MySQL, PostgreSQL, SQLite, Oracle, CockroachDB are supported by Pony ORM |
Tortoise ORM Adapter | ORM | @thearchitector | ✅ | PostgreSQL (>=9.4), MySQL, MariaDB, and SQLite are supported by Tortoise ORM |
Async Ormar Adapter | ORM | @shepilov-vladislav | ✅ | PostgreSQL, MySQL, SQLite are supported by Ormar |
SQLModel Adapter | ORM | @shepilov-vladislav | ✅ | PostgreSQL, MySQL, SQLite are supported by SQLModel |
Couchbase Adapter | NoSQL | ScienceLogic | ✅ (without remove_filtered_policy() ) | For Couchbase |
DynamoDB Adapter | NoSQL | @abqadeer | ✅ | For DynamoDB |
Pymongo Adapter | NoSQL | Casbin | ❌ | MongoDB is supported by Pymongo |
Redis Adapter | KV store | Casbin | ✅ | For Redis |
GCP Firebase Adapter | Cloud | @devrushi41 | ✅ | For Google Cloud Platform Firebase |
Adapter | Type | Author | AutoSave | Description |
---|---|---|---|---|
File Adapter (built-in) | File | Casbin | ❌ | For .CSV (Comma-Separated Values) files |
EF Adapter | ORM | Casbin | ❌ | MySQL, PostgreSQL, SQLite, Microsoft SQL Server, Oracle, DB2, etc. are supported by Entity Framework 6 |
EFCore Adapter | ORM | Casbin | ✅ | MySQL, PostgreSQL, SQLite, Microsoft SQL Server, Oracle, DB2, etc. are supported by Entity Framework Core |
Linq2DB Adapter | ORM | @Tirael | ✅ | MySQL, PostgreSQL, SQLite, Microsoft SQL Server, Oracle, Access, Firebird, Sybase, etc. are supported by linq2db |
Azure Cosmos DB Adapter | Cloud | @sagarkhandelwal | ✅ | For Microsoft Azure Cosmos DB |
Adapter | Type | Author | AutoSave | Description |
---|---|---|---|---|
File Adapter (built-in) | File | Casbin | ❌ | For .CSV (Comma-Separated Values) files |
Diesel Adapter | ORM | Casbin | ✅ | SQLite, PostgreSQL, MySQL are supported by Diesel |
Sqlx Adapter | ORM | Casbin | ✅ | PostgreSQL, MySQL are supported by Sqlx with fully asynchronous operation |
SeaORM Adapter | ORM | @lingdu1234 | ✅ | PostgreSQL, MySQL, SQLite are supported by SeaORM with fully asynchronous operation |
SeaORM Adapter | ORM | @ZihanType | ✅ | PostgreSQL, MySQL, SQLite are supported by SeaORM with fully asynchronous operation |
Rbatis Adapter | ORM | rbatis | ✅ | MySQL, PostgreSQL, SQLite, SQL Server, MariaDB, TiDB, CockroachDB, Oracle are supported by Rbatis |
DynamodDB Adapter | NoSQL | @fospitia | ✅ | For Amazon DynamoDB |
MongoDB Adapter | MongoDB | @wangjun861205 | ✅ | For MongoDB |
JSON Adapter | String | Casbin | ✅ | For JSON |
YAML Adapter | String | Casbin | ✅ | For YAML |
Adapter | Type | Author | AutoSave | Description |
---|---|---|---|---|
File Adapter (built-in) | File | Casbin | ❌ | For .CSV (Comma-Separated Values) files |
Sequel Adapter | ORM | CasbinRuby | ✅ | ADO, Amalgalite, IBM_DB, JDBC, MySQL, Mysql2, ODBC, Oracle, PostgreSQL, SQLAnywhere, SQLite3, and TinyTDS are supported by Sequel |
Adapter | Type | Author | AutoSave | Description |
---|---|---|---|---|
File Adapter (built-in) | File | Casbin | ❌ | For .CSV (Comma-Separated Values) files |
Memory Adapter (built-in) | Memory | Casbin | ❌ | For memory |
Fluent Adapter | ORM | Casbin | ✅ | PostgreSQL, SQLite, MySQL, MongoDB are supported by Fluent |
Adapter | Type | Author | AutoSave | Description |
---|---|---|---|---|
File Adapter (built-in) | File | Casbin | ❌ | For .CSV (Comma-Separated Values) files |
Filtered File Adapter (built-in) | File | Casbin | ❌ | For .CSV (Comma-Separated Values) files with policy subset loading support |
LuaSQL Adapter | ORM | Casbin | ✅ | MySQL, PostgreSQL, SQLite3 are supported by LuaSQL |
4DaysORM Adapter | ORM | Casbin | ✅ | MySQL, SQLite3 are supported by 4DaysORM |
OpenResty Adapter | ORM | @tom2nonames | ✅ | MySQL, PostgreSQL are supported by it |
- 如果使用显式或隐式适配器调用
casbin.NewEnforcer()
,策略将自动加载。 - 您可以调用
e.LoadPolicy()
从存储中重新加载策略规则。 - 如果适配器不支持
Auto-Save
功能,当您添加或删除策略时,策略规则不能自动保存回存储。 您必须手动调用SavePolicy()
来保存所有策略规则。
示例
这里我们提供了几个示例:
文件适配器(内置)
下面展示了如何从内置文件适配器初始化一个执行器:
- Go
- PHP
- Rust
import "github.com/casbin/casbin"
e := casbin.NewEnforcer("examples/basic_model.conf", "examples/basic_policy.csv")
use Casbin\Enforcer;
$e = new Enforcer('examples/basic_model.conf', 'examples/basic_policy.csv');
use casbin::prelude::*;
let mut e = Enforcer::new("examples/basic_model.conf", "examples/basic_policy.csv").await?;
这与下面的内容相同:
- Go
- PHP
- Rust
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)
use Casbin\Enforcer;
use Casbin\Persist\Adapters\FileAdapter;
$a = new FileAdapter('examples/basic_policy.csv');
$e = new Enforcer('examples/basic_model.conf', $a);
use casbin::prelude::*;
let a = FileAdapter::new("examples/basic_policy.csv");
let e = Enforcer::new("examples/basic_model.conf", a).await?;
MySQL适配器
下面展示了如何从MySQL数据库初始化一个执行器。 它连接到127.0.0.1:3306上的MySQL DB,使用root和空密码。
- Go
- Rust
- PHP
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)
// https://github.com/casbin-rs/diesel-adapter
// make sure you activate feature `mysql`
use casbin::prelude::*;
use diesel_adapter::{ConnOptions, DieselAdapter};
let mut conn_opts = ConnOptions::default();
conn_opts
.set_hostname("127.0.0.1")
.set_port(3306)
.set_host("127.0.0.1:3306") // overwrite hostname, port config
.set_database("casbin")
.set_auth("casbin_rs", "casbin_rs");
let a = DieselAdapter::new(conn_opts)?;
let mut e = Enforcer::new("examples/basic_model.conf", a).await?;
// https://github.com/php-casbin/dbal-adapter
use Casbin\Enforcer;
use CasbinAdapter\DBAL\Adapter as DatabaseAdapter;
$config = [
// Either 'driver' with one of the following values:
// pdo_mysql,pdo_sqlite,pdo_pgsql,pdo_oci (unstable),pdo_sqlsrv,pdo_sqlsrv,
// mysqli,sqlanywhere,sqlsrv,ibm_db2 (unstable),drizzle_pdo_mysql
'driver' => 'pdo_mysql',
'host' => '127.0.0.1',
'dbname' => 'test',
'user' => 'root',
'password' => '',
'port' => '3306',
];
$a = DatabaseAdapter::newAdapter($config);
$e = new Enforcer('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
适配器有一个叫做Auto-Save
的功能。 当一个适配器支持Auto-Save
时,意味着它可以支持将单个策略规则添加到存储中,或者从存储中删除单个策略规则。 这与SavePolicy()
不同,因为后者会删除存储中的所有策略规则,并将所有Casbin执行器的策略规则保存到存储中。 因此,当策略规则的数量较大时,可能会遇到性能问题。
当适配器支持Auto-Save
时,您可以通过Enforcer.EnableAutoSave()
函数切换此选项。 该选项默认启用(如果适配器支持)。
Auto-Save
功能是可选的。 适配器可以选择实现它或者不实现。Auto-Save
只在Casbin执行器使用的适配器支持它时才起作用。- 查看上面的适配器列表中的
AutoSave
列,以查看适配器是否支持Auto-Save
。
这是一个如何使用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(...)
更多示例,请参见:https://github.com/casbin/xorm-adapter/blob/master/adapter_test.go
如何编写适配器
所有适配器都应实现Adapter接口,至少提供两个必需的方法:LoadPolicy(model model.Model) error
和 SavePolicy(model model.Model) error
。
其他三个函数是可选的。 如果适配器支持Auto-Save
功能,它们应该被实现。
方法 | 类型 | 描述 |
---|---|---|
LoadPolicy() | 必需 | 从存储中加载所有策略规则 |
SavePolicy() | 必需 | 将所有策略规则保存到存储中 |
AddPolicy() | 可选 | 将策略规则添加到存储中 |
RemovePolicy() | 可选 | 从存储中删除策略规则 |
RemoveFilteredPolicy() | 可选 | 从存储中删除与过滤器匹配的策略规则 |
如果适配器不支持Auto-Save
,它应该为这三个可选函数提供一个空的实现。 这是一个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执行器在调用这三个可选函数时会忽略not implemented
错误。
关于如何编写适配器的详细信息。
- 数据结构。 适配器应支持至少读取六列。
- 数据库名称。 默认的数据库名称应该是
casbin
。 - 表名。 默认的表名应该是
casbin_rule
。 - Ptype列。 此列的名称应为
ptype
,而不是p_type
或Ptype
。 - 表定义应为
(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
列上建立。 LoadFilteredPolicy
需要一个filter
作为参数。 过滤器应该像这样。
{
"p":[ [ "alice" ], [ "bob" ] ],
"g":[ [ "", "book_group" ], [ "", "pen_group" ] ],
"g2":[ [ "alice" ] ]
}
谁负责创建数据库?
按照惯例,如果数据库不存在,适配器应能够自动创建名为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的基础上,你可以为上下文封装你自己的处理逻辑
简单引用 gormadapter
: adapter.go