0
0
Flaskframework~5 mins

Decorator for role requirement in Flask

Choose your learning style9 modes available
Introduction

A decorator for role requirement helps control who can access certain parts of a web app based on their role. It keeps your code clean and secure by checking user roles before running a function.

You want only admins to access the admin dashboard.
You want to restrict editing features to editors only.
You want to show certain pages only to logged-in users with specific roles.
You want to avoid repeating role checks in every route function.
Syntax
Flask
from functools import wraps

def role_required(role):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            if current_user.role != role:
                return "Access denied", 403
            return func(*args, **kwargs)
        return wrapper
    return decorator

The outer function role_required takes the role name as input.

The inner decorator wraps the original function to add role checking.

Examples
This protects the admin_panel function so only users with role 'admin' can access it.
Flask
@role_required('admin')
def admin_panel():
    return "Welcome Admin"
This restricts the edit_article function to users with role 'editor'.
Flask
@role_required('editor')
def edit_article():
    return "Edit your article here"
Sample Program

This Flask example shows a simple role check decorator. The current_user is mocked as an admin. The admin_panel route allows access, but edit_article denies access because the user is not an editor.

Flask
from flask import Flask
from functools import wraps

app = Flask(__name__)

# Mock current_user for demo
class User:
    def __init__(self, role):
        self.role = role

current_user = User('admin')

def role_required(role):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            if current_user.role != role:
                return "Access denied", 403
            return func(*args, **kwargs)
        return wrapper
    return decorator

@app.route('/admin')
@role_required('admin')
def admin_panel():
    return "Welcome Admin"

@app.route('/edit')
@role_required('editor')
def edit_article():
    return "Edit your article here"

# Simulate calling routes
print(admin_panel())
print(edit_article())
OutputSuccess
Important Notes

Make sure current_user correctly represents the logged-in user in your real app.

You can extend the decorator to accept multiple roles or check permissions more flexibly.

Summary

Decorators can check user roles before running a function.

This keeps your code clean and secure by centralizing role checks.

Use it to protect routes or functions based on user roles.