def optional_login_api(func):
"""
This decorator is similar in behavior to require_login_api, but is intended for use with endpoints that offer
extended functionality with a login, but can still be used without any authentication.
The decorator will set current_user if authentication via an API key is provided, and will continue without error
otherwise.
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 func(*args, **kwargs)
return decorator
评论列表
文章目录