python 26 lines · 7 steps

Building an admin-only decorator in Flask

A custom decorator layers role checks on top of Flask-Login to guard admin routes.

Explained by highlit
1from functools import wraps
2 
3from flask import Blueprint, abort, jsonify
4from flask_login import current_user, login_required
5 
6admin_bp = Blueprint("admin", __name__, url_prefix="/admin")
7 
8 
9def admin_required(view):
10 @wraps(view)
11 @login_required
12 def wrapped(*args, **kwargs):
13 if not current_user.is_active:
14 abort(403, description="Account is disabled.")
15 if current_user.role != "admin":
16 abort(403, description="Administrator access required.")
17 return view(*args, **kwargs)
18 
19 return wrapped
20 
21 
22@admin_bp.route("/users")
23@admin_required
24def list_users():
25 users = User.query.order_by(User.created_at.desc()).all()
26 return jsonify(users=[u.to_dict() for u in users])
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Stacking decorators lets you compose authentication and authorization as independent, reusable layers.
  2. 2Wrapping with functools.wraps preserves the view's identity so Flask's routing and introspection keep working.
  3. 3Returning early with abort centralizes access denials instead of scattering checks through each view.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building an admin-only decorator in Flask — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code