postgres-adapter uses tokio-postgres and deadpool-postgres as an adapter for Casbin-rs. With this library, Casbin can load policy from Postgres or save policy to it with fully asynchronous support and prepared statements.
Add it to Cargo.toml
postgres-adapter = { version = "0.1.0" }
tokio = "1.19.2"
-
Set up database environment
#!/bin/bash docker run -itd \ --restart always \ -e POSTGRES_USER=casbin_rs \ -e POSTGRES_PASSWORD=casbin_rs \ -e POSTGRES_DB=casbin \ -p 5432:5432 \ -v /srv/docker/postgresql:/var/lib/postgresql \ postgres:11;
-
Create table
casbin_rule
# PostgreSQL psql postgres://casbin_rs:[email protected]:5432/casbin -c "CREATE TABLE IF NOT EXISTS casbin_rule ( id SERIAL PRIMARY KEY, ptype VARCHAR NOT NULL, v0 VARCHAR NOT NULL, v1 VARCHAR NOT NULL, v2 VARCHAR NOT NULL, v3 VARCHAR NOT NULL, v4 VARCHAR NOT NULL, v5 VARCHAR NOT NULL, CONSTRAINT unique_key_sqlx_adapter UNIQUE(ptype, v0, v1, v2, v3, v4, v5) );"
-
Configure
env
Rename
sample.env
to.env
and putDATABASE_URL
,POOL_SIZE
insideDATABASE_URL=postgres://casbin_rs:casbin_rs@localhost:5432/casbin POOL_SIZE=8
Or you can export
DATABASE_URL
,POOL_SIZE
export DATABASE_URL=postgres://casbin_rs:casbin_rs@localhost:5432/casbin export POOL_SIZE=8
use postgres_adapter::casbin::prelude::*;
use postgres_adapter::casbin::Result;
use postgres_adapter::TokioPostgresAdapter;
use tokio_postgres::NoTls;
#[tokio::main]
async fn main() -> Result<()> {
let m = DefaultModel::from_file("examples/rbac_model.conf").await?;
let a = TokioPostgresAdapter::new("postgres://casbin_rs:[email protected]:5432/casbin", 8, NoTls).await?;
let mut e = Enforcer::new(m, a).await?;
Ok(())
}
postgres