django自定义后端验证实现账号,手机号,邮箱任一方式登录

自定义后端验证

class MyBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, phone=None, email=None):
        if username and password:
            # user = super(MyBackend, self).authenticate(request, username=username, password=password)
            user = super().authenticate(request, username=username, password=password)
            print('=====----账号-----=====')
            if user:
                return user
            else:
                print('=====----手机-----=====')
                if (phone or email) and password:
                    user = UserProfile.objects.filter(Q(phone=phone) | Q(email=email)).first()
                    if user:
                        print('=====----密码-----=====')
                        if user.check_password(password):
                            return user
                        else:
                            print('======', user.check_password(password))

登录页面函数

class Login(APIView):
    def post(self, request):
        username = request.POST.get('username')
        user = UserProfile.objects.filter(Q(username=username) | Q(phone=username) | Q(email=username)).first()
        print('user=====', user)
        if not user:
            return Response({'msg': '该用户不存在,请注册', "status": 403})
        print('------', user.is_active, user)  # ----- True
        if user.is_active == False:
            return JsonResponse({'msg': '用户尚未激活,请激活', "status": 403})
        password = request.POST.get('password')
        user = authenticate(username=username, password=password, phone=username, email=username)
        # 需要激活后,并且账号密码正确才是TURE
        print('==========++', user)
        if user:
            # 表示用户登陆了,向session添加用户名
            login(request, user)
            serializer = UserProfileSerializer(user)
            # print('+++++',serializer.data.get('email'))
            data = {
                "msg": "登录成功!",
                "status": 200,
            }
            return Response(data)
        return Response({"msg": "账号或密码有误,请重新输入!", "status": 403, })
        
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值