Opened 10 months ago
Closed 10 months ago
#36084 closed New feature (wontfix)
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: | Mariusz Felisiak | 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 (1)
comment:1 by , 10 months ago
| Cc: | added; removed |
|---|---|
| Resolution: | → wontfix |
| Status: | new → closed |
Thanks for this ticket, however, the current thread is to keep Django a core framework, not providing every utility which might be useful. You can handle "roles" as permissions assigned to users. As far as I'm aware there is no need for a separate mechanism.
If you don't agree, please first start a discussion on the DevelopersMailingList, where you'll reach a wider audience and see what other think, and follow the guidelines with regards to requesting features.