added user identity check on deck edit

This commit is contained in:
Alexander Karpov 2022-06-08 19:03:38 +03:00
parent 56dc11c7b3
commit ea262c3c98
3 changed files with 32 additions and 2 deletions

View File

@ -90,7 +90,6 @@ class CreateDeckSerializer(serializers.ModelSerializer):
return instance
class GetPlayerSerializer(serializers.ModelSerializer):
class Meta:
model = Player

View File

@ -79,7 +79,11 @@ class PlayerCreateView(GenericAPIView, CreateModelMixin):
access_jwt = sign_jwt({"id": instance.id, "type": "access"}, t_life=3600)
refresh_jwt = sign_jwt({"id": instance.id, "type": "refresh"})
return Response(
{"access_token": access_jwt, "refresh_token": refresh_jwt},
{
"access_token": access_jwt,
"refresh_token": refresh_jwt,
"deck_id": instance.get_last_deck().id,
},
status=status.HTTP_201_CREATED,
)
@ -96,6 +100,7 @@ class DeckCreateView(GenericAPIView, CreateModelMixin):
serializer.is_valid(raise_exception=True)
instance = self.perform_create(serializer)
heroes_list = ListHeroSerializer(instance.get_heroes(), many=True)
heroes_list.data["deck_id"] = instance.id
return Response(heroes_list.data, status=status.HTTP_201_CREATED)
@ -115,10 +120,30 @@ class RetireUpdateDeleteDeckView(
return self.retrieve(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
if not self._check_user_identity(request.user.id, kwargs["id"]):
return Response(
"Attempt to change another user's deck",
status=status.HTTP_403_FORBIDDEN,
)
return self.update(request, *args, **kwargs)
def patch(self, request, *args, **kwargs):
if not self._check_user_identity(request.user.id, kwargs["id"]):
return Response(
"Attempt to change another user's deck",
status=status.HTTP_403_FORBIDDEN,
)
return self.partial_update(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
if not self._check_user_identity(request.user.id, kwargs["id"]):
return Response(
"Attempt to delete another user's deck",
status=status.HTTP_403_FORBIDDEN,
)
return self.destroy(request, *args, **kwargs)
def _check_user_identity(self, user_id, deck_id) -> bool:
return deck_id in list(
Deck.objects.filter(player_id=user_id).values_list("id", flat=True)
)

View File

@ -29,7 +29,9 @@ class Player(models.Model):
def save(
self, force_insert=False, force_update=False, using=None, update_fields=None
):
"""saves user and creates deck for him with 16 heroes"""
super(Player, self).save()
deck = Deck.objects.create(player=self)
types = (
["ARCHER" for _ in range(4)]
+ ["WARRIOR" for _ in range(6)]
@ -54,6 +56,10 @@ class Player(models.Model):
hero.speed = random.randint(0, 10)
hero.save()
HeroInDeck.objects.create(deck=deck, hero=hero)
def get_last_deck(self):
return Deck.objects.filter(player=self).last()
def __str__(self):
return self.name