I am creating simple API using flask, and I want to check if user which is trying to access is admin. This is function which should decide if user is admin or not
def admin_required(f):
wraps(f)
@jwt_required()
def decorated_function(*args, **kwargs):
current_user = get_jwt_identity()
if current_user != "test1":
return jsonify(admin=False), 200
return f(*args, **kwargs)
return decorated_function()
And this is endpoint
@app.route("/am_i_admin", methods= ["GET"])
@jwt_required()
@admin_required
def am_i_admin():
return jsonify(admin=True), 200
I am getting this error
Traceback (most recent call last):
File "/Users/jozkomrkvicka/PycharmProjects/API/my_api/my_api.py", line 166, in <module>
def am_i_admin():
File "/Users/jozkomrkvicka/PycharmProjects/API/my_api/my_api.py", line 92, in admin_required
return decorated_function()
File "/Users/jozkomrkvicka/PycharmProjects/API/my_api/my_api.py", line 88, in decorated_function
current_user = get_jwt_identity()
File "/Users/jozkomrkvicka/PycharmProjects/API/venv/lib/python3.9/site-packages/flask_jwt_extended/utils.py", line 62, in get_jwt_identity
return get_jwt().get(config.identity_claim_key, None)
File "/Users/jozkomrkvicka/PycharmProjects/API/venv/lib/python3.9/site-packages/flask_jwt_extended/utils.py", line 26, in get_jwt
decoded_jwt = g.get("_jwt_extended_jwt", None)
File "/Users/jozkomrkvicka/PycharmProjects/API/venv/lib/python3.9/site-packages/werkzeug/local.py", line 316, in __get__
obj = instance._get_current_object() # type: ignore[misc]
File "/Users/jozkomrkvicka/PycharmProjects/API/venv/lib/python3.9/site-packages/werkzeug/local.py", line 513, in _get_current_object
raise RuntimeError(unbound_message) from None
RuntimeError: Working outside of application context.
I don't know where is the problem, I did this according this documentation. Could someone help me how to solve this issue?
CodePudding user response:
Is the indentation in your post what is actually in your code, because it is indented wrong. Here is an example of an authentication check (not an admin check), but you can see how the indentation should look. You are also missing the decorator on wraps(f).
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated