0
0
Flaskframework~30 mins

Template-level authorization in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Template-level Authorization in Flask
📖 Scenario: You are building a simple Flask web app where users have different roles. Some parts of the page should only be visible to users with the 'admin' role.
🎯 Goal: Create a Flask app with a user dictionary, a role configuration, and a template that shows a special message only if the user is an admin.
📋 What You'll Learn
Create a dictionary called users with usernames and their roles
Create a variable called current_user set to a specific username
Use a Flask template with a conditional to show content only if current_user has the 'admin' role
Render the template in a Flask route
💡 Why This Matters
🌍 Real World
Many web apps show or hide parts of pages based on user roles, like admin panels or special buttons.
💼 Career
Understanding template-level authorization is key for building secure and user-friendly web applications.
Progress0 / 4 steps
1
Create the user roles dictionary
Create a dictionary called users with these exact entries: 'alice': 'admin', 'bob': 'user', 'carol': 'user'.
Flask
Need a hint?

Use curly braces to create the dictionary and colons to assign roles.

2
Set the current user
Create a variable called current_user and set it to the string 'alice'.
Flask
Need a hint?

Assign the string 'alice' to the variable current_user.

3
Create the Flask app and template with authorization check
Import Flask and create an app. Define a route / that renders a template called index.html. Pass current_user and users to the template. In the template, use a Jinja2 {% if %} statement to show the text Welcome, admin! only if the role of current_user in users is 'admin'.
Flask
Need a hint?

Use @app.route('/') to create the home route and render_template to send variables to the template.

4
Add the template code for conditional display
Create a file called templates/index.html. Inside, write HTML that uses Jinja2 syntax. Add a conditional {% if users[current_user] == 'admin' %} that shows <p>Welcome, admin!</p> only if the current user is an admin. Otherwise, show <p>Welcome, user!</p>.
Flask
Need a hint?

Use Jinja2 {% if %} and {% else %} tags to show different messages.