From 3efd2d2a221f5a75760c03750ab4f3a203ab9010 Mon Sep 17 00:00:00 2001 From: Guy Davis Date: Sun, 3 Mar 2024 07:45:44 +1300 Subject: [PATCH] [guivis/KeepPolling#9] - add some testing to disallow unauthenticated users casting votes - added login required to polls endpoints - requiring csrf token for casting vote --- polls/tests.py | 38 ++++++++++++++++++++++++++++++++++++-- polls/views.py | 7 +++++++ 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/polls/tests.py b/polls/tests.py index e9cda6f..b3b3e58 100644 --- a/polls/tests.py +++ b/polls/tests.py @@ -72,7 +72,7 @@ class PollDetailsTests( self, ): """ - If test user has not yet voted, options should be shown + If test user has already voted, results should be shown """ test_user = self.fresh_user_logged_in() poll = self.create_poll_with_questions() @@ -111,7 +111,7 @@ class PollDetailsTests( self, ): """ - If test user has not yet voted, options should be shown + If test user has already voted, voting again should not change anything """ test_user = self.fresh_user_logged_in() poll = self.create_poll_with_questions() @@ -146,3 +146,37 @@ class PollDetailsTests( Vote.objects.count(), 1, ) + + def test_unauthenticated_user_cant_vote( + self, + ): + """ + If an unauthenticated user tries to vote it should fail + """ + poll = self.create_poll_with_questions() + options = Option.objects.filter( + poll=poll, + ) + + self.assertEqual( + Vote.objects.count(), + 0, + ) + + response = self.client.post( + reverse( + "cast-vote", + kwargs={ + "poll_id": poll.pk, + "option_id": options[0].pk, + } + ), + ) + self.assertNotEqual( + response.status_code, + 200, + ) + self.assertEqual( + Vote.objects.count(), + 0, + ) diff --git a/polls/views.py b/polls/views.py index 1e8e4f5..99fe6f6 100644 --- a/polls/views.py +++ b/polls/views.py @@ -1,9 +1,12 @@ +from django.contrib.auth.decorators import login_required from django.db.models import Count from django.shortcuts import render, get_object_or_404 +from django.views.decorators.csrf import requires_csrf_token from polls.models import Poll, Option, Vote +@login_required def polls( request, ): @@ -29,6 +32,7 @@ def already_voted( return vote.exists() +@login_required def poll_results( request, poll_id, @@ -56,6 +60,7 @@ def poll_results( ) +@login_required def poll_details( request, poll_id, @@ -90,6 +95,8 @@ def poll_details( ) +@login_required +@requires_csrf_token def cast_vote( request, poll_id,