Skip to content

Commit

Permalink
condition replaced by exception handling in permission checks
Browse files Browse the repository at this point in the history
  • Loading branch information
simonkern committed Jan 5, 2023
1 parent 07cc1b0 commit 922b498
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 9 deletions.
20 changes: 11 additions & 9 deletions hijack/permissions.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
def superusers_only(*, hijacker, hijacked):
"""Superusers may hijack any other user."""
if not hijacked:
try:
return hijacked.is_active and hijacker.is_superuser
except AttributeError:
return False
return hijacked.is_active and hijacker.is_superuser


def superusers_and_staff(*, hijacker, hijacked):
Expand All @@ -12,13 +13,14 @@ def superusers_and_staff(*, hijacker, hijacked):
A superuser may hijack any other user.
A staff member may hijack any user, except another staff member or superuser.
"""
if not hijacked:
return False
try:
if not hijacked.is_active:
return False

if not hijacked.is_active:
return False
if hijacker.is_superuser:
return True

if hijacker.is_superuser:
return True
return hijacker.is_staff and not (hijacked.is_staff or hijacked.is_superuser)

return hijacker.is_staff and not (hijacked.is_staff or hijacked.is_superuser)
except AttributeError:
return False
13 changes: 13 additions & 0 deletions hijack/tests/test_permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,23 @@

from hijack import permissions

from .test_app.models import Post

superuser = get_user_model()(is_superuser=True)
staff_member = get_user_model()(is_staff=True)
regular_user = get_user_model()()
inactive_user = get_user_model()(is_active=False)
post = Post() # lacks all attributes used in permission checks


@pytest.mark.parametrize(
"hijacker, hijacked, has_perm",
[
(post, None, False),
(post, superuser, False),
(post, staff_member, False),
(post, regular_user, False),
(post, inactive_user, False),
(superuser, None, False),
(superuser, superuser, True),
(superuser, staff_member, True),
Expand All @@ -36,6 +44,11 @@ def test_superusers_only(hijacker, hijacked, has_perm):
@pytest.mark.parametrize(
"hijacker, hijacked, has_perm",
[
(post, None, False),
(post, superuser, False),
(post, staff_member, False),
(post, regular_user, False),
(post, inactive_user, False),
(superuser, None, False),
(superuser, superuser, True),
(superuser, staff_member, True),
Expand Down

0 comments on commit 922b498

Please sign in to comment.