nopaque/app/decorators.py

80 lines
2.5 KiB
Python
Raw Permalink Normal View History

2024-05-04 12:55:05 +00:00
from flask import abort, request
from flask_login import current_user
2020-03-27 11:06:11 +00:00
from functools import wraps
2024-09-25 15:46:53 +00:00
from typing import Optional
from werkzeug.exceptions import NotAcceptable
from app.models import Permission
2021-12-03 13:07:03 +00:00
def permission_required(permission):
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not current_user.can(permission):
abort(403)
return f(*args, **kwargs)
return decorated_function
return decorator
def admin_required(f):
2021-12-03 13:07:03 +00:00
return permission_required(Permission.ADMINISTRATE)(f)
2024-05-04 12:55:05 +00:00
def socketio_login_required(f):
@wraps(f)
2024-05-04 12:55:05 +00:00
def wrapper(*args, **kwargs):
if current_user.is_authenticated:
return f(*args, **kwargs)
return {'code': 401, 'body': 'Unauthorized'}
return wrapper
def socketio_permission_required(permission):
def decorator(f):
@wraps(f)
def wrapper(*args, **kwargs):
if not current_user.can(permission):
return {'code': 403, 'body': 'Forbidden'}
return f(*args, **kwargs)
return wrapper
return decorator
def socketio_admin_required(f):
return socketio_permission_required(Permission.ADMINISTRATE)(f)
def content_negotiation(
2024-09-25 15:46:53 +00:00
produces: Optional[str | list[str]] = None,
consumes: Optional[str | list[str]] = None
):
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
provided = request.mimetype
if consumes is None:
consumeables = None
elif isinstance(consumes, str):
consumeables = {consumes}
elif isinstance(consumes, list) and all(isinstance(x, str) for x in consumes):
consumeables = {*consumes}
else:
raise TypeError()
accepted = {*request.accept_mimetypes.values()}
if produces is None:
produceables = None
elif isinstance(produces, str):
produceables = {produces}
elif isinstance(produces, list) and all(isinstance(x, str) for x in produces):
produceables = {*produces}
else:
raise TypeError()
if produceables is not None and len(produceables & accepted) == 0:
raise NotAcceptable()
if consumeables is not None and provided not in consumeables:
raise NotAcceptable()
return f(*args, **kwargs)
return decorated_function
return decorator