decorators.py 文件源码

python
阅读 27 收藏 0 点赞 0 评论 0

项目:modern-paste 作者: LINKIWI 项目源码 文件源码
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
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号