0
0
Flaskframework~5 mins

Permission checking in routes in Flask

Choose your learning style9 modes available
Introduction

Permission checking helps control who can see or do things in your web app. It keeps your app safe and organized.

When you want only logged-in users to access certain pages.
When some users should see admin features but others should not.
When you want to stop users from changing data they shouldn't.
When you want to show different content based on user roles.
When you want to protect sensitive information from unauthorized access.
Syntax
Flask
from flask import Flask, request, abort

app = Flask(__name__)

@app.route('/secret')
def secret():
    if not user_has_permission():
        abort(403)  # Forbidden
    return 'Secret data here'

Use abort(403) to stop users without permission.

Check permissions early in the route function to avoid running unwanted code.

Examples
This example blocks users who are not admins from seeing the admin panel.
Flask
from flask import Flask, abort

app = Flask(__name__)

@app.route('/admin')
def admin_panel():
    if not is_admin():
        abort(403)
    return 'Welcome to admin panel'
This checks if the user can edit a specific item before allowing access.
Flask
from flask import Flask, abort, request

app = Flask(__name__)

@app.route('/edit/<item_id>')
def edit_item(item_id):
    if not can_edit(item_id):
        abort(403)
    return f'Editing item {item_id}'
This example only lets users with role 'user' see the profile page.
Flask
from flask import Flask, abort

app = Flask(__name__)

@app.route('/profile')
def profile():
    user_role = get_user_role()
    if user_role != 'user':
        abort(403)
    return 'User profile page'
Sample Program

This Flask app has a route '/dashboard' that only lets users with the admin role access it. It checks the username from the URL query and blocks others with a 403 error.

Flask
from flask import Flask, abort, request

app = Flask(__name__)

# Dummy user data
users = {
    'alice': {'role': 'admin'},
    'bob': {'role': 'user'}
}

def get_current_user():
    # Simulate getting username from request args
    username = request.args.get('username')
    return users.get(username)

def is_admin():
    user = get_current_user()
    return user and user.get('role') == 'admin'

@app.route('/dashboard')
def dashboard():
    if not is_admin():
        abort(403)  # Forbidden
    return 'Welcome to the admin dashboard!'

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Always return a proper HTTP status code like 403 for forbidden access.

Use helper functions to keep permission checks clean and reusable.

Test routes with different users to make sure permissions work correctly.

Summary

Permission checking controls who can access routes in Flask.

Use abort(403) to block unauthorized users.

Check permissions early and keep checks in helper functions.