Skip to content

Commit

Permalink
Add username validation to registration forms
Browse files Browse the repository at this point in the history
  • Loading branch information
aottr committed Mar 13, 2024
1 parent 07e7122 commit 399cc20
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 8 deletions.
20 changes: 15 additions & 5 deletions core/forms.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from django import forms
from django.conf import settings
from .models import PawUser

from django.utils.translation import gettext_lazy as _

class UserChangeForm(forms.Form):
email = forms.EmailField(required=True, widget=forms.EmailInput(
Expand All @@ -20,10 +20,21 @@ class Meta:
fields = ('email', 'profile_picture',
'language', 'telegram_username', 'use_darkmode')

USERNAME_REGEX_FIELD = forms.RegexField(
required=True,
label='Username',
max_length=50,
regex=r'^[a-zA-Z0-9-_@]+$',
error_messages={
'required': _('Please enter your name'),
'invalid': _('Alphanumeric characters and underscores and dashes only (a-z, 0-9, _, -, @)')
},
widget=forms.TextInput(
attrs={'placeholder': _('Username'), 'class': 'input input-bordered w-full'}),
)

class RegisterForm(forms.Form):
username = forms.CharField(required=True, widget=forms.TextInput(
attrs={'class': 'input input-bordered w-full'}))
username = USERNAME_REGEX_FIELD
email = forms.EmailField(required=True, widget=forms.EmailInput(
attrs={'class': 'input input-bordered w-full'}))
password = forms.CharField(required=True, widget=forms.PasswordInput(
Expand Down Expand Up @@ -61,8 +72,7 @@ def clean(self):


class AccountFinishForm(forms.Form):
username = forms.CharField(required=True, widget=forms.TextInput(
attrs={'class': 'input input-bordered w-full'}))
username = USERNAME_REGEX_FIELD

class Meta:
model = PawUser
Expand Down
6 changes: 3 additions & 3 deletions core/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,13 +89,13 @@ def google_callback_view(request):
except Exception:
return redirect("login")

user, created = PawUser.objects.get_or_create(email=user_info["email"])
user, created = PawUser.objects.get_or_create(email=user_info["email"], username=user_info["email"])

if created:
GoogleSSOUser.objects.create(user=user, google_id=user_info["id"])
GoogleSSOUser.objects.create(paw_user=user, google_id=user_info["id"])

login(request, user)
if created or not user.username:
if created or user.username == user.email:
form = AccountFinishForm()
return render(request, "core/account_finish.html", {"form": form})

Expand Down

0 comments on commit 399cc20

Please sign in to comment.