0
0
Flaskframework~5 mins

Role-based access control in Flask

Choose your learning style9 modes available
Introduction

Role-based access control helps decide who can do what in a web app. It keeps things safe by letting only the right people use certain parts.

You want only admins to change settings on your website.
You want users to see their own data but not others'.
You want to hide some pages from visitors who are not logged in.
You want to give different permissions to different user groups.
You want to protect sensitive actions like deleting or editing content.
Syntax
Flask
from flask import Flask, redirect, url_for, request
from functools import wraps

app = Flask(__name__)

# Example user data with roles
users = {
    'alice': 'admin',
    'bob': 'editor',
    'carol': 'viewer'
}

# Decorator to check user role
def role_required(role):
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            username = request.args.get('user')
            if not username or users.get(username) != role:
                return "Access denied", 403
            return f(*args, **kwargs)
        return decorated_function
    return decorator

@app.route('/admin')
@role_required('admin')
def admin_panel():
    return "Welcome to the admin panel!"

if __name__ == '__main__':
    app.run()

The role_required function is a decorator that checks if the user has the right role.

We get the username from the URL query for simplicity, but real apps use login sessions.

Examples
This protects the admin_page so only users with the 'admin' role can see it.
Flask
@role_required('admin')
def admin_page():
    return "Admin only content"
This allows only editors to access the edit_page.
Flask
@role_required('editor')
def edit_page():
    return "Editor content"
This restricts the page to viewers only.
Flask
@role_required('viewer')
def view_page():
    return "Viewer content"
Sample Program

This Flask app has three pages: admin, edit, and view. Each page is protected by a role check. The user role is checked from the URL query parameter ?user=alice. Only users with the matching role can access the page.

Flask
from flask import Flask, request
from functools import wraps

app = Flask(__name__)

users = {
    'alice': 'admin',
    'bob': 'editor',
    'carol': 'viewer'
}

def role_required(role):
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            username = request.args.get('user')
            if not username:
                return "No user provided", 400
            user_role = users.get(username)
            if user_role != role:
                return "Access denied", 403
            return f(*args, **kwargs)
        return decorated_function
    return decorator

@app.route('/admin')
@role_required('admin')
def admin_panel():
    return "Welcome to the admin panel!"

@app.route('/edit')
@role_required('editor')
def edit_panel():
    return "Welcome to the editor panel!"

@app.route('/view')
@role_required('viewer')
def view_panel():
    return "Welcome to the viewer panel!"

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

In real apps, user roles come from logged-in user sessions, not URL parameters.

Use HTTPS to keep user info safe when sending requests.

Role checks can be combined to allow multiple roles if needed.

Summary

Role-based access control limits what users can do based on their role.

Use decorators in Flask to protect routes easily.

Always check user identity securely before allowing access.