dmc94
dmc94

Reputation: 536

How can I access a return from a decorator?

I have an auth decorator, that I am using to verify tokens for logins. I would like to return the UID from the decorator but I am unsure of how to do that? Any advice? (The idea is that we can use that UID from the token to access user-specific resources on our server)

Decorator:

def check_auth(id_token):
    decoded_token = auth.verify_id_token(id_token)
    uid = decoded_token['uid']
    print(uid)
    return uid


def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.headers.get("Authorization")
        if not auth or not check_auth(auth):
            message = {"error": "Authorization Required"}
            resp = message
            return resp
        return f(*args, **kwargs)

    return decorated

Upvotes: 0

Views: 61

Answers (1)

Klaus D.
Klaus D.

Reputation: 14369

The return value of a decorator is what will replace the decorated function. If you return a UID from the decorator your decorated function will be replaced by the UID.

What you can do is to inject the UID into the function call:

def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.headers.get("Authorization")
        if not auth or not check_auth(auth):
            message = {"error": "Authorization Required"}
            resp = message
            return resp
        kwargs['uid'] = check_auth(auth)
        return f(*args, **kwargs)

    return decorated

This requires all decorated functions to accept a uid argument:

@requires_auth
def decorated_function(uid):
    …

Upvotes: 1

Related Questions