Search code examples
pythoneve

Python eve - how to get the current user after successful authentication?


I created an auth token class like the below, and I use self.set_request_auth_value(user['_id']) to set the user of this request, in some hooks I want to access this user, how can I get it ?

I tried app.get_request_auth_value(), but that is not it.

Token Auth class:

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

Solution

  • The actual auth_value is stored in Flask's g object (docs), as auth_value. So in your callback you could probably do something like:

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

    Or, to stay within Eve semantics, you could use current_app:

    from flask import current_app
    
    current_app.auth.get_request_auth_value()