def require_login_api(func):
"""
A custom implementation of Flask-login's built-in @login_required decorator.
This decorator will allow usage of the API endpoint if the user is either currently logged in via the app
or if the user authenticates with an API key in the POST JSON parameters.
This implementation overrides the behavior taken when the current user is not authenticated by
returning the predefined AUTH_FAILURE JSON response with HTTP status code 401.
This decorator is intended for use with API endpoints.
"""
@wraps(func)
def decorator(*args, **kwargs):
data = request.get_json()
if current_user.is_authenticated:
return func(*args, **kwargs)
try:
if data and data.get('api_key'):
user = database.user.get_user_by_api_key(data['api_key'], active_only=True)
login_user(user)
del data['api_key']
request.get_json = lambda: data
return func(*args, **kwargs)
except UserDoesNotExistException:
return jsonify(AUTH_FAILURE), AUTH_FAILURE_CODE
return jsonify(AUTH_FAILURE), AUTH_FAILURE_CODE
return decorator
评论列表
文章目录