API Reference

class litestar_permissions.Permission[source]

A granular action like ‘application:deploy’. Use create_models() to get concrete ORM classes.

class litestar_permissions.PermissionResolver[source]

Resolves whether a user has a specific permission, optionally scoped to a resource.

Supports hierarchical inheritance: if a user has org-admin on org X, they inherit all permissions on projects and applications within org X.

__init__(config, models)[source]
Parameters:
Return type:

None

async can(user_id, permission, resource_type=None, resource_id=None, *, db)[source]

Check if user has the given permission, optionally scoped to a resource.

Return type:

bool

Parameters:
async get_user_permissions(user_id, resource_type=None, resource_id=None, *, db)[source]

Get all permission codenames a user has at the given scope (+ ancestors).

Return type:

set[str]

Parameters:
invalidate_user(user_id)[source]

Remove all cached entries for a user.

Return type:

None

Parameters:

user_id (UUID | str)

invalidate_all()[source]

Clear the entire cache.

Return type:

None

class litestar_permissions.PermissionsConfig[source]

Configuration for the permissions plugin.

table_prefix: str = ''
class_prefix: str = ''
cache_ttl: int = 300
cache_max_size: int = 10000
hierarchy: dict[str, str]
resource_resolver: Callable[[...], Any] | None = None
user_key: str = 'user'
superuser_bypass: bool = True
__init__(table_prefix='', class_prefix='', cache_ttl=300, cache_max_size=10000, hierarchy=<factory>, resource_resolver=None, user_key='user', superuser_bypass=True)
Parameters:
Return type:

None

class litestar_permissions.PermissionsPlugin[source]

Litestar plugin for fine-grained hierarchical RBAC.

Note

Consumers must populate scope["db_session"] with a per-request AsyncSession for guards and middleware to function. This is typically done via middleware or a dependency that writes to the ASGI scope.

Example:

from litestar_permissions import PermissionsPlugin, PermissionsConfig

config = PermissionsConfig(
    hierarchy={"application": "project", "project": "organization"},
)

app = Litestar(
    plugins=[PermissionsPlugin(config=config, base=Base)],
)
__init__(config=None, base=None, models=None)[source]
Parameters:
Return type:

None

on_app_init(app_config)[source]

Receive the AppConfig instance after on_app_init hooks have been called.

Examples

from litestar import Litestar, get
from litestar.di import Provide
from litestar.plugins import InitPluginProtocol


def get_name() -> str:
    return "world"


@get("/my-path")
def my_route_handler(name: str) -> dict[str, str]:
    return {"hello": name}


class MyPlugin(InitPluginProtocol):
    def on_app_init(self, app_config: AppConfig) -> AppConfig:
        app_config.dependencies["name"] = Provide(get_name)
        app_config.route_handlers.append(my_route_handler)
        return app_config


app = Litestar(plugins=[MyPlugin()])
Parameters:

app_config (AppConfig) – The AppConfig instance.

Return type:

AppConfig

Returns:

The app config object.

class litestar_permissions.ResourceProtocol[source]

Interface for resources that permissions can be scoped to.

property id: UUID | str | int
property resource_type: str

e.g. ‘organization’, ‘project’, ‘application’

property parent: ResourceProtocol | None

Parent resource for hierarchy traversal. None = top-level.

__init__(*args, **kwargs)
class litestar_permissions.Role[source]

Named role that groups permissions. Use create_models() to get concrete ORM classes.

class litestar_permissions.RolePermission[source]

Many-to-many: which permissions belong to which role. Use create_models() to get concrete ORM classes.

class litestar_permissions.UserProtocol[source]

Interface that user models must satisfy for permission resolution.

property id: UUID | str | int
property is_superuser: bool
__init__(*args, **kwargs)
class litestar_permissions.UserRoleAssignment[source]

Assigns a role to a user, optionally scoped to a resource. Use create_models() to get concrete ORM classes.

litestar_permissions.create_models(base, table_prefix='', class_prefix='')[source]

Factory that creates concrete RBAC models bound to the app’s Base.

