1
e11sync/app/signup/views.py

61 lines
1.9 KiB
Python

import logging
import geoip2
from django.contrib.gis.geoip2 import GeoIP2
from django.shortcuts import render, redirect
from django.urls import reverse
from django.db import IntegrityError
from django.core.exceptions import ValidationError
from django.db.utils import DatabaseError
from lib.anonymize_ip import anonymize_ip
from .models import Signup
logger = logging.getLogger(__name__)
def index(request):
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)
try:
geoip = GeoIP2().city(anonymous_ip)
except geoip2.errors.AddressNotFoundError:
geoip = None
s = Signup(
email=request.POST.get("email"),
anonymized_ip=anonymous_ip,
user_agent=request.META.get('HTTP_USER_AGENT', ''),
geoip=geoip,
referrer=request.META.get('HTTP_REFERRER', ''),
)
try:
s.clean_fields()
except ValidationError as e:
return render(request, "signup/index.html",
{"error_message": ", ".join(e.messages)})
logging.info("registering email={}".format(request.POST.get("email")))
try:
s.save()
except IntegrityError:
# email already registered, presumably
return redirect(reverse("index") + "?success=already_subscribed")
except DatabaseError:
logger.exception("database error when registering an email")
err = "Sorry, database error. Please come back later."
return render(request, "signup/index.html",
{"error_message": err})
return redirect(reverse("index") + "?success=subscribed")
return render(request, "signup/index.html", {})