Skip to main content

permissions2fast-fastapi

🔒 Role-Based Access Control (RBAC) extension for oauth2fast-fastapi.

📖 Conventions reference: this package follows the 2fast-handbook for ecosystem conventions (structure, versioning, README, commits, release).

Easily manage user roles and permissions in your FastAPI application with support for High-Performance Redis Caching.

Features

  • 👥 Role Management: Create, assign, and manage roles for users.
  • 🔑 Granular Permissions: Define specific permissions and assign them to roles or directly to users (polymorphic assignments).
  • � Redis Caching (Optional): High-performance permission evaluation using Redis to minimize database lookups.
  • �🛡️ Route Protection: Dependencies to protect endpoints based on roles or permissions.
  • ⚡ Async Support: Fully async database interactions via pgsqlasync2fast-fastapi.
  • 🔌 Seamless Integration: Built to extend oauth2fast-fastapi.

Installation

pip install permissions2fast-fastapi

Configuration

This package uses the same database connection logic as oauth2fast-fastapi. Configure your environment variables in .env.

Basic Settings

# JWT / refresh tokens (shared with oauth2fast-fastapi)
SECRET_KEY=your-secure-secret-key
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=15
REFRESH_TOKEN_EXPIRE_MINUTES=10080
REFRESH_COOKIE_SECURE=true
REFRESH_COOKIE_SAMESITE=strict
# REDIS_URL=redis://localhost:6379/0

# Database Configuration
DB_CONNECTIONS__AUTH__USERNAME=db_user
DB_CONNECTIONS__AUTH__PASSWORD=db_password
DB_CONNECTIONS__AUTH__HOST=localhost
DB_CONNECTIONS__AUTH__DATABASE=db_name
DB_CONNECTIONS__AUTH__PORT=5432

Advanced Features (Redis)

You can enable Redis caching by setting the following environment variables:

PERMISSIONS_REDIS_RBAC_ENABLED=True

# Redis connection details (if caching is enabled)
PERMISSIONS_REDIS__HOST=localhost
PERMISSIONS_REDIS__PORT=6379
PERMISSIONS_REDIS__DB=0
# PERMISSIONS_REDIS__PASSWORD=your_redis_password

Usage

1. Basic Integration

from fastapi import FastAPI, Depends
from permissions2fast_fastapi import permissions_router, roles_router, has_role
from oauth2fast_fastapi import public_router, admin_router
from tools2fast_fastapi import install_auth_error_handler

app = FastAPI()
install_auth_error_handler(app)  # standardized 401/403 envelope

# Public auth endpoints (token, register, verify-email, logout)
app.include_router(public_router)

# Admin auth endpoints with RBAC injection
app.include_router(admin_router, dependencies=[Depends(has_role("admin"))])

# Permissions and roles management (protect as needed)
app.include_router(permissions_router)
app.include_router(roles_router)

2. Bootstrap an Admin User

# 1. Create admin user (verified, no roles)
python -m oauth2fast_fastapi.scripts.create_admin \
    --email admin@example.com \
    --password 'StrongPassword123'

# 2. Assign admin role (creates role if it doesn't exist)
python -m permissions2fast_fastapi.scripts.assign_role \
    --email admin@example.com \
    --role admin

Base roles (admin, user, manager, guest) are auto-seeded at startup by the pgsqlasync2fast-fastapi orchestrator from seeders/{dev,prod}/roles.json.

3. Protecting Routes

Use the provided dependencies to restrict access to endpoints. The system will automatically check Redis cache if enabled, and fallback to database queries if needed.

Denials are HTTP 403 with a stable error.type (RoleMissing or PermissionDenied) and no WWW-Authenticate header, so clients can show an authorization error without logging the user out. Install install_auth_error_handler(app) once at startup to get the project envelope.

from fastapi import Depends
from permissions2fast_fastapi.dependencies import has_permission, has_role
from oauth2fast_fastapi.models import User

# Require a specific role
@app.get("/admin-dashboard")
async def admin_dashboard(user: User = Depends(has_role("admin"))):
    return {"message": "Welcome Admin"}

# Require a specific permission
@app.get("/edit-post")
async def edit_post(user: User = Depends(has_permission("posts.edit"))):
    return {"message": "You can edit posts"}

3. Using the Default Seeder

To quickly set up default access control for the package routes itself (admin role and necessary permissions to add/remove routes, roles, and permissions), you can use the built-in JSON seeder during the application startup process (lifespan).

from contextlib import asynccontextmanager
from fastapi import FastAPI
from pgsqlasync2fast_fastapi import startup_database, get_db_manager
from oauth2fast_fastapi import get_db_engine, AuthModel
from permissions2fast_fastapi import seed_rbac_from_json

