Python前夕 - 如何在成功验证后获得当前用户?

时间:2016-02-04 12:48:23

标签: python eve

我创建了一个如下所示的身份验证令牌类,我使用self.set_request_auth_value(user['_id'])来设置此请求的用户,在某些我想访问此用户的挂钩中,我该如何获取它?

我试过了app.get_request_auth_value(),但事实并非如此。

Token Auth类:

class TokenAuth(TokenAuth):
    def check_auth(self, token, allowed_roles, resource, method):
        """ Token authentication using itsdangerous """
        # TODO: revoked access can be checked here
        # without even parsing the token
        s = Serilizer(app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except SignatureExpired:
            return []
        except BadSignature:
            return []
        # Celery borker Async task test
        r = add.delay(4, 4)
        print r.id
        # use Eve's own db driver; no additional connections/resources are used
        users = app.data.driver.db['users']
        user = users.find_one({'_id': ObjectId(data.get('id'))})
        # Set the user of this request
        self.set_request_auth_value(user['_id'])
        return user

1 个答案:

答案 0 :(得分:1)

实际auth_value存储在Flask的g对象(docs)中,auth_value。所以在你的回调中你可能会做类似的事情:

import flask

user = flask.g.get('auth_value', None)
# or, alternatively:
user = getattr(flask.g, 'auth_value', None)

或者,为了保持Eve语义,你可以使用current_app

from flask import current_app

current_app.auth.get_request_auth_value()