Parameters:
  • base (type[DeclarativeBase]) – The SQLAlchemy declarative base to bind models to.

  • table_prefix (str) – Prefix for database table names.

  • class_prefix (str) – Cosmetic prefix for ORM class __name__ attributes, affecting repr() and logging output. For actual registry conflict avoidance, remove the conflicting model or use PermissionsPlugin(models=...) to inject pre-created models.

Return type:

dict[str, type]

Returns dict with keys: ‘Role’, ‘Permission’, ‘RolePermission’, ‘UserRoleAssignment’

litestar_permissions.require_permission(*permissions, resource_type_param=None, resource_id_param=None)[source]

Guard factory that checks if the current user has ALL of the specified permissions.

Parameters:
  • permissions (str) – Permission codenames the user must have (e.g. “application:deploy”).

  • resource_type_param (str | None) – Path/query param name that holds the resource type. If None, uses resource_id_param with a fixed resource_type from the guard config.

  • resource_id_param (str | None) – Path/query param name that holds the resource ID.

Return type:

Any

Usage:

@get(“/apps/{app_id}/deploy”, guards=[require_permission(“application:deploy”, resource_id_param=”app_id”)])

Note

Consumers must populate connection.scope["db_session"] with a per-request AsyncSession (e.g. via middleware or a dependency that writes to scope).

litestar_permissions.require_role(*role_names, resource_type_param=None, resource_id_param=None)[source]

Guard factory that checks if the current user has ANY of the specified roles.

Parameters:
  • role_names (str) – Role names (user must have at least one).

  • resource_type_param (str | None) – Path param for resource type.

  • resource_id_param (str | None) – Path param for resource ID.

Return type:

Any

Note

Consumers must populate connection.scope["db_session"] with a per-request AsyncSession (e.g. via middleware or a dependency that writes to scope).

Config

class litestar_permissions.config.PermissionsConfig[source]

Configuration for the permissions plugin.

table_prefix: str = ''
class_prefix: str = ''
cache_ttl: int = 300
cache_max_size: int = 10000
hierarchy: dict[str, str]
resource_resolver: Callable[[...], Any] | None = None
user_key: str = 'user'
superuser_bypass: bool = True
__init__(table_prefix='', class_prefix='', cache_ttl=300, cache_max_size=10000, hierarchy=<factory>, resource_resolver=None, user_key='user', superuser_bypass=True)
Parameters:
Return type:

None

Plugin

class litestar_permissions.plugin.PermissionsPlugin[source]

Litestar plugin for fine-grained hierarchical RBAC.

Note

Consumers must populate scope["db_session"] with a per-request AsyncSession for guards and middleware to function. This is typically done via middleware or a dependency that writes to the ASGI scope.

Example:

from litestar_permissions import PermissionsPlugin, PermissionsConfig

config = PermissionsConfig(
    hierarchy={"application": "project", "project": "organization"},
)

app = Litestar(
    plugins=[PermissionsPlugin(config=config, base=Base)],
)
__init__(config=None, base=None, models=None)[source]
Parameters:
Return type:

None

on_app_init(app_config)[source]

Receive the AppConfig instance after on_app_init hooks have been called.

Examples

from litestar import Litestar, get
from litestar.di import Provide
from litestar.plugins import InitPluginProtocol


def get_name() -> str:
    return "world"


@get("/my-path")
def my_route_handler(name: str) -> dict[str, str]:
    return {"hello": name}


class MyPlugin(InitPluginProtocol):
    def on_app_init(self, app_config: AppConfig) -> AppConfig:
        app_config.dependencies["name"] = Provide(get_name)
        app_config.route_handlers.append(my_route_handler)
        return app_config


app = Litestar(plugins=[MyPlugin()])
Parameters:

app_config (AppConfig) – The AppConfig instance.

Return type:

AppConfig

Returns:

The app config object.

Resolver

class litestar_permissions.resolver.PermissionResolver[source]

Resolves whether a user has a specific permission, optionally scoped to a resource.

Supports hierarchical inheritance: if a user has org-admin on org X, they inherit all permissions on projects and applications within org X.

