使用mysql数据库通过电子邮件进行django身份验证

时间:2020-06-07 14:35:28

标签: python django

我尝试了很多方法来解决我的问题,但是我想代码无法正常工作,但是它在数据库中找不到类似的行,或者我无法登录。 我从某个网站复制了电子邮件后端,但我自己写的没有,所以如果有原因在学习python网站开发,我就找不到错误。

views.py

  from django.shortcuts import render
from django.contrib.auth import authenticate
from Play.models import user
from django.contrib.auth.models import User
from django.contrib.auth.models import auth
from django.shortcuts import redirect
from django.shortcuts import HttpResponse
from django.contrib.auth.hashers import make_password

def JoinRequest(request):

    if request.method == 'POST':
        fullname = request.POST['fullname']
        email = request.POST['email']
        phone = request.POST['phone']
        password = request.POST['password']
        cpassword = request.POST['cpassword']

        #encpass = make_password(password)

        def get_client_ip(request):
            x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
            if x_forwarded_for:
                ip = x_forwarded_for.split(',')[-1].strip()
            else:
                ip = request.META.get('REMOTE_ADDR')
            return ip

        if password != cpassword:
            return HttpResponse('Password Not Matching To Confirm Password Value..')

        else:
            senddata = user(fullname=fullname, email=email, phone=phone, password=password , ipaddress=get_client_ip(request))
            senddata.save()


            return HttpResponse('')



def Join_View(request):
    return render(request, 'Join.html', {})

def login_view(request):
    return render(request, 'Login.html', {})


def LoginREQUEST(request):

    if request.method == 'POST':
        username = request.POST['email']
        password = request.POST['password']

        user = auth.authenticate(username=username, password=password)

        if user is not None:

            auth.login(request, user)
            return HttpResponse('DONE')
        else:
            return HttpResponse("NONE")

SETTINGS.py

AUTHENTICATION_BACKENDS = [
    'Accounts.EmailAuthentication.EmailOrUsernameModelBackend',
]

EmailAuthentication.py

   from django.contrib.auth import get_user_model
from django.http import HttpResponse
from django.contrib.auth.backends import ModelBackend as _ModelBackend

User = get_user_model()


class EmailOrUsernameModelBackend(_ModelBackend):
    """ Authenticate user by username or email """

    def authenticate(self, username=None, password=None):
        try:
            user = User.objects.get(email=username)
            if user.check_password(password):
                return user
            else:
                return None
        except User.DoesNotExist:
            return None

    def get_user(self, user_id=None):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

请在代码中仔细查看压痕。

数据插入正在正常进行。

0 个答案:

没有答案