"""Authentication backends for IILMP.

v1 ships with email + password + TOTP MFA only. SSO (OAuth2 / SAML / OIDC)
is **out of scope for v1** — see `setup/SRS.md` §"Authentication scope (v1)".
The ``LINKEDIN_*`` env vars in ``config/settings/base.py`` are placeholders
reserved for a future LinkedIn OIDC sign-in flow; they have no effect today.

If/when SSO is reintroduced, prefer ``mozilla-django-oidc`` for OIDC providers
(Google Workspace, Microsoft Entra) or ``djangosaml2`` for SAML. Add the
backend to ``AUTHENTICATION_BACKENDS`` and wire the callback routes in
``apps.core.authentication.urls``.
"""
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend

User = get_user_model()


class EmailBackend(ModelBackend):
    """Authenticate with email + password (USERNAME_FIELD = email)."""

    def authenticate(self, request, username=None, password=None, **kwargs):
        email = kwargs.get("email") or username
        if email is None or password is None:
            return None
        try:
            user = User.objects.get(email__iexact=email)
        except User.DoesNotExist:
            User().set_password(password)
            return None
        if user.check_password(password) and self.user_can_authenticate(user):
            return user
        return None
