Files
Keith SmithandClaude Sonnet 4.5 6eb277c701 Fix authentication: allow superusers to bypass email verification and approval
The authentication backend was requiring ALL users (including superusers)
to have email_verified=True and is_approved=True. This created a
chicken-and-egg problem where the first superuser couldn't log in to
approve themselves.

Now superusers bypass these checks and can log in immediately after
creation via createsuperuser command. Regular users still require
email verification and admin approval.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-26 17:14:46 -07:00

50 lines
1.6 KiB
Python

"""
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