casbin-fastapi-decorator-db
Database enforcer provider for casbin-fastapi-decorator.
Loads Casbin policies from a SQLAlchemy async session and creates a casbin.Enforcer per request.
Installation
pip install casbin-fastapi-decorator-db
Or via the core package extra:
pip install "casbin-fastapi-decorator[db]"
Usage
Define a SQLAlchemy ORM model for your policy table:
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
class Base(DeclarativeBase):
pass
class PolicyORM(Base):
__tablename__ = "policies"
id: Mapped[int] = mapped_column(primary_key=True)
sub: Mapped[str]
obj: Mapped[str]
act: Mapped[str]
Create the provider and pass it to PermissionGuard:
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from casbin_fastapi_decorator_db import DatabaseEnforcerProvider
from casbin_fastapi_decorator import PermissionGuard
from fastapi import FastAPI, HTTPException
engine = create_async_engine("sqlite+aiosqlite:///./policies.db")
AsyncSessionLocal = async_sessionmaker(engine, class_=AsyncSession)
async def get_current_user() -> dict:
return {"sub": "alice", "role": "admin"}
enforcer_provider = DatabaseEnforcerProvider(
model_path="model.conf",
session_factory=AsyncSessionLocal,
policy_model=PolicyORM,
policy_mapper=lambda p: (p.sub, p.obj, p.act),
default_policies=[("admin", "*", "*")], # optional
)
guard = PermissionGuard(
user_provider=get_current_user,
enforcer_provider=enforcer_provider,
error_factory=lambda user, *rv: HTTPException(403, "Forbidden"),
)
app = FastAPI()
@app.get("/articles")
@guard.require_permission("articles", "read")
async def list_articles():
return []
API
DatabaseEnforcerProvider
DatabaseEnforcerProvider(
model_path: str,
session_factory: async_sessionmaker[AsyncSession],
policy_model: type,
policy_mapper: Callable[[Any], tuple],
default_policies: list[tuple] = [],
)
| Parameter | Description |
|---|---|
model_path |
Path to the Casbin model .conf file |
session_factory |
SQLAlchemy async_sessionmaker |
policy_model |
ORM model class representing the policy table |
policy_mapper |
Function that maps an ORM row to a (sub, obj, act) tuple |
default_policies |
Static policies added on top of the database policies (default: []) |
On each request the provider opens a session, loads all rows from the policy table, maps them via policy_mapper, merges with default_policies, and returns a fresh casbin.Enforcer.
Development
See the workspace README for setup instructions.
task db:lint # ruff + bandit + ty
task db:test # pytest (requires Docker for testcontainers)
Metadata
Release files for casbin-fastapi-decorator-db 1.3.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| casbin_fastapi_decorator_db-1.3.1.tar.gz | 4.3 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| casbin_fastapi_decorator_db-1.3.1-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 9.7 kB
Release files / casbin_fastapi_decorator_db-1.3.1.tar.gz
| Download URL | casbin_fastapi_decorator_db-1.3.1.tar.gz |
|---|---|
| Size | 4.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
40db71bc3b76ebb5eb0fc36693ce35de7ff911adcb9afd4be336c8847d11fe25
|
|
BLAKE2b-256 checksum How to use checksums |
5aec688becebc60d37e129abfe54a4b66f5782ebd5baa2cf03c23125b93c4e85
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.12.23 {"installer":{"name":"uv","version":"0.12.23","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Release files / casbin_fastapi_decorator_db-1.3.1-py3-none-any.whl
| Download URL | casbin_fastapi_decorator_db-1.3.1-py3-none-any.whl |
|---|---|
| Size | 5.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
af5254d53ec8594a978cd37aa2100b3a0405fb1d2a3585723f94b7f702b920d5
|
|
BLAKE2b-256 checksum How to use checksums |
e7564cd055831dd6b288b770be8e37a2a65219d8e99343aff98d3e13bddd5318
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.12.23 {"installer":{"name":"uv","version":"0.12.23","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|