51 lines
1.4 KiB
Python
51 lines
1.4 KiB
Python
"""Authentication decorators shared by API route modules."""
|
|
|
|
from functools import wraps
|
|
|
|
import flask
|
|
|
|
from core import auth
|
|
|
|
|
|
def requireUser(requireLogin=False):
|
|
def decorator(route):
|
|
@wraps(route)
|
|
def wrapped(*args, **kwargs):
|
|
principal = auth.authenticateBearerToken(
|
|
flask.request.headers.get("Authorization"),
|
|
allowService=False,
|
|
)
|
|
if not auth.isUserPrincipal(principal, requireLogin=requireLogin):
|
|
return flask.jsonify({"error": "unauthorized"}), 401
|
|
flask.g.principal = principal
|
|
flask.g.user_uuid = principal["user_uuid"]
|
|
return route(*args, **kwargs)
|
|
|
|
return wrapped
|
|
|
|
return decorator
|
|
|
|
|
|
def requireService(scope):
|
|
def decorator(route):
|
|
@wraps(route)
|
|
def wrapped(*args, **kwargs):
|
|
principal = auth.authenticateBearerToken(
|
|
flask.request.headers.get("Authorization"),
|
|
requiredScopes=[scope],
|
|
allowUser=False,
|
|
)
|
|
if not auth.hasServiceScope(principal, scope):
|
|
return flask.jsonify({"error": "unauthorized"}), 401
|
|
flask.g.principal = principal
|
|
return route(*args, **kwargs)
|
|
|
|
return wrapped
|
|
|
|
return decorator
|
|
|
|
|
|
def jsonObject():
|
|
data = flask.request.get_json(silent=True)
|
|
return data if isinstance(data, dict) else None
|