""" Custom authentication backends for KeepItGoing. """ from django.contrib.auth.backends import ModelBackend from django.contrib.auth import get_user_model User = get_user_model() class EmailVerifiedApprovedBackend(ModelBackend): """ Authentication backend that requires email verification and admin approval. This backend extends Django's ModelBackend to add additional checks: - User must have verified their email address - User must be approved by an admin If authentication fails due to these checks, helpful error messages are stored in the session for the web UI. """ def authenticate(self, request, username=None, password=None, **kwargs): # Call parent to do the actual authentication user = super().authenticate(request, username=username, password=password, **kwargs) if user is None: return None # Superusers bypass email verification and approval checks if user.is_superuser: return user # Check email verification for regular users if not user.email_verified: # Store reason for failed login (for web UI) if request: request.session['login_error'] = 'email_not_verified' request.session['login_email'] = user.email return None # Check admin approval for regular users if not user.is_approved: if request: request.session['login_error'] = 'not_approved' request.session['login_email'] = user.email return None return user