Template-level authorization helps control what parts of a web page a user can see based on their permissions. It keeps your app safe by hiding or showing content depending on who is logged in.
0
0
Template-level authorization in Flask
Introduction
You want to show a special admin menu only to admin users.
You want to hide edit buttons from users who cannot change content.
You want to display different messages based on user roles.
You want to prevent unauthorized users from seeing sensitive data on a page.
Syntax
Flask
{% if condition %}
<!-- content to show if condition is true -->
{% else %}
<!-- content to show if condition is false -->
{% endif %}Use Flask's
current_user or your own user object to check permissions inside templates.Conditions can check roles, permissions, or any user attribute.
Examples
Shows a welcome message if the user is logged in, otherwise asks to log in.
Flask
{% if current_user.is_authenticated %}
<p>Welcome, {{ current_user.username }}!</p>
{% else %}
<p>Please log in.</p>
{% endif %}Shows an admin dashboard link only if the user has the 'admin' role.
Flask
{% if 'admin' in current_user.roles %}
<a href="/admin">Admin Dashboard</a>
{% endif %}Shows an edit button only if the user has permission to edit.
Flask
{% if current_user.can_edit %}
<button>Edit Post</button>
{% else %}
<p>You cannot edit this post.</p>
{% endif %}Sample Program
This Flask app shows how to use template-level authorization. It displays a welcome message and an admin dashboard link only if the user is logged in and has the admin role.
Flask
from flask import Flask, render_template_string from flask_login import LoginManager, UserMixin, login_user, current_user app = Flask(__name__) app.secret_key = 'secret' login_manager = LoginManager(app) class User(UserMixin): def __init__(self, id, username, roles): self.id = id self.username = username self.roles = roles @login_manager.user_loader def load_user(user_id): # For demo, return a user with admin role return User(user_id, 'Alice', ['admin']) @app.route('/') def home(): template = ''' {% if current_user.is_authenticated %} <p>Welcome, {{ current_user.username }}!</p> {% if 'admin' in current_user.roles %} <a href="/admin">Admin Dashboard</a> {% else %} <p>Standard user dashboard</p> {% endif %} {% else %} <p>Please log in.</p> {% endif %} ''' return render_template_string(template) with app.test_request_context(): user = User('1', 'Alice', ['admin']) login_user(user) print(home())
OutputSuccess
Important Notes
Always check user permissions in both backend and templates for security.
Use Flask-Login's current_user to access user info in templates.
Keep template logic simple to avoid clutter and confusion.
Summary
Template-level authorization controls what users see based on their roles or permissions.
Use {% if %} blocks in templates to show or hide content.
Combine backend checks with template checks for better security.