Created
February 25, 2020 12:01
-
-
Save namieluss/738db7e76bb07e0428172992edc9ac7a to your computer and use it in GitHub Desktop.
A python flask decorator to check user access level before entry to page.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask, g, abort | |
app = Flask(__name__) | |
# This decorator checks the role of the user before allowing entry | |
def check_role(access_level, json=False): | |
def decorator(func): | |
@wraps(func) | |
def wrapper(*args, **kwargs): | |
if not g.user.role == access_level: | |
if json: | |
return jsonify({"message": "not authorized"}), 403 | |
return abort(403) | |
return func(*args, **kwargs) | |
return wrapper | |
return decorator | |
# Everyone can access this page, no permissions required | |
@app.route("/") | |
def home_page(): | |
return render_template("homepage.html", user=user) | |
# Only admin can access this page. | |
# If staff try to access, they get pushed out, redirect to 403 | |
@app.route("/admin") | |
@check_role(access_level="admin") | |
def admin_page(): | |
user = g.user | |
return render_template("admin/dashboard.html", user=user) | |
# Only staff can access this page. | |
# If admin try to access, they get pushed out, redirect to 403 | |
@app.route("/profile") | |
@check_role(access_level="staff") | |
def staff_page(): | |
user = g.user | |
return render_template("admin/dashboard.html", user=user) | |
# Only staff can send post request to this endpoint. | |
@app.route("/profile/update", methods=["POST"]) | |
@check_role("staff", json=True) | |
def staff_profile_update(): | |
# ... | |
# do some update tasks... | |
# ... | |
return jsonify({"message": "profile update successful"}), 200 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment