Skip to content
Snippets Groups Projects

Hide voters hashes in running election

Merged jan.bednarik requested to merge test into master
4 files
+ 36
5
Compare changes
  • Side-by-side
  • Inline
Files
4
+ 32
4
import re
import pytz
from django.conf import settings
from django.http import JsonResponse
from django.views.generic import TemplateView, View
@@ -21,6 +24,24 @@ class IndexView(TemplateView):
template_name = "api/index.html"
def get_auth_token(headers):
auth_header = headers.get("Authorization", "")
m = re.match(r"Bearer (?P<token>.+)", auth_header)
if m:
return m.group("token")
return None
def should_hide_votes(request, election):
if election.voting_has_started() and not election.voting_has_stopped():
if not settings.API_TOKEN:
return True
if get_auth_token(request.headers) == settings.API_TOKEN:
return False
return True
return False
def election_as_dict(election):
voting_start_at = (
election.voting_start_at.replace(tzinfo=pytz.UTC)
@@ -74,7 +95,10 @@ class UserElectionsView(JsonView):
elections = []
for voter in qs:
election = election_as_dict(voter.election)
election["user_has_voted"] = voter.vote_hash is not None
if should_hide_votes(request, voter.election):
election["user_has_voted"] = False
else:
election["user_has_voted"] = voter.vote_hash is not None
elections.append(election)
return {"username": username, "elections": elections}
@@ -90,14 +114,18 @@ class ElectionVotersView(JsonView):
result = election_as_dict(election)
result["voters"] = []
hide_votes = should_hide_votes(request, election)
voters = (
election.voter_set.all()
.values_list("user__user_id", "vote_hash")
.order_by("user__user_id")
)
for user_id, vote_hash in voters:
result["voters"].append(
{"username": user_id, "has_voted": vote_hash is not None}
)
if hide_votes:
has_voted = False
else:
has_voted = vote_hash is not None
result["voters"].append({"username": user_id, "has_voted": has_voted})
return result
Loading