From 3ff5b9bb70c61ce810e2434d7e15861896eeeddd Mon Sep 17 00:00:00 2001 From: Raz Date: Mon, 13 Jan 2025 13:01:41 +0100 Subject: [PATCH] fix login with email --- padelclub_backend/settings.py | 5 +++ tournaments/backends.py | 38 +++++++++++++++++ tournaments/forms.py | 41 +++++++++++++++++++ .../templates/register_tournament.html | 6 +-- tournaments/templates/registration/login.html | 15 +++++++ .../tournaments/tournament_info.html | 4 +- tournaments/urls.py | 8 +++- 7 files changed, 111 insertions(+), 6 deletions(-) create mode 100644 tournaments/backends.py diff --git a/padelclub_backend/settings.py b/padelclub_backend/settings.py index c1cff4d..f5b9fb4 100644 --- a/padelclub_backend/settings.py +++ b/padelclub_backend/settings.py @@ -149,3 +149,8 @@ from .settings_app import * # settings.py LOGIN_REDIRECT_URL = '/' # Redirect to the homepage after login LOGOUT_REDIRECT_URL = '/' # Redirect to the homepage after logout + +AUTHENTICATION_BACKENDS = [ + 'tournaments.backends.EmailOrUsernameModelBackend', # replace 'yourapp' with your actual app name + 'django.contrib.auth.backends.ModelBackend', +] diff --git a/tournaments/backends.py b/tournaments/backends.py new file mode 100644 index 0000000..04f1346 --- /dev/null +++ b/tournaments/backends.py @@ -0,0 +1,38 @@ +# backends.py +from django.contrib.auth import get_user_model +from django.contrib.auth.backends import ModelBackend +from django.db.models import Q + +from django.contrib.auth import get_user_model +from django.contrib.auth.backends import ModelBackend +from django.db.models import Q +import logging + +logger = logging.getLogger(__name__) + +class EmailOrUsernameModelBackend(ModelBackend): + def authenticate(self, request, username=None, password=None, **kwargs): + UserModel = get_user_model() + + print(f"Backend attempting authentication for: {username}") # Debug print + logger.info(f"Backend attempting authentication for: {username}") + + try: + user = UserModel.objects.get( + Q(username__iexact=username) | Q(email__iexact=username) + ) + print(f"User found: {user}") # Debug print + logger.info(f"User found: {user}") + + if user.check_password(password): + print("Password check successful") # Debug print + logger.info("Password check successful") + return user + print("Password check failed") # Debug print + logger.warning("Password check failed") + return None + + except UserModel.DoesNotExist: + print("User not found") # Debug print + logger.warning("User not found") + return None diff --git a/tournaments/forms.py b/tournaments/forms.py index c13c0a2..c19bfd3 100644 --- a/tournaments/forms.py +++ b/tournaments/forms.py @@ -165,3 +165,44 @@ class CustomPasswordChangeForm(PasswordChangeForm): # Remove autofocus from all fields in the PasswordChangeForm for field in self.fields.values(): field.widget.attrs.pop("autofocus", None) + +from django.contrib.auth.forms import AuthenticationForm +from django.contrib.auth import authenticate # Add this import +from django import forms +import logging + +logger = logging.getLogger(__name__) + +class EmailOrUsernameAuthenticationForm(AuthenticationForm): + username = forms.CharField(label='Username or Email') + + def clean(self): + username = self.cleaned_data.get('username') + password = self.cleaned_data.get('password') + + print(f"Login attempt with username/email: {username}") # Debug print + logger.info(f"Login attempt with username/email: {username}") + + if username and password: + self.user_cache = authenticate( + self.request, + username=username, + password=password + ) + + print(f"Authentication result: {self.user_cache}") # Debug print + logger.info(f"Authentication result: {self.user_cache}") + + if self.user_cache is None: + print("Authentication failed") # Debug print + logger.warning("Authentication failed") + raise forms.ValidationError( + "Please enter a correct username/email and password.", + code='invalid_login' + ) + else: + print(f"Authentication successful for user: {self.user_cache}") # Debug print + logger.info(f"Authentication successful for user: {self.user_cache}") + self.confirm_login_allowed(self.user_cache) + + return self.cleaned_data diff --git a/tournaments/templates/register_tournament.html b/tournaments/templates/register_tournament.html index 81f1305..0528874 100644 --- a/tournaments/templates/register_tournament.html +++ b/tournaments/templates/register_tournament.html @@ -114,11 +114,11 @@
{% if tournament.get_waiting_list_position == 1 %} - {{ tournament.get_waiting_list_position }} équipe en liste d'attente devant vous + Tournoi complet, {{ tournament.get_waiting_list_position }} équipe en liste d'attente devant vous {% elif tournament.get_waiting_list_position > 1 %} - {{ tournament.get_waiting_list_position }} équipes en liste d'attente devant vous + Tournoi complet, {{ tournament.get_waiting_list_position }} équipes en liste d'attente devant vous {% elif tournament.get_waiting_list_position == 0 %} - Aucune équipe en liste d'attente devant vous + Tournoi complet, vous êtes la première équipe en liste d'attente. {% endif %}
diff --git a/tournaments/templates/registration/login.html b/tournaments/templates/registration/login.html index c8cf291..ba26166 100644 --- a/tournaments/templates/registration/login.html +++ b/tournaments/templates/registration/login.html @@ -11,6 +11,21 @@
+ {% if form.errors %} +
+ {% if form.non_field_errors %} + {% for error in form.non_field_errors %} +

