From d41708f6aa90f6bc3e5121f2037d3fdfcf6635ee Mon Sep 17 00:00:00 2001
From: George Katsikas <giorgakis.katsikas@gmail.com>
Date: Thu, 4 Apr 2024 15:50:28 +0200
Subject: [PATCH] forbid invalid characters in username

---
 scipost_django/scipost/forms.py | 11 +++++++++--
 1 file changed, 9 insertions(+), 2 deletions(-)

diff --git a/scipost_django/scipost/forms.py b/scipost_django/scipost/forms.py
index 9c733c24d..43b03ece2 100644
--- a/scipost_django/scipost/forms.py
+++ b/scipost_django/scipost/forms.py
@@ -256,9 +256,16 @@ class RegistrationForm(forms.Form):
         return self.cleaned_data.get("password_verif", "")
 
     def clean_username(self):
-        if User.objects.filter(username=self.cleaned_data["username"]).exists():
+        # Username should not contain spaces or special characters
+        username = self.cleaned_data.get("username", "")
+        if re.search(r"[^a-zA-Z0-9._@\-+]", username):
+            raise forms.ValidationError(
+                "Your username may only contain letters, numbers, and any of the following: . _ @ - +"
+            )
+
+        if User.objects.filter(username=username).exists():
             self.add_error("username", "This username is already in use")
-        return self.cleaned_data.get("username", "")
+        return username
 
     def clean_email(self):
         if User.objects.filter(email=self.cleaned_data["email"]).exists():
-- 
GitLab