@asynccontextmanager
async def lifespan(app: FastAPI):
    # This example assumes you have an 'auth' bound session using pgsqlasync2fast-fastapi
    await startup_database()

    # List configured connections
    manager = get_db_manager()

    # Create auth database tables
    engine = get_db_engine("auth", manager)
    async with engine.begin() as conn:
        # Create auth tables (User, etc.)
        await conn.run_sync(AuthModel.metadata.create_all)
    # Run the seeder when starting up your application
    session = await manager.get_session("auth")
    try:
        # Seeder is idempotent and won't duplicate data on multiple startups
        await seed_rbac_from_json(session, route_prefix="")
    finally:
        await session.close()

app = FastAPI(lifespan=lifespan)

📋 Naming Conventions

This package follows consistent naming conventions for models and database tables:

Model Classes (Python)

  • Singular PascalCase
  • Examples: User, Role, Permission, Route, RoleUser

Database Tables

  • Plural snake_case
  • Examples: users, roles, permissions, routes, role_users

Many-to-Many Join Tables

  • Plural snake_case on both table names
  • Alphabetical order of the two table names
  • Examples: role_users (r < u), permission_roles (p < r)

Seeders

The package ships a base RBAC dataset and registers it automatically when imported. A consuming app only needs RUN_SEEDERS=true to get roles, categories, permissions and the global route links.

Data layout

permissions2fast_fastapi/seeders/
  manifest.json          # v2.0, explicit uuid7 literals, natural_key by name
  boot/categories.json
  boot/roles.json
  boot/permissions.json

The manifest is validated in CI:

from pgsqlasync2fast_fastapi import validate_seeders_report

report = validate_seeders_report(
    "permissions2fast_fastapi/seeders/manifest.json",
    {"categories": Category, "roles": Role, "permissions": Permission},
    profile="dev",
)
assert report.errors == [] and report.warnings == []

Route manifests (JSON)

Declare guarded GLOBAL routes as JSON and let the package seed routes, permissions grants and permission_routes:

[
  {"method": "GET",  "path": "/roles", "permission": "roles:read",  "roles": ["admin"]},
  {"method": "POST", "path": "/roles", "permission": "roles:write", "roles": ["admin"]}
]
from permissions2fast_fastapi import (
    load_route_manifest,
    validate_route_manifest,
    seed_global_routes,
)

errors = validate_route_manifest("app/routes/global.json")
assert errors == []

specs = load_route_manifest("app/routes/global.json")
await seed_global_routes(session, specs, profile="dev")

Routes are idempotent by (method, path); links are idempotent by (permission, route).

Adopting explicit ids

Existing databases are migrated to the manifest literals on boot:

from permissions2fast_fastapi import adopt_explicit_seed_ids

await adopt_explicit_seed_ids(session, profile="dev")
await session.commit()

The permissions-global migration chain rebuilds RBAC FKs with ON UPDATE CASCADE, so ids are updated in place and children follow.

UUID migration coordination (0.12.2+)

role_users.user_id and permission_assignments.entity_id (entity_type="User") are backfilled from the _uuid_migration_user_map table left by oauth2fast-fastapi >= 0.8.2. If the map is absent (auth-only databases migrated with 0.8.1), the previous no-backfill behavior is kept. Upgrade the AUTH lane in order: oauth -> permissions -> tenant2fast-auth.

Metadata

Release files for permissions2fast-fastapi 0.14.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for permissions2fast-fastapi 0.14.2
File Size Uploaded Provenance Actions
permissions2fast_fastapi-0.14.2.tar.gz 47.6 kB Without provenance Details for permissions2fast_fastapi-0.14.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for permissions2fast-fastapi 0.14.2
File Interpreter ABI Platform Actions
permissions2fast_fastapi-0.14.2-py3-none-any.whl Python 3 none any Details for permissions2fast_fastapi-0.14.2-py3-none-any.whl

Total release size: 94.8 kB

Release files / permissions2fast_fastapi-0.14.2.tar.gz

Download URL permissions2fast_fastapi-0.14.2.tar.gz
Size 47.6 kB
Tags Source
SHA-256 checksum
How to use checksums
9a6dc07b02d58d8678f511fb86f8d35866653d6c88989f1adc099d7da838cbb9
BLAKE2b-256 checksum
How to use checksums
33c6ee0514e5247f672be09b94d6d83aed80f86a92be09e3bcdf33cb5ac2c1ce
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.10

Release files / permissions2fast_fastapi-0.14.2-py3-none-any.whl

Download URL permissions2fast_fastapi-0.14.2-py3-none-any.whl
Size 47.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e4e03a36c04de6e7acc59f64e2fb0a657e9409500688cb47bb80255a55091277
BLAKE2b-256 checksum
How to use checksums
2ea8aaeaf320611d7907361a7c53aa11fc5d51e40218074b7ed20e317d5b06a7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.10

Security for permissions2fast-fastapi 0.14.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.14.2 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page