43 lines
1.2 KiB
Python
43 lines
1.2 KiB
Python
|
|
"""`@require_perm` Flask decorator (group-based RBAC)."""
|
||
|
|
|
||
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
from collections.abc import Callable
|
||
|
|
from functools import wraps
|
||
|
|
from typing import TYPE_CHECKING, ParamSpec, TypeVar
|
||
|
|
|
||
|
|
from flask import abort
|
||
|
|
from flask_login import current_user
|
||
|
|
|
||
|
|
from mimic.rbac.matrix import Permission
|
||
|
|
|
||
|
|
if TYPE_CHECKING:
|
||
|
|
pass
|
||
|
|
|
||
|
|
P = ParamSpec("P")
|
||
|
|
R = TypeVar("R")
|
||
|
|
|
||
|
|
|
||
|
|
def require_perm(perm: Permission) -> Callable[[Callable[P, R]], Callable[P, R]]:
|
||
|
|
"""Reject the request with 401/403 unless the user holds `perm`."""
|
||
|
|
|
||
|
|
def _decorate(view: Callable[P, R]) -> Callable[P, R]:
|
||
|
|
@wraps(view)
|
||
|
|
def _wrapped(*args: P.args, **kwargs: P.kwargs) -> R:
|
||
|
|
user = current_user
|
||
|
|
if not getattr(user, "is_authenticated", False):
|
||
|
|
abort(401)
|
||
|
|
permissions: frozenset[Permission] = getattr(user, "permissions", frozenset())
|
||
|
|
if perm not in permissions:
|
||
|
|
abort(403)
|
||
|
|
return view(*args, **kwargs)
|
||
|
|
|
||
|
|
return _wrapped # type: ignore[return-value]
|
||
|
|
|
||
|
|
return _decorate
|
||
|
|
|
||
|
|
|
||
|
|
def user_has(perm: Permission, permissions: frozenset[Permission]) -> bool:
|
||
|
|
"""Pure helper, easier to unit-test than the decorator."""
|
||
|
|
return perm in permissions
|