简体   繁体   中英

Django authenticate not keeping user logged in

I am attempting to learn Django's authentication system by contriving a basic login scenario. My views are set up such that a view, logIn , either receives a user's credentials (and prints the success/failure of the login), or it renders a login form.

A second view, privatePage , is designed as a sanity check that the user is actually logged in. The code is as follows:

views.py :

@login_required(login_url='/logIn')
def privatePage(request):
    return HttpResponse("You're viewing a private page")

@csrf_exempt
def logIn(request):
    if request.method == "POST" and \
       request.POST.get('email') and \
       request.POST.get('password'):
        user = authenticate(username=request.POST['email'], 
                            password=request.POST['password'])
        return HttpResponse('Valid login' if user is not None else 'Invalid login')
    # render login form
    return HttpResponse("<form>...</form>")

I'm finding that after succcessfully logging in via the logIn view, I am still redirected to the login view upon trying to visit privatePage . FYI, I'm attempting to visit the privatePage view directly by URL, as opposed to navigating through provided links (eg I'm not sure if I'm violating some CSRF rule).

Any idea what's going on?

You've not actually logged in. You need to login the user after verifying their identity with authenticate :

from django.contrib.auth import login

user = authenticate(email=email, password=password)
    if user is not None:
        login(request, user)

login should only be used on users that have been confirmed to exist.


What authenticate does:

verifies a user is who they claim to be

It does not perform the actual login .

To keep the user logged in a session must be provided to user with usage of login() method. Login is the process of providing user with a session and authenticate() verifies that the given credentials corresponds to an existing user model object in database . Import django's built in login and authenticate methods from django.contrib.auth import authenticate, login . And then your code looks like

user =authenticate(email, password)
    If user:
        login(user, request)

Hope it helps :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM