Build reusable bot framework
This commit is contained in:
50
api/security.py
Normal file
50
api/security.py
Normal file
@@ -0,0 +1,50 @@
|
||||
"""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
|
||||
Reference in New Issue
Block a user