1
0
Fork 0
mirror of https://github.com/seanmorley15/AdventureLog.git synced 2025-07-19 04:49:37 +02:00

Refactor authentication backends to enhance NoPasswordAuthBackend functionality; integrate Allauth for email login and improve password handling logic.

This commit is contained in:
Sean Morley 2025-05-28 12:21:43 -04:00
parent a7128756bd
commit 8be723b9ad
2 changed files with 35 additions and 8 deletions

View file

@ -238,8 +238,8 @@ HEADLESS_FRONTEND_URLS = {
AUTHENTICATION_BACKENDS = [ AUTHENTICATION_BACKENDS = [
'users.backends.NoPasswordAuthBackend', 'users.backends.NoPasswordAuthBackend',
'allauth.account.auth_backends.AuthenticationBackend', # 'allauth.account.auth_backends.AuthenticationBackend',
'django.contrib.auth.backends.ModelBackend', # 'django.contrib.auth.backends.ModelBackend',
] ]
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

View file

@ -1,15 +1,42 @@
from django.contrib.auth.backends import ModelBackend from django.contrib.auth.backends import ModelBackend
from allauth.socialaccount.models import SocialAccount from allauth.socialaccount.models import SocialAccount
from allauth.account.auth_backends import AuthenticationBackend as AllauthBackend
from django.contrib.auth import get_user_model
User = get_user_model()
class NoPasswordAuthBackend(ModelBackend): class NoPasswordAuthBackend(ModelBackend):
def authenticate(self, request, username=None, password=None, **kwargs): def authenticate(self, request, username=None, password=None, **kwargs):
# First, attempt normal authentication # Handle allauth-specific authentication (like email login)
user = super().authenticate(request, username=username, password=password, **kwargs) allauth_backend = AllauthBackend()
if user is None: allauth_user = allauth_backend.authenticate(request, username=username, password=password, **kwargs)
# If allauth handled it, check our password disable logic
if allauth_user:
has_social_accounts = SocialAccount.objects.filter(user=allauth_user).exists()
if has_social_accounts and getattr(allauth_user, 'disable_password', False):
return None
return allauth_user
# Fallback to regular username/password authentication
if username is None or password is None:
return None return None
if SocialAccount.objects.filter(user=user).exists() and user.disable_password: try:
# If yes, disable login via password # Get the user first
user = User.objects.get(username=username)
except User.DoesNotExist:
return None return None
return user # Check if this user has social accounts and password is disabled
has_social_accounts = SocialAccount.objects.filter(user=user).exists()
# If user has social accounts and disable_password is True, deny password login
if has_social_accounts and getattr(user, 'disable_password', False):
return None
# Otherwise, proceed with normal password authentication
if user.check_password(password) and self.user_can_authenticate(user):
return user
return None