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

63 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
2022-08-03 02:07:44 +02:00
from django.http import HttpRequest, HttpResponseRedirect, HttpResponseForbidden
from django.shortcuts import render
from django.urls import reverse
2022-08-03 02:06:55 +02:00
import clubhaus.settings as django_settings
2022-08-03 02:07:44 +02:00
from .models import Tobacco, ClubhausEvent, EventDate, EventDateVotes, VotingUser
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")
2022-08-03 02:07:44 +02:00
votes = EventDateVotes.objects.filter(date__event=next_event).order_by("voter_id", "date")
2022-08-03 02:07:44 +02:00
return render(request, 'homepage/events.html', {'next_event': next_event, "dates": dates, 'votes': votes})
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)
2022-08-03 02:07:44 +02:00
if request.method != "POST" and rate_cache.get(cache_key) > django_settings.IP_RATE_LIMIT_COUNT:
return HttpResponseRedirect(reverse("events"))
modify_key = request.POST["modifyKey"] or ""
if name := request.POST["name"]:
request.session["name"] = name
request.session["modifyKey"] = modify_key
user, _ = VotingUser.objects.get_or_create(name=name, modify_key=modify_key)
event_dates = EventDate.objects.filter(event__active=True).order_by("date")
for date in event_dates:
date_in_request = date.date.isoformat() in request.POST
EventDateVotes.objects.update_or_create(
voter=user, date=date,
defaults={"voter": user, "date": date, "available": date_in_request})
return HttpResponseRedirect(reverse("events"))