Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am using two decorators to decorate a function "add_user", the first one @auth_user authenticates the logged in user via json web token request headers and returns the user's information as an argument "user_info" back to the decorated function add_user. The second decorator @has_permission is supposed to check whether or not the user has permissions on the requested resource. I wanted to pass the user's information returned as user_info by @auth_user to @has_permission but don't know how to do that, here is the code so far:

What I have tried:

Python
@has_permission
@auth_user
def add_user(user_info):
    """
    do something
    """
    return None


The decorators:

Python
def auth_user(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        data = jwt.decode(request.headers['some-access-token'], some_secret_key)
        try:
            user_info = User.query.filter(User.id==data['user_id']).first()
        except:
            return jsonify({"message" : "error"}), 401

        return f(user_info, *args, **kwargs)

    return wrapper


and:

Python
def has_permission(f):
    wraps(f)
    def wrapper(*args, **kwargs):
        # This is where I want to access the user information instead of processing the key again #
        # return some new_args ... #
        return f(*args, **kwargs)
    return wrapper


What is the best way to achieve this?

Thanks.
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900