Skip to main content

Bitwise permission system for Python with SQLAlchemy and FastAPI integration

Project description

binauth

CI PyPI version

A bitwise permission system for Python with SQLAlchemy and FastAPI integration.

Features

  • Bitwise permission storage (up to 32 actions per scope)
  • Type-safe permission definitions using IntEnum
  • Async SQLAlchemy repository
  • FastAPI integration with dependency injection
  • Permission discovery endpoint for admin UIs
  • TTL-based permission caching
  • Generic user ID support (int, UUID, str)

Installation

From GitHub

# Core only
pip install git+https://github.com/insmnia/binauth.git

# With SQLAlchemy support
pip install "binauth[db] @ git+https://github.com/insmnia/binauth.git"

# With FastAPI support
pip install "binauth[fastapi] @ git+https://github.com/insmnia/binauth.git"

# All dependencies
pip install "binauth[all] @ git+https://github.com/insmnia/binauth.git"

From PyPI (when published)

pip install binauth
pip install binauth[db]       # With SQLAlchemy
pip install binauth[fastapi]  # With FastAPI
pip install binauth[all]      # All dependencies

Quick Start

Define Permissions

from enum import IntEnum
from typing import ClassVar
from binauth import PermissionActionRegistry, PermissionsManager

class TaskPermissions(PermissionActionRegistry):
    scope_name = "tasks"
    category = "Content Management"  # For grouping in admin UI
    description = "Task management permissions"

    class Actions(IntEnum):
        CREATE = 1 << 0  # 1
        READ = 1 << 1    # 2
        UPDATE = 1 << 2  # 4
        DELETE = 1 << 3  # 8

    # Optional: descriptions for admin UI
    action_descriptions: ClassVar[dict[str, str]] = {
        "CREATE": "Create new tasks",
        "READ": "View tasks",
        "UPDATE": "Edit tasks",
        "DELETE": "Remove tasks",
    }

manager = PermissionsManager([TaskPermissions])

Check Permissions

class User:
    def __init__(self, permissions: dict[PermissionScope, PermissionBinLevel]):
        self.permissions = permissions

# User has CREATE and READ permissions (level = 3)
user = User(permissions={"tasks": 3})

# Check single permission
has_read = manager.check_permission(user, "tasks", TaskPermissions.Actions.READ)

# Check multiple permissions (all required)
has_all = manager.check_permissions(
    user,
    "tasks",
    [TaskPermissions.Actions.READ, TaskPermissions.Actions.UPDATE],
    require_all=True,
)

# Check multiple permissions (any required)
has_any = manager.check_permissions(
    user,
    "tasks",
    [TaskPermissions.Actions.CREATE, TaskPermissions.Actions.DELETE],
    require_all=False,
)

FastAPI Integration

from fastapi import FastAPI, Depends
from binauth import (
    create_permission_dependency,
    get_permissions_router,
    setup_permission_exception_handler,
)

app = FastAPI()
setup_permission_exception_handler(app)

# Option 1: Pass user ID directly
permission = create_permission_dependency(
    manager=manager,
    get_db=get_db,
    get_current_user_id=get_current_user_id,  # Returns int/UUID/str
    cache_ttl=60,
)

# Option 2: Pass user object with .id attribute
permission = create_permission_dependency(
    manager=manager,
    get_db=get_db,
    get_current_user=get_current_user,  # Returns User with .id
    cache_ttl=60,
)

# Protected endpoint
@app.get("/tasks")
async def list_tasks(
    user_id: int = Depends(permission.require("tasks", TaskPermissions.Actions.READ))
):
    return {"tasks": [...]}

# Permission discovery endpoint (for admin UI)
app.include_router(get_permissions_router(manager, get_current_user))
# GET /permissions returns all available permissions grouped by category

Database Storage

from binauth import AsyncPermissionRepository, Base

# Create tables
async with engine.begin() as conn:
    await conn.run_sync(Base.metadata.create_all)

# Use repository
async with async_session() as session:
    repo = AsyncPermissionRepository(session, manager)

    # Grant permissions
    await repo.grant_actions(user_id, "tasks", TaskPermissions.Actions.READ)

    # Check permissions
    has_perm = await repo.has_permission(
        user_id, "tasks", TaskPermissions.Actions.READ
    )

    # Get all user permissions
    perms = await repo.get_all_user_permissions(user_id)

Permission Discovery

Get all available permissions for admin UIs:

schema = manager.get_permissions_schema()
# Returns:
# [
#     {
#         "name": "Content Management",
#         "scopes": [
#             {
#                 "name": "tasks",
#                 "description": "Task management permissions",
#                 "actions": [
#                     {"name": "CREATE", "value": 1, "description": "Create new tasks"},
#                     {"name": "READ", "value": 2, "description": "View tasks"},
#                     ...
#                 ]
#             }
#         ]
#     }
# ]

Limitations

  • Maximum 32 actions per scope (uses PostgreSQL INTEGER for storage)
  • Action values must be powers of 2 (1 << n where 0 <= n <= 31)

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

binauth-0.3.0.tar.gz (12.8 kB view details)

Uploaded Source

Built Distribution

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

binauth-0.3.0-py3-none-any.whl (15.5 kB view details)

Uploaded Python 3

File details

Details for the file binauth-0.3.0.tar.gz.

File metadata

  • Download URL: binauth-0.3.0.tar.gz
  • Upload date:
  • Size: 12.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for binauth-0.3.0.tar.gz
Algorithm Hash digest
SHA256 677155842cc066f6cdc41bf29a8be5bf15f9d64c8195fb27dae6957fdb1d818c
MD5 cd12c9be905887bf4b73db3ea2ed19cd
BLAKE2b-256 721c3a417d3b807979809d010d1d711d6177c5e53a57eef76a7cb90ff09f1994

See more details on using hashes here.

Provenance

The following attestation bundles were made for binauth-0.3.0.tar.gz:

Publisher: publish.yml on insmnia/binauth

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file binauth-0.3.0-py3-none-any.whl.

File metadata

  • Download URL: binauth-0.3.0-py3-none-any.whl
  • Upload date:
  • Size: 15.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for binauth-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 df2c29aa886ef7717614a71006c07606550eaee02b0d4c2719da6c76ebc221b9
MD5 af6c5dc201949d48f852f71503b8d710
BLAKE2b-256 d8f23da627967bc23ea7895e1c27cef87c614be8212fcc86db4a5345a7e06a87

See more details on using hashes here.

Provenance

The following attestation bundles were made for binauth-0.3.0-py3-none-any.whl:

Publisher: publish.yml on insmnia/binauth

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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