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 django.urls import path, include app_name = "api"
How URL-namespaced API versioning works in Django
api versioning
url routing
namespaces
Intermediate
8 steps
python
import asyncio from dataclasses import dataclass import aiohttp
Bounded-concurrency HTTP fetching with asyncio
async
concurrency
semaphore
Intermediate
8 steps
python
from pathlib import Path from typing import Iterator
Filtering files with pathlib.glob
generators
filesystem
filtering
Intermediate
6 steps
python
import heapq from collections import Counter from typing import Iterable, Hashable
Finding the top-N items in a stream
heaps
counting
generators
Intermediate
5 steps
php
<?php namespace App\Providers;
Defining authorization gates in Laravel
authorization
gates
service-provider
Intermediate
6 steps
python
from flask import Blueprint, jsonify from sqlalchemy import text from sqlalchemy.exc import SQLAlchemyError
Building a health check endpoint in Flask
health-check
blueprint
error-handling
Intermediate
6 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.