from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend


class PinBackend(ModelBackend):
    """Authenticate festival users by username + 3-digit PIN stored in `pin`.

    Strong passwords stay on the User model for /admin/ via the default
    ModelBackend. Staff can also set a PIN to use the drink tool with the
    same username.
    """

    def authenticate(self, request, username=None, pin=None, **kwargs):
        if username is None or pin is None:
            return None
        User = get_user_model()
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            return None
        if not user.check_pin(pin):
            return None
        if not self.user_can_authenticate(user):
            return None
        return user
