I need to introduce role-based authorization in existing Flask application. Because of that I can't just swap currently used flask-login package with flask-user for example. Nevertheless I have to restrict access to some endpoints to "admin" users without rebuilding entire code base.
I came up with a decorator like this:
def admin_required(func):
"""
Modified login_required decorator to restrict access to admin group.
"""
@wraps(func)
def decorated_view(*args, **kwargs):
if current_user.group != 0: # zero means admin, one and up are other groups
flash("You don't have permission to access this resource.", "warning")
return redirect(url_for("main.home"))
return func(*args, **kwargs)
return decorated_view
I use it with original login_required
decorator like so:
@app.route("/admin-restricted"):
@login_required
@admin_required
def admin_resource():
return "Hello admin"
Everything works as expected BUT I have two concerns:
- Is my method safe? Have I missed something which is potential security flaw? Unfortunately I have limited knowledge about Flask internals.
- Is there more simple/safe/pythonic way to do that? It just doesn't feel right to me.