Adapters
Casbin에서 정책 저장소는 어댑터(즉, Casbin의 미들웨어)로 구현됩니다. Casbin 사용자는 어댑터를 사용하여 저장소에서 정책 규칙을 로드(즉, LoadPolicy()
)하거나 정책 규칙을 저장(즉, SavePolicy()
)할 수 있습니다. 가벼운 무게를 유지하기 위해, 우리는 어댑터 코드를 주 라이브러리에 넣지 않습니다.
지원되는 어댑터
아래에 Casbin 어댑터의 전체 목록이 제공됩니다. 새로운 어댑터에 대한 제3자의 기여는 환영이며, 우리에게 알려주시면 이 목록에 추가하겠습니다:
- 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 |
Pgx Adapter | SQL | @gtoxlili | ✅ | PostgreSQL is supported by pgx, supports customizable column count |
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 |
NATS JetStream Adapter | KV store | grepplabs | ✅ | For NATS JetStream |
Kubernetes Adapter | Cloud | grepplabs | ✅ | For Kubernetes |
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 |
String Adapter | String | Casbin | ❌ | For String |
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에서 root와 빈 비밀번호로 MySQL DB에 연결합니다.
- 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 enforcer의 모든 정책 규칙을 저장소에 저장합니다. 따라서 정책 규칙의 수가 많을 경우 성능 문제가 발생할 수 있습니다.
어댑터가 Auto-Save
를 지원할 때, Enforcer.EnableAutoSave()
함수를 통해 이 옵션을 전환할 수 있습니다. 이 옵션은 기본적으로 활성화되어 있습니다(어댑터가 지원하는 경우).
Auto-Save
기능은 선택 사항입니다. 어댑터는 이를 구현하거나 구현하지 않을 수 있습니다.Auto-Save
는 어댑터가 지원할 때만 Casbin enforcer에 대해 작동합니다.- 어댑터가
Auto-Save
를 지원하는지 확인하려면 위의 어댑터 목록에서AutoSave
열을 참조하십시오.
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
어댑터 작성 방법
모든 어댑터는 적어도 두 가지 필수 메서드인 LoadPolicy(model model.Model) error
와 SavePolicy(model model.Model) error
를 제공하여 Adapter 인터페이스를 구현해야 합니다.
나머지 세 가지 함수는 선택 사항입니다. 어댑터가 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 enforcer는 이 세 가지 선택적 함수를 호출할 때 'not implemented' 오류를 무시합니다.
어댑터를 작성하는 방법에 대한 세부 정보가 있습니다.
- 데이터 구조. 어댑터는 최소한 여섯 개의 열을 읽을 수 있어야 합니다.
- 데이터베이스 이름. 기본 데이터베이스 이름은 'casbin'이어야 합니다.
- 테이블 이름. 기본 테이블 이름은 'casbin_rule'이어야 합니다.
- Ptype 열. 이 열의 이름은 'p_type' 또는 'Ptype' 대신 '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": ["", "domain1"],
"g": ["", "", "domain1"]
}
데이터베이스를 생성할 책임이 누구인가요?
관례적으로, 어댑터는 존재하지 않는 경우 'casbin'이라는 데이터베이스를 자동으로 생성하고 정책 저장소로 사용할 수 있어야 합니다. 참조 구현으로 Xorm 어댑터를 사용하십시오: https://github.com/casbin/xorm-adapter
Update Adapter
The UpdateAdapter
interface extends the basic Adapter
interface to support updating policies directly in the storage. This is more efficient than removing and re-adding policies when you need to modify existing rules.
An adapter that implements the UpdateAdapter
interface should provide the following methods:
Method | Type | Description |
---|---|---|
UpdatePolicy() | optional | Update a single policy rule in the storage |
UpdatePolicies() | optional | Update multiple policy rules in the storage |
UpdateFilteredPolicies() | optional | Update policy rules that match the filter in the storage |
예시
Here's an example of using the update adapter methods:
import (
"github.com/casbin/casbin/v2"
"github.com/casbin/gorm-adapter/v3"
)
a, _ := gormadapter.NewAdapter("mysql", "root:@tcp(127.0.0.1:3306)/")
e, _ := casbin.NewEnforcer("examples/rbac_model.conf", a)
// Update a single policy
// Change: p, alice, data1, read -> p, alice, data1, write
e.UpdatePolicy(
[]string{"alice", "data1", "read"},
[]string{"alice", "data1", "write"},
)
// Update multiple policies at once
e.UpdatePolicies(
[][]string{{"alice", "data1", "write"}, {"bob", "data2", "read"}},
[][]string{{"alice", "data1", "read"}, {"bob", "data2", "write"}},
)
// Update all policies matching a filter
e.UpdateFilteredPolicies(
[][]string{{"alice", "data1", "write"}},
0,
"alice", "data1", "read",
)
How to write an update adapter
To implement the UpdateAdapter
interface, your adapter needs to implement the update methods in addition to the basic Adapter
interface:
// UpdatePolicy updates a policy rule from storage.
// This is part of the UpdateAdapter interface.
func (a *Adapter) UpdatePolicy(sec string, ptype string, oldRule, newRule []string) error {
// Implementation to update the policy in storage
// For example, in SQL: UPDATE casbin_rule SET v0=?, v1=?, v2=? WHERE ptype=? AND v0=? AND v1=? AND v2=?
return nil
}
// UpdatePolicies updates multiple policy rules in the storage.
// This is part of the UpdateAdapter interface.
func (a *Adapter) UpdatePolicies(sec string, ptype string, oldRules, newRules [][]string) error {
// Implementation to update multiple policies in storage
// This should be done in a transaction for consistency
return nil
}
// UpdateFilteredPolicies updates policy rules that match the filter from the storage.
// This is part of the UpdateAdapter interface.
func (a *Adapter) UpdateFilteredPolicies(sec string, ptype string, newRules [][]string, fieldIndex int, fieldValues ...string) error {
// Implementation to update filtered policies in storage
// First find policies matching the filter, then update them
return nil
}
If an adapter doesn't support the UpdateAdapter
interface, Casbin will automatically fall back to using the combination of RemovePolicy()
and AddPolicy()
operations.
컨텍스트 어댑터
ContextAdapter는 Casbin 어댑터에 대한 컨텍스트 인식 인터페이스를 제공합니다.
컨텍스트를 통해 어댑터 API에 대한 타임아웃 제어와 같은 기능을 구현할 수 있습니다
Example
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
: adapter.go
Transaction
Casbin now supports Transactions. Here's an example about how to use Transaction
in gormadapter
:
db, _ := gorm.Open(...)
adapter, _ := gormadapter.NewTransactionalAdapterByDB(db)
e, _ := casbin.NewTransactionalEnforcer("examples/rbac_model.conf", adapter)
ctx := context.Background()
// WithTransaction executes a function within a transaction.
// If the function returns an error, the transaction is rolled back.
// Otherwise, it's committed automatically.
err := e.WithTransaction(ctx, func(tx *casbin.Transaction) error {
tx.AddPolicy("alice", "data1", "read")
tx.AddPolicy("alice", "data1", "write")
return nil
})
// If you wish to manually handle the transaction
tx, _ := e.BeginTransaction(ctx)
tx.AddPolicy("alice", "data1", "write")
if err := tx.Commit(); err != nil {
// handle if transaction failed
}
To add this capability to your adapter, you need to implement TransactionalAdapter
and TransactionContext
in persist/transaction.go.
Code reference to the gormadapter
: adapter.go