Home > Blockchain >  Django request doesn't save the logged in user
Django request doesn't save the logged in user

Time:04-30

So I'm starting to learn Django authentication.

from django.contrib.auth import login as log_in

def login(request):
    ...
    if request.method == "POST":
            form = UserLoginForm(request.POST)
            if form.is_valid():
                user = User.objects.filter(email=form.cleaned_data["email"])
                if user.exists():
                    user = user.first()
                    if check_password(
                        form.cleaned_data["password"], user.password
                    ):
                        log_in(request,user)
                        return redirect("/main/")
                    else:
                        messages.warning(request, "email/password are incorrect")
                else:
                    messages.warning(request, "User not found")
    ...

and I'm trying to access the request.user in another view like this:

if request.user.is_authenticated:
    #do somthing 

but while debugging I found that after the first code log_in() statement the request.user is authenticated, but in the seconed code it's not.

CodePudding user response:

You have to set the authentication backend:

    from django.conf import settings
    # ...
    user.backend = settings.AUTHENTICATION_BACKENDS[0]
    log_in(request, user)

CodePudding user response:

I found the problem, The problem is that I'm using a custom user model with an email attribute instead of a username so I had to build a new Backend to use with my custom model, then added it to the AUTHENTICATION_BACKENDS in the settings.py file.

from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.hashers import check_password
from .models import User

class NewBackend(ModelBackend):
    def authenticate(self, request, email, password) -> User:
        try:
            user: User = User.objects.get(email=email)
            if user.check_password(password):
                return user
            else:
                return None
        except User.DoesNotExist:
            return None

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

and in views.py

def login(request: HttpRequest):
    if request.user.is_authenticated:
        return redirect("/main/")
    if request.method == "POST":
        form = UserLoginForm(request.POST)
        if form.is_valid():
            umail=form.cleaned_data['email']
            upasswd=form.cleaned_data['password']
            user = authenticate(request=request,email=umail,password=upasswd)
            if user is not None:         
                    log_in(request,user)
                    return redirect("/main/")
            else:
                messages.warning(request, "email/password are incorrect")
    form = UserLoginForm()
    context = {"title": "Login", "form": form}
    return render(request, "login.html", context)

settings.py:

AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
    'login_signup.backend.NewBackend',
]
  • Related