📖 Scenario: You are building a simple web app with Flask. It has an admin panel that only logged-in users with admin rights can access.This project will guide you to protect the admin panel route so only authorized users can see it.
🎯 Goal: Create a Flask app with a protected admin panel route. Only users with is_admin = True can access /admin. Others get redirected to the login page.
📋 What You'll Learn
Create a Flask app with a user dictionary containing username and admin status
Add a variable to simulate the current logged-in user
Write a route for /admin that checks if the user is admin
Redirect non-admin users to /login route
💡 Why This Matters
🌍 Real World
Web apps often have admin panels that only certain users can access. Protecting these routes is essential for security.
💼 Career
Understanding route protection and user authorization is a key skill for backend web developers working with Flask or similar frameworks.
Progress0 / 4 steps
1
Create user data
Create a dictionary called users with these exact entries: 'alice': {'is_admin': True}, 'bob': {'is_admin': False}, 'carol': {'is_admin': False}.
Flask
Hint
Use a dictionary with usernames as keys and another dictionary with is_admin boolean as value.
2
Simulate logged-in user
Add a variable called current_user and set it to the string 'bob' to simulate the logged-in user.
Flask
Hint
Just create a variable current_user and assign the string 'bob'.
3
Create admin route with protection
Import Flask, redirect, and url_for. Create a Flask app called app. Write a route for /admin that checks if users[current_user]['is_admin'] is True. If yes, return the string 'Welcome to admin panel'. Otherwise, redirect to url_for('login').
Flask
Hint
Use @app.route('/admin') decorator and check admin status inside the function.
4
Add login route
Add a route for /login that returns the string 'Please log in'.
Flask
Hint
Use @app.route('/login') and return the login message string.
Practice
(1/5)
1. What is the main purpose of protecting an admin panel in a Flask app?
easy
A. To restrict access only to authorized users
B. To make the page load faster
C. To change the page style dynamically
D. To allow everyone to view admin data
Solution
Step 1: Understand admin panel purpose
The admin panel contains sensitive controls and data that should not be public.
Step 2: Identify protection goal
Protecting means only authorized users can access it, preventing unauthorized access.
Final Answer:
To restrict access only to authorized users -> Option A
Quick Check:
Admin panel protection = restrict access [OK]
Hint: Admin panel must be private, not public [OK]
Common Mistakes:
Thinking protection speeds up the page
Confusing style changes with security
Allowing all users access
2. Which Flask feature is commonly used to remember if a user is logged in for admin access?
easy
A. Flask sessions
B. Flask blueprints
C. Flask templates
D. Flask static files
Solution
Step 1: Recall Flask features
Sessions store data across requests, like login status.
Step 2: Match feature to login tracking
Sessions keep track of user login state, enabling admin protection.
Final Answer:
Flask sessions -> Option A
Quick Check:
Login status stored in sessions [OK]
Hint: Use sessions to track login state [OK]
Common Mistakes:
Confusing blueprints with login storage
Thinking templates store login info
Using static files for user data
3. What will happen if this Flask route code runs and the user is not logged in?
from flask import session, redirect, url_for
@app.route('/admin')
def admin_panel():
if not session.get('logged_in'):
return redirect(url_for('login'))
return 'Welcome to admin panel'
medium
A. User sees 'Welcome to admin panel'
B. App crashes with an error
C. User is redirected to the login page
D. User sees a blank page
Solution
Step 1: Check login condition
The code checks if 'logged_in' is not in session or False.
Step 2: Follow redirect logic
If not logged in, it redirects user to the 'login' route.
Final Answer:
User is redirected to the login page -> Option C
Quick Check:
Not logged in triggers redirect [OK]
Hint: If not logged_in, redirect to login [OK]
Common Mistakes:
Assuming user sees admin content without login
Expecting an error instead of redirect
Thinking blank page appears
4. Identify the error in this Flask admin route code:
from flask import session, redirect, url_for
@app.route('/admin')
def admin_panel():
if session['logged_in'] == False:
return redirect(url_for('login'))
return 'Admin content'
medium
A. Using url_for incorrectly
B. Using session['logged_in'] without checking if key exists
C. Missing return statement after redirect
D. Redirecting to login instead of admin
Solution
Step 1: Check session key access
Accessing session['logged_in'] directly causes error if key missing.
Step 2: Explain safe access method
Use session.get('logged_in') to avoid KeyError if key absent.
Final Answer:
Using session['logged_in'] without checking if key exists -> Option B
Quick Check:
Direct session key access risks KeyError [OK]
Hint: Use session.get() to avoid missing key errors [OK]
Common Mistakes:
Ignoring KeyError risk on missing session key
Thinking redirect needs extra return
Misusing url_for function
5. You want to protect your Flask admin panel so only logged-in users can access it. Which code snippet correctly implements this protection?
hard
A. return 'Admin panel content' # No login check needed
B. if session.get('logged_in'):
return redirect(url_for('login'))
return 'Admin panel content'
C. if session['logged_in'] == False:
return 'Admin panel content'
else:
return redirect(url_for('login'))
D. if not session.get('logged_in'):
return redirect(url_for('login'))
return 'Admin panel content'
Solution
Step 1: Check login condition correctly
We want to redirect if user is NOT logged in, so use if not session.get('logged_in').
Step 2: Return admin content only if logged in
After redirecting unauthorized users, show admin content to logged-in users.
Final Answer:
if not session.get('logged_in'):
return redirect(url_for('login'))
return 'Admin panel content' -> Option D
Quick Check:
Redirect unauthorized, show admin if logged in [OK]
Hint: Redirect if NOT logged in, else show admin [OK]
Common Mistakes:
Redirecting logged-in users instead of unauthorized
Using direct session key access without get()
Skipping login check entirely
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.