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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Stacking decorators lets you compose authentication and authorization as independent, reusable layers.
- 2Wrapping with functools.wraps preserves the view's identity so Flask's routing and introspection keep working.
- 3Returning early with abort centralizes access denials instead of scattering checks through each view.
Related explainers
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
python
import secrets from django.contrib.auth import authenticate, login from django.core.cache import cache
Two-factor login with OTP in Django
two-factor-auth
one-time-passwords
caching
Intermediate
9 steps
go
package middleware import ( "net/http"
Per-plan export limits in Gin middleware
middleware
rate-limiting
authorization
Intermediate
7 steps
python
import re from functools import total_ordering from typing import Optional
Parsing and comparing semantic versions
regex
operator-overloading
sorting
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-an-admin-only-decorator-in-flask-explained-python-d707/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.