0

I am trying to put a validate wrapper around my flask endpoints to check if the user has permissions to the data. I want to define the permissions required in the decorator and then the wrapper verifies the user has those roles.

def create_app(config):
    app=Flask(__name__)
    app.config.from_object(config)

    db.init_app(app)

    JWTManager(app)
    app.config["JWT_ROLE_CLAIM"] = "roles"
    jwt.init_app(app)

    api.add_namespace(auth_ns)
    api.add_namespace(tasks_ns)

    return app

from flask_jwt_extended import get_jwt_claims

def requires_roles(*roles):
    def wrapper(f):
        @wraps(f)
        def wrapped(*args, **kwargs):
            # Get the user's roles from the JWT token
            user_roles = get_jwt_claims().get("roles")

            # Check if the user has any of the required roles
            if any(role in user_roles for role in roles):
                # Call the endpoint function and return its result
                return f(*args, **kwargs)
            else:
                # Return a 403 Forbidden response
                return "Forbidden", 403
        return wrapped
    return wrapper
@auth_ns.route('/authtest')
@requires_roles("admin", "manager")
class AuthtestResource(Resource):
    # @jwt_required()
    def get(self):
        return make_response(jsonify({"msg":"Authenticated success"}),200)

I get this error: cannot import name 'get_jwt_claims' from 'flask_jwt_extended'

I am not very familiar with decorators, what am I doing wrong here?

I have tried creating a decorator and using an AI tool to help me write the code

0 Answers0