Skip to content

Commit

Permalink
[Backport] Support for methods on User model when checking permissions
Browse files Browse the repository at this point in the history
The ``permissions_required`` decorator, and hence
``Application.permissions_map`` and
``Application.default_permissions``, now
handle both methods and properties on the User model.
Previously, it
wasn't supported, but a docstring showed
``is_anonymous`` as an example,
which is a method.

Cherry-picked from 8b610f6
  • Loading branch information
maiksprenger committed Jun 19, 2014
1 parent 333a7e8 commit a400a24
Showing 1 changed file with 10 additions and 5 deletions.
15 changes: 10 additions & 5 deletions oscar/views/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def check_permissions(user, permissions):
every permission list will be evaluated and the outcome will be checked
for truthiness.
Each item of the list(s) must be either a valid Django permission name
(model.codename) or an attribute on the User model
(model.codename) or a property or method on the User model
(e.g. 'is_active', 'is_superuser').
Example usage:
Expand All @@ -71,13 +71,18 @@ def check_permissions(user, permissions):
def _check_one_permission_list(perms):
regular_permissions = [perm for perm in perms if '.' in perm]
conditions = [perm for perm in perms if '.' not in perm]
if conditions and ['is_active', 'is_anonymous'] not in conditions:
# always check for is_active where appropriate
# always check for is_active if not checking for is_anonymous
if (conditions and
'is_anonymous' not in conditions and
'is_active' not in conditions):
conditions.append('is_active')
passes_conditions = all([getattr(user, perm) for perm in conditions])
attributes = [getattr(user, perm) for perm in conditions]
# evaluates methods, explicitly casts properties to booleans
passes_conditions = all([
attr() if callable(attr) else bool(attr) for attr in attributes])
return passes_conditions and user.has_perms(regular_permissions)

if permissions is None:
if not permissions:
return True
elif isinstance(permissions, list):
return _check_one_permission_list(permissions)
Expand Down

0 comments on commit a400a24

Please sign in to comment.