1
0
clubhaus-schornbach/clubhaus/homepage/views.py

67 lines
2.5 KiB
Python
Raw Normal View History

import django.utils.timezone
2022-07-30 18:02:05 +02:00
from django.core.cache import cache
from django.http import HttpRequest, HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from .models import Tobacco, ClubhausEvent, EventDate, EventDateVotes
2022-08-03 02:06:55 +02:00
import clubhaus.settings as django_settings
def index(request: HttpRequest) -> django.http.HttpResponse:
return render(request, 'homepage/index.html', {})
2022-07-30 18:02:05 +02:00
def tobacco(request: HttpRequest) -> django.http.HttpResponse:
2022-07-31 18:53:53 +02:00
context = {'tobaccos': Tobacco.objects.all().order_by('-in_stock')}
return render(request, 'homepage/tobacco.html', context)
2022-07-30 18:02:05 +02:00
def events(request: HttpRequest) -> django.http.HttpResponse:
next_events = ClubhausEvent.objects.filter(active=True).order_by('-id')
if len(next_events) == 1:
next_event = next_events[0]
dates = EventDate.objects.filter(event=next_event).order_by("date")
votes = EventDateVotes.objects.filter(date__event=next_event)
voter_names = sorted(set(map(lambda v: v.name, votes)))
vote_map = {}
for voter_name in voter_names:
vote_map[voter_name] = {date.date.isoformat(): False for date in dates}
for vote in votes:
v_name = vote.name
v_date = vote.date.date.isoformat()
if v_name in vote_map and v_date in vote_map[v_name]:
vote_map[v_name][v_date] = True
return render(request, 'homepage/events.html', {'next_event': next_event, "dates": dates, 'votes': vote_map})
else:
return HttpResponseRedirect(reverse("index"))
2022-07-30 18:02:05 +02:00
def voting(request: HttpRequest) -> django.http.HttpResponse:
request.session.clear_expired()
2022-07-31 18:53:53 +02:00
2022-08-03 02:06:55 +02:00
# Proxy use is forbidden
if request.META.get("X-Forwarded-For"):
return HttpResponseForbidden()
2022-07-30 18:02:05 +02:00
ip = request.META.get("REMOTE_ADDR")
cache_key = f"voting_block_{ip}"
2022-07-30 18:02:05 +02:00
rate_cache: django.core.cache.BaseCache = cache
if ip not in rate_cache:
2022-08-03 02:06:55 +02:00
rate_cache.add(cache_key, 0, django_settings.IP_RATE_LIMIT_TIME)
rate_cache.incr(cache_key)
if request.method == "POST" and rate_cache.get(cache_key) < 3:
if name := request.POST["name"]:
request.session["name"] = name
for date in EventDate.objects.filter(event__active=True).order_by("date"):
if date.date.isoformat() in request.POST:
EventDateVotes.objects.update_or_create(name=name, date=date)
else:
EventDateVotes.objects.filter(name=name, date=date).delete()
return HttpResponseRedirect(reverse("events"))