0

我正在尝试实现一个装饰器,该装饰器在授予对函数的访问权限之前对用户的令牌进行身份验证。我当前的实现有点不稳定,因为我无法在装饰器中获取本地人,因此我需要执行两个查询。有一个更好的方法吗?

def require_auth(func):
    print 'require_auth'
    @wraps(func)
    def inner():
        if 'token' in request.json:
            token = request.json['token']
            session = Session()
            for instance in session.query(SQLTypes.User).filter(SQLTypes.User.token==token):
                auth_user = instance.username
            try:
                auth_user
                print 'authenticated!'
            except NameError:
                abort(401)
        else:
            abort(401)
        return func()
    return inner

@app.route('/st/projects', methods=['POST'])
@require_auth
def post_project():

    session = Session()

    for instance in session.query(SQLTypes.User).filter(SQLTypes.User.token==request.json['token']):
        auth_user = instance.username

    # do something with auth_user

    session.close()
4

1 回答 1

1

您可以将经过身份验证的用户存储在flask.g

from flask import g

# ...

def require_auth(func):

    # ...

    for instance in session.query(SQLTypes.User).filter(SQLTypes.User.token==token):
        g.auth_user = instance.username
    try:
        g.auth_user
        print 'authenticated!'
    except AttributeError:
        abort(401)

    # ...

然后在您的视图功能中,您可以将用户访问为g.auth_user.

于 2013-11-04T20:15:20.343 回答