Restrict access to character view

This commit is contained in:
Gabriel Augendre 2022-11-11 08:59:18 +01:00
parent c2de3c9731
commit ddf1a1b6d3
4 changed files with 59 additions and 1 deletions

View file

@ -86,6 +86,13 @@ class CharacterQuerySet(models.QuerySet):
def owned_by(self, user):
return self.filter(player=user)
def friendly_to(self, user):
from party.models import Party
return self.filter(
Q(player=user) | Q(parties__in=Party.objects.related_to(user))
)
DEFAULT_NOTES = """
#### Traits personnalisés

View file

@ -0,0 +1,45 @@
import pytest
from model_bakery import baker
from character.models import Character
from common.models import User
from party.models import Party
@pytest.mark.django_db
def test_can_access_own_character(client):
# Create a user
player = User.objects.create_user("username", password="password")
character = baker.make(Character, player=player)
client.force_login(player)
res = client.get(character.get_absolute_url())
assert res.status_code == 200
@pytest.mark.django_db
def test_cant_access_random_character(client):
# Create a user
player = User.objects.create_user("user", password="password")
other = User.objects.create_user("other", password="password")
character = baker.make(Character, player=other)
client.force_login(player)
res = client.get(character.get_absolute_url())
assert res.status_code == 404
@pytest.mark.django_db
def test_can_access_character_in_party(client):
# Create a user
player = User.objects.create_user("user", password="password")
friend = User.objects.create_user("friend", password="password")
character = baker.make(Character, player=player)
friend_character = baker.make(Character, player=friend)
party = baker.make(Party)
party.characters.add(character)
party.characters.add(friend_character)
client.force_login(player)
res = client.get(character.get_absolute_url())
assert res.status_code == 200

View file

@ -60,7 +60,7 @@ def character_change(request, pk: int):
@login_required
def character_view(request, pk: int):
character = get_object_or_404(
Character.objects.all()
Character.objects.friendly_to(request.user)
.select_related("player", "racial_capability", "profile", "race")
.prefetch_related("capabilities__path", "weapons"),
pk=pk,

View file

@ -11,3 +11,9 @@ def collectstatic():
def firefox_options(firefox_options):
firefox_options.add_argument("-headless")
return firefox_options
@pytest.fixture(autouse=True)
def settings(settings):
settings.DEBUG_TOOLBAR = False
return settings