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.
This commit is contained in:
Kumi 2024-11-16 22:27:55 +01:00
parent 0e8116cd68
commit e67e89a09b
Signed by: kumi
GPG key ID: ECBCC9082395383F
2 changed files with 24 additions and 2 deletions

View file

@ -0,0 +1,9 @@
{% extends "base.html" %}
{% block title %}
Hold Your Horses
{% endblock title %}
{% block content %}
<div class="notification is-danger">
You cannot start additional registrations at this time.
</div>
{% endblock content %}

View file

@ -3,10 +3,14 @@ from django.shortcuts import render, redirect, get_object_or_404
from django.urls import reverse_lazy from django.urls import reverse_lazy
from django.core.mail import send_mail from django.core.mail import send_mail
from django.conf import settings from django.conf import settings
from .forms import UsernameForm, EmailForm, RegistrationForm from .forms import UsernameForm, EmailForm, RegistrationForm
from .models import UserRegistration from .models import UserRegistration
import requests import requests
from secrets import token_urlsafe from secrets import token_urlsafe
from datetime import datetime, timedelta
class LandingPageView(TemplateView): class LandingPageView(TemplateView):
@ -51,13 +55,22 @@ class EmailInputView(FormView):
) )
return self.form_invalid(form) return self.form_invalid(form)
token = token_urlsafe(32)
if not settings.TRUST_PROXY: if not settings.TRUST_PROXY:
ip_address = self.request.META.get("REMOTE_ADDR") ip_address = self.request.META.get("REMOTE_ADDR")
else: else:
ip_address = self.request.META.get("HTTP_X_FORWARDED_FOR") 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( UserRegistration.objects.create(
username=self.request.session["username"], username=self.request.session["username"],
email=email, email=email,