From 61555f9e3402e175e034a1ab57e0d4540a4c4e67 Mon Sep 17 00:00:00 2001 From: Kumi Date: Sat, 16 Nov 2024 20:40:51 +0100 Subject: [PATCH] feat: Adds username validation in registration form Introduces logic to clean and validate usernames by ensuring they remove the matrix domain prefix/suffix, are not empty, and contain only allowed characters. Enhances input validation for improved user error messaging. --- .../registration/forms.py | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/synapse_registration/registration/forms.py b/src/synapse_registration/registration/forms.py index a35460d..4b2166f 100644 --- a/src/synapse_registration/registration/forms.py +++ b/src/synapse_registration/registration/forms.py @@ -1,4 +1,5 @@ from django import forms +from django.conf import settings class UsernameForm(forms.Form): @@ -9,6 +10,27 @@ class UsernameForm(forms.Form): ), ) + def clean(self): + cleaned_data = super().clean() + username = cleaned_data.get("username") + + if username.startswith("@") and username.endswith(f":{settings.MATRIX_DOMAIN}"): + username = username[1:-len(f":{settings.MATRIX_DOMAIN}")] + + if not username: + self.add_error("username", "Username cannot be empty.") + + if not all( + c in "abcdefghijklmnopqrstuvwxyz0123456789._=-" for c in username.lower() + ): + self.add_error( + "username", + "Username can only contain the characters a-z, 0-9, ., _, =, -, and /.", + ) + + cleaned_data["username"] = username + return cleaned_data + class EmailForm(forms.Form): email = forms.EmailField(