Protecting the admin panel keeps important settings safe from unauthorized users. It stops strangers from changing things they shouldn't.
Admin panel protection in Flask
from flask import Flask, request, redirect, url_for, session app = Flask(__name__) app.secret_key = 'your_secret_key' @app.route('/admin') def admin_panel(): if not session.get('logged_in'): return redirect(url_for('login')) return 'Welcome to the admin panel!' @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': if request.form['username'] == 'admin' and request.form['password'] == 'password': session['logged_in'] = True return redirect(url_for('admin_panel')) else: return 'Wrong credentials!' return '''<form method="post"> Username: <input name="username"><br> Password: <input name="password" type="password"><br> <input type="submit" value="Login"> </form>'''
Use session to remember if a user is logged in.
Redirect users to login if they try to access admin without permission.
if not session.get('logged_in'): return redirect(url_for('login'))
session['logged_in'] = True
@app.route('/logout') def logout(): session.pop('logged_in', None) return redirect(url_for('login'))
This Flask app protects the admin panel by requiring a login. If you visit '/admin' without logging in, it sends you to '/login'. After entering the correct username and password, you can access the admin panel. You can also log out to protect the panel again.
from flask import Flask, request, redirect, url_for, session app = Flask(__name__) app.secret_key = 'supersecretkey' @app.route('/admin') def admin_panel(): if not session.get('logged_in'): return redirect(url_for('login')) return 'Welcome to the admin panel!' @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] if username == 'admin' and password == 'password': session['logged_in'] = True return redirect(url_for('admin_panel')) else: return 'Wrong credentials!' return '''<form method="post"> Username: <input name="username"><br> Password: <input name="password" type="password"><br> <input type="submit" value="Login"> </form>''' @app.route('/logout') def logout(): session.pop('logged_in', None) return redirect(url_for('login')) if __name__ == '__main__': app.run(debug=True)
Always use a strong secret key for sessions to keep data safe.
Never store passwords in plain text in real apps; use hashing.
Consider adding more security like HTTPS and rate limiting for real projects.
Protect admin pages by checking if a user is logged in.
Use Flask sessions to remember login status.
Redirect unauthorized users to a login page.
Practice
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 AQuick Check:
Admin panel protection = restrict access [OK]
- Thinking protection speeds up the page
- Confusing style changes with security
- Allowing all users access
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 AQuick Check:
Login status stored in sessions [OK]
- Confusing blueprints with login storage
- Thinking templates store login info
- Using static files for user data
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'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 CQuick Check:
Not logged in triggers redirect [OK]
- Assuming user sees admin content without login
- Expecting an error instead of redirect
- Thinking blank page appears
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'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 BQuick Check:
Direct session key access risks KeyError [OK]
- Ignoring KeyError risk on missing session key
- Thinking redirect needs extra return
- Misusing url_for function
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 DQuick Check:
Redirect unauthorized, show admin if logged in [OK]
- Redirecting logged-in users instead of unauthorized
- Using direct session key access without get()
- Skipping login check entirely
Ready to prove it?
Pass the test and this pattern moves unknown
