1
e11sync/app/signup/views.py

61 lines
1.9 KiB
Python
Raw Permalink Normal View History

2024-01-11 23:36:15 +02:00
import logging
2024-01-12 12:12:13 +02:00
import geoip2
2024-01-11 23:36:15 +02:00
2024-01-12 12:12:13 +02:00
from django.contrib.gis.geoip2 import GeoIP2
2024-01-11 23:36:15 +02:00
from django.shortcuts import render, redirect
2024-01-12 00:05:57 +02:00
from django.urls import reverse
2024-01-11 23:36:15 +02:00
from django.db import IntegrityError
2024-01-12 12:12:13 +02:00
from django.core.exceptions import ValidationError
from django.db.utils import DatabaseError
2024-01-11 23:36:15 +02:00
from lib.anonymize_ip import anonymize_ip
from .models import Signup
logger = logging.getLogger(__name__)
2023-12-14 18:27:56 +02:00
def index(request):
2024-01-11 23:36:15 +02:00
if request.method == "POST":
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
anonymous_ip = anonymize_ip(ip)
2024-01-12 12:12:13 +02:00
try:
geoip = GeoIP2().city(anonymous_ip)
except geoip2.errors.AddressNotFoundError:
geoip = None
s = Signup(
2024-01-15 09:09:39 +02:00
email=request.POST.get("email"),
anonymized_ip=anonymous_ip,
2024-03-05 12:06:51 +02:00
user_agent=request.META.get('HTTP_USER_AGENT', ''),
2024-01-15 09:09:39 +02:00
geoip=geoip,
2024-02-27 18:30:20 +02:00
referrer=request.META.get('HTTP_REFERRER', ''),
2024-01-11 23:36:15 +02:00
)
try:
2024-01-12 12:12:13 +02:00
s.clean_fields()
2024-01-11 23:36:15 +02:00
except ValidationError as e:
2024-01-12 12:12:13 +02:00
return render(request, "signup/index.html",
2024-03-05 12:06:51 +02:00
{"error_message": ", ".join(e.messages)})
2024-01-11 23:36:15 +02:00
logging.info("registering email={}".format(request.POST.get("email")))
try:
2024-01-12 12:12:13 +02:00
s.save()
2024-01-11 23:36:15 +02:00
except IntegrityError:
# email already registered, presumably
2024-01-12 00:11:23 +02:00
return redirect(reverse("index") + "?success=already_subscribed")
2024-01-11 23:36:15 +02:00
except DatabaseError:
logger.exception("database error when registering an email")
2024-01-15 09:09:39 +02:00
err = "Sorry, database error. Please come back later."
2024-01-11 23:36:15 +02:00
return render(request, "signup/index.html",
{"error_message": err})
2024-01-12 00:11:23 +02:00
return redirect(reverse("index") + "?success=subscribed")
2024-01-11 23:36:15 +02:00
2023-12-14 22:41:20 +02:00
return render(request, "signup/index.html", {})