Adapters
Dans Casbin, le stockage des politiques est implémenté comme un adaptateur (aussi appelé middleware pour Casbin). Un utilisateur de Casbin peut utiliser un adaptateur pour charger des rÚgles de politique à partir d'un stockage (aka LoadPolicy()
), ou pour y sauvegarder des rĂšgles de politique (aka SavePolicy()
). Pour rester léger, nous ne mettons pas le code de l'adaptateur dans la bibliothÚque principale.
Adaptateurs pris en chargeâ
Une liste complĂšte des adaptateurs Casbin est fournie ci-dessous. Toute contribution de tiers sur un nouvel adaptateur est la bienvenue, veuillez nous en informer et nous l'ajouterons Ă cette liste :
- 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 |
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 | @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 |
- Si
casbin.NewEnforcer()
est appelé avec un adaptateur explicite ou implicite, la politique sera chargée automatiquement. - Vous pouvez appeler
e.LoadPolicy()
pour recharger les rÚgles de politique à partir du stockage. - Si l'adaptateur ne prend pas en charge la fonctionnalité
Auto-Save
, les rĂšgles de politique ne peuvent pas ĂȘtre automatiquement sauvegardĂ©es dans le stockage lorsque vous ajoutez ou supprimez des politiques. Vous devez appelerSavePolicy()
manuellement pour sauvegarder toutes les rĂšgles de politique.
Exemplesâ
Nous fournissons ici plusieurs exemples :
Adaptateur de fichier (intĂ©grĂ©)â
Voici comment initialiser un exécuteur à partir de l'adaptateur de fichier intégré :
- 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?;
C'est la mĂȘme chose avec :
- 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?;
Adaptateur MySQLâ
Voici comment initialiser un exécuteur à partir d'une base de données MySQL. il se connecte à une base de données MySQL sur 127.0.0.1:3306 avec root et sans mot de passe.
- 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);
Utilisez votre propre adaptateur de stockageâ
Vous pouvez utiliser votre propre adaptateur comme ci-dessous :
import (
"github.com/casbin/casbin"
"github.com/your-username/your-repo"
)
a := yourpackage.NewAdapter(params)
e := casbin.NewEnforcer("examples/basic_model.conf", a)
Migrer/Convertir entre diffĂ©rents adaptateursâ
Si vous voulez convertir l'adaptateur de A
Ă B
, vous pouvez faire comme ceci :
1.Charger la politique de A en mémoire
e, _ := NewEnforcer(m, A)
ou
e.SetAdapter(A)
e.LoadPolicy()
2.convertir votre adaptateur de A Ă B
e.SetAdapter(B)
3.Sauvegarder la politique de la mémoire à B
e.SavePolicy()
Charger/Sauvegarder en temps rĂ©elâ
Vous pouvez Ă©galement vouloir recharger le modĂšle, recharger la politique ou sauvegarder la politique aprĂšs l'initialisation :
// 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).
- The
Auto-Save
feature is optional. An adapter can choose to implement it or not. Auto-Save
only works for a Casbin enforcer when the adapter the enforcer uses supports it.- See the
AutoSave
column in the above adapter list to see ifAuto-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.
Method | Type | Description |
---|---|---|
LoadPolicy() | mandatory | Load all policy rules from the storage |
SavePolicy() | mandatory | Save all policy rules to the storage |
AddPolicy() | optional | Add a policy rule to the storage |
RemovePolicy() | optional | Supprimer une rĂšgle de politique du stockage |
RemoveFilteredPolicy() | optionnel | Supprimer les rĂšgles de politique qui correspondent au filtre du stockage |
Si un adaptateur ne prend pas en charge Auto-Save
, il doit fournir une implémentation vide pour les trois fonctions optionnelles. Voici un exemple pour 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")
}
L'exécuteur Casbin ignorera l'erreur non implémentée
lors de l'appel de ces trois fonctions optionnelles.
Il y a des détails sur comment écrire un adaptateur.
- Structure de données. L'adaptateur devrait supporter la lecture d'au moins six colonnes.
- Nom de la base de donnĂ©es. Le nom de base de donnĂ©es par dĂ©faut devrait ĂȘtre
casbin
. - Nom de la table. Le nom de la table par dĂ©faut devrait ĂȘtre
casbin_rule
. - Colonne Ptype. Le nom de cette colonne devrait ĂȘtre
ptype
au lieu dep_type
ouPtype
. - La dĂ©finition de la table devrait ĂȘtre
(id int primary key, ptype varchar, v0 varchar, v1 varchar, v2 varchar, v3 varchar, v4 varchar, v5 varchar)
. - L'index de clĂ© unique devrait ĂȘtre construit sur les colonnes
ptype,v0,v1,v2,v3,v4,v5
. LoadFilteredPolicy
nécessite unfilter
comme paramĂštre. Le filtre devrait ressembler Ă ceci.
{
"p":[ [ "alice" ], [ "bob" ] ],
"g":[ [ "", "book_group" ], [ "", "pen_group" ] ],
"g2":[ [ "alice" ] ]
}
Qui est responsable de la crĂ©ation de la base de donnĂ©es ?â
Par convention, l'adaptateur devrait ĂȘtre capable de crĂ©er automatiquement une base de donnĂ©es nommĂ©e casbin
si elle n'existe pas et de l'utiliser pour le stockage des politiques. Veuillez utiliser l'adaptateur Xorm comme une implémentation de référence : https://github.com/casbin/xorm-adapter
Adaptateur de contexteâ
ContextAdapter fournit une interface consciente du contexte pour les adaptateurs Casbin.
Grùce au contexte, vous pouvez implémenter des fonctionnalités telles que le contrÎle du délai d'attente pour l'API de l'adaptateur
Exempleâ
gormadapter prend en charge l'adaptateur avec contexte, voici un contrÎle de délai d'attente implémenté à l'aide du contexte
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)
}
Comment Ă©crire un adaptateur de contexteâ
ContextAdapter
API n'a qu'une couche supplémentaire de traitement de contexte que l'API Adapter
ordinaire, et sur la base de la mise en Ćuvre de l'API Adapter ordinaire, vous pouvez encapsuler votre propre logique de traitement pour le contexte
A simple reference to the gormadapter
: context_adapter.go