__init__(config, models)[source]
Parameters:
Return type:

None

async can(user_id, permission, resource_type=None, resource_id=None, *, db)[source]

Check if user has the given permission, optionally scoped to a resource.

Return type:

bool

Parameters:
async get_user_permissions(user_id, resource_type=None, resource_id=None, *, db)[source]

Get all permission codenames a user has at the given scope (+ ancestors).

Return type:

set[str]

Parameters:
invalidate_user(user_id)[source]

Remove all cached entries for a user.

Return type:

None

Parameters:

user_id (UUID | str)

invalidate_all()[source]

Clear the entire cache.

Return type:

None

Guards

litestar_permissions.guards.require_permission(*permissions, resource_type_param=None, resource_id_param=None)[source]

Guard factory that checks if the current user has ALL of the specified permissions.

Parameters:
  • permissions (str) – Permission codenames the user must have (e.g. “application:deploy”).

  • resource_type_param (str | None) – Path/query param name that holds the resource type. If None, uses resource_id_param with a fixed resource_type from the guard config.

  • resource_id_param (str | None) – Path/query param name that holds the resource ID.

Return type:

Any

Usage:

@get(“/apps/{app_id}/deploy”, guards=[require_permission(“application:deploy”, resource_id_param=”app_id”)])

Note

Consumers must populate connection.scope["db_session"] with a per-request AsyncSession (e.g. via middleware or a dependency that writes to scope).

litestar_permissions.guards.require_role(*role_names, resource_type_param=None, resource_id_param=None)[source]

Guard factory that checks if the current user has ANY of the specified roles.

Parameters:
  • role_names (str) – Role names (user must have at least one).

  • resource_type_param (str | None) – Path param for resource type.

  • resource_id_param (str | None) – Path param for resource ID.

Return type:

Any

Note

Consumers must populate connection.scope["db_session"] with a per-request AsyncSession (e.g. via middleware or a dependency that writes to scope).

Middleware

class litestar_permissions.middleware.PermissionsMiddleware[source]

Injects the user’s resolved permissions into request scope for template use.

Note

Consumers must populate scope["db_session"] with a per-request AsyncSession before this middleware runs (e.g. via an earlier middleware).

scopes: ClassVar[set[str]] = {'http'}

Protocols

class litestar_permissions.protocols.UserProtocol[source]

Interface that user models must satisfy for permission resolution.

property id: UUID | str | int
property is_superuser: bool
__init__(*args, **kwargs)
class litestar_permissions.protocols.ResourceProtocol[source]

Interface for resources that permissions can be scoped to.

property id: UUID | str | int
property resource_type: str

e.g. ‘organization’, ‘project’, ‘application’

property parent: ResourceProtocol | None

Parent resource for hierarchy traversal. None = top-level.

__init__(*args, **kwargs)

Models

class litestar_permissions.models.Role[source]

Named role that groups permissions. Use create_models() to get concrete ORM classes.

class litestar_permissions.models.Permission[source]

A granular action like ‘application:deploy’. Use create_models() to get concrete ORM classes.

class litestar_permissions.models.RolePermission[source]

Many-to-many: which permissions belong to which role. Use create_models() to get concrete ORM classes.

class litestar_permissions.models.UserRoleAssignment[source]

Assigns a role to a user, optionally scoped to a resource. Use create_models() to get concrete ORM classes.

litestar_permissions.models.create_models(base, table_prefix='', class_prefix='')[source]

Factory that creates concrete RBAC models bound to the app’s Base.

Parameters:
  • base (type[DeclarativeBase]) – The SQLAlchemy declarative base to bind models to.

  • table_prefix (str) – Prefix for database table names.

  • class_prefix (str) – Cosmetic prefix for ORM class __name__ attributes, affecting repr() and logging output. For actual registry conflict avoidance, remove the conflicting model or use PermissionsPlugin(models=...) to inject pre-created models.

Return type:

dict[str, type]

Returns dict with keys: ‘Role’, ‘Permission’, ‘RolePermission’, ‘UserRoleAssignment’