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

# 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
from permissions2fast_fastapi import permissions_router, roles_router
from oauth2fast_fastapi import router as auth_router

app = FastAPI()

app.include_router(auth_router)
app.include_router(permissions_router)
app.include_router(roles_router)

2. 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.

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)

Download files

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

Source Distribution

permissions2fast_fastapi-0.8.4.tar.gz (25.2 kB view details)

Uploaded Source

Built Distribution

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

permissions2fast_fastapi-0.8.4-py3-none-any.whl (31.5 kB view details)

Uploaded Python 3

File details

Details for the file permissions2fast_fastapi-0.8.4.tar.gz.

File metadata

File hashes

Hashes for permissions2fast_fastapi-0.8.4.tar.gz
Algorithm Hash digest
SHA256 5af5ce2985b07750ad31612e6fcfacf733aca1861464cff69ec1f40b121afb5a
MD5 cd223f39100416b3a4611bdca60559b3
BLAKE2b-256 b0dbf47c9c869c9b8c63773a5bfa00e1744a8c1c2287148705b3402388f36518

See more details on using hashes here.

File details

Details for the file permissions2fast_fastapi-0.8.4-py3-none-any.whl.

File metadata

File hashes

Hashes for permissions2fast_fastapi-0.8.4-py3-none-any.whl
Algorithm Hash digest
SHA256 f1fff5d617413680efce8b32db7283040cbc8428909d31ca2c373ed730ddc6e0
MD5 c440a6662b3d01a0816b5dcb36c26a27
BLAKE2b-256 a1cab81a0edbef19258acbd88dd4bba999e84767af623d1c498876f793980fd3

See more details on using hashes here.

Release history Release notifications | RSS feed

This release

0.8.4 This release

2 files

0.8.3

2 files

0.8.2

2 files

0.8.1

2 files

0.8.0

2 files

0.7.1

2 files

0.7.0

2 files

0.6.0

2 files

0.5.1

2 files

0.5.0

2 files

0.4.0

2 files

0.3.0

2 files

0.2.0

2 files

0.1.3

2 files

0.1.2

2 files

0.1.1

2 files

0.1.0

2 files

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