You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
61 lines
1.9 KiB
61 lines
1.9 KiB
from django.contrib.auth import get_user_model
|
|
from django.contrib.auth.backends import ModelBackend
|
|
|
|
|
|
class EmailOrUsernameModelBackend(ModelBackend):
|
|
"""
|
|
自定义认证后端,允许用户使用用户名或邮箱登录
|
|
Extends ModelBackend to allow authentication using either username or email.
|
|
"""
|
|
|
|
def authenticate(self, request, username=None, password=None, **kwargs):
|
|
"""
|
|
用户认证方法
|
|
Authenticate a user based on username/email and password.
|
|
|
|
Args:
|
|
request: HTTP请求对象
|
|
username: 用户输入的用户名或邮箱
|
|
password: 用户输入的密码
|
|
**kwargs: 其他参数
|
|
|
|
Returns:
|
|
User: 认证成功的用户对象
|
|
None: 认证失败
|
|
"""
|
|
# 判断输入的是邮箱还是用户名
|
|
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:
|
|
# 用户不存在时返回None
|
|
return None
|
|
|
|
def get_user(self, user_id):
|
|
"""
|
|
根据用户ID获取用户对象
|
|
Get a user by their primary key.
|
|
|
|
Args:
|
|
user_id: 用户ID
|
|
|
|
Returns:
|
|
User: 用户对象
|
|
None: 用户不存在
|
|
"""
|
|
try:
|
|
# 通过主键查找用户
|
|
return get_user_model().objects.get(pk=user_id)
|
|
except get_user_model().DoesNotExist:
|
|
# 用户不存在时返回None
|
|
return None |