{{ error }}

+ {% endfor %} + {% endif %} + + {% for field in form %} + {% for error in field.errors %} +

{{ error }}

+ {% endfor %} + {% endfor %} +
+ {% endif %}
{% csrf_token %} diff --git a/tournaments/templates/tournaments/tournament_info.html b/tournaments/templates/tournaments/tournament_info.html index ae1a0ce..b67bd59 100644 --- a/tournaments/templates/tournaments/tournament_info.html +++ b/tournaments/templates/tournaments/tournament_info.html @@ -20,14 +20,14 @@
{% if team.is_in_waiting_list >= 0 %} - Vous êtes en liste d'attente. + Tournoi complet, vous êtes en liste d'attente.
{% if team.is_in_waiting_list == 1 %} {{ team.is_in_waiting_list }} équipe en liste d'attente devant vous {% elif team.is_in_waiting_list > 1 %} {{ team.is_in_waiting_list }} équipes en liste d'attente devant vous {% elif team.is_in_waiting_list == 0 %} - Aucune équipe en liste d'attente devant vous + vous êtes la première équipe en liste d'attente. {% endif %}
{% endif %} diff --git a/tournaments/urls.py b/tournaments/urls.py index 980e460..66c78d2 100644 --- a/tournaments/urls.py +++ b/tournaments/urls.py @@ -1,5 +1,8 @@ from django.contrib.auth import views as auth_views from django.urls import include, path +from .forms import EmailOrUsernameAuthenticationForm +from django.views.decorators.csrf import ensure_csrf_cookie +from django.utils.decorators import method_decorator from . import views @@ -40,7 +43,10 @@ urlpatterns = [ path('terms-of-use/', views.terms_of_use, name='terms-of-use'), path('utils/xls-to-csv/', views.xls_to_csv, name='xls-to-csv'), path('mail-test/', views.simple_form_view, name='mail-test'), - path('login/', auth_views.LoginView.as_view(), name='login'), + path('login/', method_decorator(ensure_csrf_cookie)(auth_views.LoginView.as_view( + template_name='registration/login.html', + form_class=EmailOrUsernameAuthenticationForm + )), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('signup/', views.signup, name='signup'), # URL pattern for signup # path('profile/', views.profile, name='profile'), # URL pattern for signup