from typing import Any from django.contrib.auth.backends import BaseBackend from django.http import HttpRequest from apps.shared.infrastructure.clock import DjangoClock from apps.users.application.use_cases import CheckLoginAllowed from apps.users.infrastructure.orm import User from apps.users.infrastructure.repositories import DjangoUserRepository class EmailBackend(BaseBackend): """Email + password login; the user must be allowed to log in today (CheckLoginAllowed).""" def authenticate( self, request: HttpRequest | None, username: str | None = None, password: str | None = None, email: str | None = None, **kwargs: Any, ) -> User | None: address = (email or username or "").strip().lower() if not address or password is None: return None user = User.objects.filter(email__iexact=address).first() if user is None: # Run the hasher anyway so response time does not reveal unknown emails. User().set_password(password) return None if user.check_password(password) and self.user_can_authenticate(user): return user return None def user_can_authenticate(self, user: User) -> bool: return CheckLoginAllowed(DjangoUserRepository(), DjangoClock()).execute(user.pk) def get_user(self, user_id: int) -> User | None: return User.objects.filter(pk=user_id).first()