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
JavaScript
x
10
10
1
def admin_required(f):
2
wraps(f)
3
@jwt_required()
4
def decorated_function(*args, **kwargs):
5
current_user = get_jwt_identity()
6
if current_user != "test1":
7
return jsonify(admin=False), 200
8
return f(*args, **kwargs)
9
return decorated_function()
10
And this is endpoint
JavaScript
1
6
1
@app.route("/am_i_admin", methods= ["GET"])
2
@jwt_required()
3
@admin_required
4
def am_i_admin():
5
return jsonify(admin=True), 200
6
I am getting this error
JavaScript
1
17
17
1
Traceback (most recent call last):
2
File "/Users/jozkomrkvicka/PycharmProjects/API/my_api/my_api.py", line 166, in <module>
3
def am_i_admin():
4
File "/Users/jozkomrkvicka/PycharmProjects/API/my_api/my_api.py", line 92, in admin_required
5
return decorated_function()
6
File "/Users/jozkomrkvicka/PycharmProjects/API/my_api/my_api.py", line 88, in decorated_function
7
current_user = get_jwt_identity()
8
File "/Users/jozkomrkvicka/PycharmProjects/API/venv/lib/python3.9/site-packages/flask_jwt_extended/utils.py", line 62, in get_jwt_identity
9
return get_jwt().get(config.identity_claim_key, None)
10
File "/Users/jozkomrkvicka/PycharmProjects/API/venv/lib/python3.9/site-packages/flask_jwt_extended/utils.py", line 26, in get_jwt
11
decoded_jwt = g.get("_jwt_extended_jwt", None)
12
File "/Users/jozkomrkvicka/PycharmProjects/API/venv/lib/python3.9/site-packages/werkzeug/local.py", line 316, in __get__
13
obj = instance._get_current_object() # type: ignore[misc]
14
File "/Users/jozkomrkvicka/PycharmProjects/API/venv/lib/python3.9/site-packages/werkzeug/local.py", line 513, in _get_current_object
15
raise RuntimeError(unbound_message) from None
16
RuntimeError: Working outside of application context.
17
I don’t know where is the problem, I did this according this documentation. Could someone help me how to solve this issue?
Advertisement
Answer
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).
JavaScript
1
9
1
def requires_auth(f):
2
@wraps(f)
3
def decorated(*args, **kwargs):
4
auth = request.authorization
5
if not auth or not check_auth(auth.username, auth.password):
6
return authenticate()
7
return f(*args, **kwargs)
8
return decorated
9