#20921: Creating a decorator any_permission_required
-------------------------------------+-------------------------------------
Reporter: fabiobatalha@… | Owner:
Type: New feature | fabiobatalha
Component: contrib.auth | Status: new
Severity: Normal | Version: 1.5
Keywords: auth perms | Resolution:
required_permission has_perms | Triage Stage:
Has patch: 0 | Unreviewed
Needs tests: 0 | Needs documentation: 0
Easy pickings: 0 | Patch needs improvement: 0
| UI/UX: 0
-------------------------------------+-------------------------------------
Changes (by fabiobatalha@…):
* needs_better_patch: => 0
* needs_tests: => 0
* needs_docs: => 0
Comment:
Suggested solution:
**Add this method at django.auth.contrib.models.User**
def has_any_perms(self, perm_list, obj=None):
"""
Returns True if the user has any of the specified permissions. If
object is passed, it checks if the user has at least one of the
required
perms for thisobject.
"""
for perm in perm_list:
if self.has_perm(perm, obj):
return True
return False
**Add this method at django.contrib.auth.decorators**
def any_permission_required(perm, login_url=None, raise_exception=False):
"""
Decorator for views that checks whether a user has any particular
permission
enabled, redirecting to the log-in page if neccesary.
If the raise_exception parameter is given the PermissionDenied
exception
is raised.
"""
def check_perms(user):
if not isinstance(perm, (list, tuple)):
perms = (perm, )
else:
perms = perm
# First check if the user has the permission (even anon users)
if user.has_any_perms(perms):
return True
# In case the 403 handler should be called raise the exception
if raise_exception:
raise PermissionDenied
# As the last resort, show the login form
return False
return user_passes_test(check_perms, login_url=login_url)
--
Ticket URL: <https://code.djangoproject.com/ticket/20921#comment:1>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-updates/080.a74a2b4413e10d6d65a501fbccc0d8d6%40djangoproject.com.
For more options, visit https://groups.google.com/groups/opt_out.