#!/usr/bin/env python
# -*- coding: utf-8 -*-

from django.contrib.auth import get_user_model
from django.db.models import Q
from django.contrib.auth.backends import ModelBackend

from common.utils.exceptions import (UserNotFound, AuthenticationError,
                                     PasswordWrong)

UserModel = get_user_model()


class CustomAuthBackend(ModelBackend):
    """
    Authenticates against settings.AUTH_USER_MODEL.
    """
    def authenticate(self, request, username=None, password=None, **kwargs):
        if username is None or password is None:
            return None
        try:
            user = UserModel.objects.all().prefetch_related(
                'user_account').only('username').get(
                    Q(user_account__phone=username)
                    | Q(user_account__email=username)
                    | Q(username=username))
        except UserModel.DoesNotExist:
            raise UserNotFound
        else:
            if not user.check_password(password):
                raise PasswordWrong
            if not self.user_can_authenticate(user):
                msg = 'User account is not active.'
                raise AuthenticationError(msg)
            return user
