foxnouns/foxnouns/decorators.py
2024-04-10 21:37:38 +02:00

45 lines
1.3 KiB
Python

from functools import wraps
from typing import Any
from quart import g
from foxnouns.exceptions import ErrorCode, ForbiddenError, UnsupportedEndpointError
def require_auth(*, scope: str | None = None):
"""Decorator that requires a token with the given scopes.
If no token is given or the required scopes aren't set on it, execution is aborted."""
def decorator(func):
@wraps(func)
async def wrapper(*args, **kwargs):
if "user" not in g or "token" not in g:
raise ForbiddenError("Not authenticated", type=ErrorCode.Forbidden)
if scope and not g.token.has_scope(scope):
raise ForbiddenError(
f"Missing scope '{scope}'", type=ErrorCode.MissingScope
)
return await func(*args, **kwargs)
return wrapper
return decorator
def require_config_key(*, keys: list[Any]):
"""Decorator that requires one or more config keys to be set.
If any of them are None, execution is aborted."""
def decorator(func):
@wraps(func)
async def wrapper(*args, **kwargs):
for key in keys:
if not key:
raise UnsupportedEndpointError()
return await func(*args, **kwargs)
return wrapper
return decorator