from django.core.exceptions import ValidationError
from .models import LoginToken, User


class PasswordlessAuthenticationBackend:
    def authenticate(self, request, uid=None):
        if uid is None:
            return None
        try:
            login_token = LoginToken.objects.get(uid=uid)
        except (LoginToken.DoesNotExist, ValidationError):
            return None
        try:
            return User.objects.get(email=login_token.email)
        except User.DoesNotExist:
            return User.objects.create_user(email=login_token.email)

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None # could also pass (which = return None)
        