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


# 用户认证方法 - 验证用户凭据并返回用户对象
class EmailOrUsernameModelBackend(ModelBackend):
    """
    允许使用用户名或邮箱登录
    """

    # 用户认证方法 - 验证用户凭据并返回用户对象
    def authenticate(self, request, username=None, password=None, **kwargs):
        if '@' in username:
            kwargs = {'email': username}
        else:
            kwargs = {'username': username}
        try:
            user = get_user_model().objects.get(**kwargs)
            if user.check_password(password):
                return user
        except get_user_model().DoesNotExist:
            return None

    # 用户获取方法 - 根据用户ID获取用户对象
    def get_user(self, username):
        try:
            return get_user_model().objects.get(pk=username)
        except get_user_model().DoesNotExist:
            return None
