from django.contrib.auth.models import User


def set_auth_hash_getter(user, delegate):
    if hasattr(user, 'get_session_auth_hash') and hasattr(delegate, 'get_session_auth_hash'):
        user.get_session_auth_hash = delegate.get_session_auth_hash


class DelegationAuthBackend:
    supports_object_permissions = False
    supports_anonymous_user = False

    def authenticate(self, request, username=None, password=None):
        try:
            if '-' in username:
                prefix, suffix = username.rsplit('-', 1)
                delegate = User.objects.get(username=username, docbowprofile__is_guest=True)
                if delegate.check_password(password):
                    return delegate
        except User.DoesNotExist:
            pass
        return None

    def get_user(self, user_id):
        try:
            delegate = User.objects.get(pk=user_id, docbowprofile__is_guest=True)
            user = User.objects.get(username=delegate.username.rsplit('-', 1)[0])
            user.delegate = delegate
            set_auth_hash_getter(user, delegate)
            return user
        except User.DoesNotExist:
            return None


try:
    import mellon.backends

    class DocbowMellonAuthBackend(mellon.backends.SAMLBackend):
        def get_user(self, user_id):
            try:
                delegate = User.objects.get(pk=user_id, docbowprofile__is_guest=True)
                if delegate.delegations_by.count() != 1:
                    return None
                user = delegate.delegations_by.first().by
                user.delegate = delegate
                set_auth_hash_getter(user, delegate)
                return user
            except User.DoesNotExist:
                return super().get_user(user_id)

except ImportError:
    pass
