0
0
Flaskframework~5 mins

Admin panel protection in Flask

Choose your learning style9 modes available
Introduction

Protecting the admin panel keeps important settings safe from unauthorized users. It stops strangers from changing things they shouldn't.

When you have a special area for site managers or admins.
When you want to keep user data or settings private.
When you want to require a login before showing admin pages.
When you want to prevent hackers from accessing sensitive controls.
Syntax
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.

Examples
This checks if the user is logged in. If not, it sends them to the login page.
Flask
if not session.get('logged_in'):
    return redirect(url_for('login'))
This marks the user as logged in after they enter correct credentials.
Flask
session['logged_in'] = True
This logs the user out by removing the login mark and sends them back to login.
Flask
@app.route('/logout')
def logout():
    session.pop('logged_in', None)
    return redirect(url_for('login'))
Sample Program

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.

Flask
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)
OutputSuccess
Important Notes

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.

Summary

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.