From e67e89a09b8444a73de2d01331eab9d68418669c Mon Sep 17 00:00:00 2001 From: Kumi Date: Sat, 16 Nov 2024 22:27:55 +0100 Subject: [PATCH] feat: Add registration rate limiting mechanism Introduces a rate limiting mechanism to prevent excessive registration attempts from a single IP address by displaying a custom message when limits are exceeded. Limits users to 5 registration attempts within a 24-hour period by checking recent attempts and blocking additional ones when necessary. This helps prevent abuse and overloading of the registration system. --- .../templates/registration/ratelimit.html | 9 +++++++++ src/synapse_registration/registration/views.py | 17 +++++++++++++++-- 2 files changed, 24 insertions(+), 2 deletions(-) create mode 100644 src/synapse_registration/registration/templates/registration/ratelimit.html diff --git a/src/synapse_registration/registration/templates/registration/ratelimit.html b/src/synapse_registration/registration/templates/registration/ratelimit.html new file mode 100644 index 0000000..8b8e4dc --- /dev/null +++ b/src/synapse_registration/registration/templates/registration/ratelimit.html @@ -0,0 +1,9 @@ +{% extends "base.html" %} +{% block title %} + Hold Your Horses +{% endblock title %} +{% block content %} +
+ You cannot start additional registrations at this time. +
+{% endblock content %} diff --git a/src/synapse_registration/registration/views.py b/src/synapse_registration/registration/views.py index 5f9936e..80c48be 100644 --- a/src/synapse_registration/registration/views.py +++ b/src/synapse_registration/registration/views.py @@ -3,10 +3,14 @@ from django.shortcuts import render, redirect, get_object_or_404 from django.urls import reverse_lazy from django.core.mail import send_mail from django.conf import settings + from .forms import UsernameForm, EmailForm, RegistrationForm from .models import UserRegistration + import requests + from secrets import token_urlsafe +from datetime import datetime, timedelta class LandingPageView(TemplateView): @@ -51,13 +55,22 @@ class EmailInputView(FormView): ) return self.form_invalid(form) - token = token_urlsafe(32) - if not settings.TRUST_PROXY: ip_address = self.request.META.get("REMOTE_ADDR") else: ip_address = self.request.META.get("HTTP_X_FORWARDED_FOR") + if ( + UserRegistration.objects.filter( + ip_address=ip_address, + timestamp__gte=datetime.now() - timedelta(hours=24), + ).count() + >= 5 + ): + return render(self.request, "registration/ratelimit.html", status=429) + + token = token_urlsafe(32) + UserRegistration.objects.create( username=self.request.session["username"], email=email,