Skip to main content

Database enforcer provider for casbin-fastapi-decorator

Project description

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)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

casbin_fastapi_decorator_db-0.2.2.tar.gz (2.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

casbin_fastapi_decorator_db-0.2.2-py3-none-any.whl (3.9 kB view details)

Uploaded Python 3

File details

Details for the file casbin_fastapi_decorator_db-0.2.2.tar.gz.

File metadata

  • Download URL: casbin_fastapi_decorator_db-0.2.2.tar.gz
  • Upload date:
  • Size: 2.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.10.9 {"installer":{"name":"uv","version":"0.10.9","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}

File hashes

Hashes for casbin_fastapi_decorator_db-0.2.2.tar.gz
Algorithm Hash digest
SHA256 1f1dc26544d9e2b85c99c023e5d1bc5b4ca7e7f20c48fe8c34cdbcf4af5f2aa1
MD5 53419a76b9fb42e9653fb36952e052e4
BLAKE2b-256 d23f965d9d645af467af0bdbf14287f9ec392e3b7dd5319e08137fcc2f9cb51d

See more details on using hashes here.

File details

Details for the file casbin_fastapi_decorator_db-0.2.2-py3-none-any.whl.

File metadata

  • Download URL: casbin_fastapi_decorator_db-0.2.2-py3-none-any.whl
  • Upload date:
  • Size: 3.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.10.9 {"installer":{"name":"uv","version":"0.10.9","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}

File hashes

Hashes for casbin_fastapi_decorator_db-0.2.2-py3-none-any.whl
Algorithm Hash digest
SHA256 93b4344e6c4b3a171d167b2e34fef25c57f7c90efb46ef22b23feb2b59370ef8
MD5 b3902b8d77fda6cdb2aa8aabc565b424
BLAKE2b-256 88d87137be8ed4e8b1f8d3c01e725d80a9f089f1d9121408cb5625523866c236

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page