Opened 3 hours ago

#36084 new New feature

Add a `role_required` decorator to Django's authentication system for role-based access control.

Reported by: H_coder Owned by:
Component: contrib.auth Version: 5.1
Severity: Normal Keywords: auth, decorator, feature
Cc: H_coder Triage Stage: Unreviewed
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

role_required decorator:

Currently, Django provides decorators like @login_required and @permission_required to restrict view access. However, there is no built-in support for role-based access control, which is a common requirement for many applications.

This ticket proposes adding a new role_required decorator that allows developers to restrict access to views based on user roles. The decorator will:

  • Check if the user has one or more specified roles.
  • Support both "any role" (test_all=False) and "all roles" (test_all=True) modes.
  • Redirect unauthorized users to the login page or a custom URL.

This feature will make it easier for developers to implement role-based access control without writing custom decorators.

Example Use Case

A marketplace application might have roles like is_seller, is_buyer, and is_admin. The role_required decorator can be used to restrict access to specific views:

from django.contrib.auth.decorators import role_required

@role_required(['is_seller'])
def seller_dashboard(request):
    # Only users with the 'is_seller' role can access this view.
    pass

@role_required(['is_admin', 'is_moderator'], test_all=True)
def admin_dashboard(request):
    # Only users with both 'is_admin' and 'is_moderator' roles can access this view.
    pass

Change History (0)

Note: See TracTickets for help on using tickets.
Back to Top