Django多字段认证的实现

Django多字段认证

需求:

django认证的检查用户是username,如果使用 username和 手机号验证登录。

重写:

ModelBackend 类下的 authenticate 方法

python 复制代码
# 在对应应用下创建 utils.py

""" 修改Django认证类,为了实现 username和手机号登录 """

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

from .models import User


def get_user_by_account(account):
    """
    通过传入的账号动态获取 user 模型对象
    :param account: 有可能是手机号,有可能是用户名
    :return: 返回user对象或None
    """
    try:
        # Q查询  |:或; &:与; ~:非;
        user = User.objects.get(Q(username=account) | Q(mobile=account))
    except User.DoesNotExist as e:
        logger.error(f"No user found with account: {account}. Error: {e}")
        return None
    else:
        # 这里返回的是 User 模型的一个实例(即一个用户对象),不是 User 模型类本身。
        return user


class UsernameModelAuthBackend(ModelBackend):
    # 重写 ModelBackend类下的 authenticate 方法
    def authenticate(self, request, username=None, password=None, **kwargs):
    # 获取user
        user = get_user_by_account(account=username)
        # 判断前端传入的密码是否正确
        if user and user.check_password(password):
            logger.info(f'{user} ,authentication is successful ')
            # 返回user
            return user
        # 如果没有找到用户或密码不正确,返回 None
        logger.warning("Authentication failed: either the user does not exist or the password is incorrect.")
        return None
修改setting.py
python 复制代码
# setting.py

""" 修改django认证后端类 """
# django认证的检查用户是username, 默认是 django.contrib.auth.backends.ModelBackend
# AUTHENTICATION_BACKENDS = ["django.contrib.auth.backends.ModelBackend"]
# 修改为自定义的用户验证类, 它也继承了 ModelBackend, 导包
AUTHENTICATION_BACKENDS = ['users.utils.UsernameModelAuthBackend']
相关推荐
WJX_KOI1 小时前
Open Notebook 一个开源的结合AI的记笔记软件
python
0思必得02 小时前
[Web自动化] 反爬虫
前端·爬虫·python·selenium·自动化
2301_822382762 小时前
Python上下文管理器(with语句)的原理与实践
jvm·数据库·python
喵手2 小时前
Python爬虫实战:从零搭建字体库爬虫 - requests+lxml 实战采集字体网字体信息数据(附 CSV 导出)!
爬虫·python·爬虫实战·零基础python爬虫教学·csv导出·采集字体库数据·字体库字体信息采集
2301_790300963 小时前
Python深度学习入门:TensorFlow 2.0/Keras实战
jvm·数据库·python
程序员敲代码吗4 小时前
用Python生成艺术:分形与算法绘图
jvm·数据库·python
Yyyyy123jsjs4 小时前
如何通过免费的外汇API轻松获取实时汇率数据
开发语言·python
喵手4 小时前
Python爬虫实战:GovDataMiner —— 开放数据门户数据集元数据采集器(附 CSV 导出)!
爬虫·python·爬虫实战·python爬虫工程化实战·零基础python爬虫教学·open data·开放数据门户数据集列表
历程里程碑5 小时前
滑动窗口---- 无重复字符的最长子串
java·数据结构·c++·python·算法·leetcode·django