Milano Slesarik Milano Slesarik - 25 days ago 8
Ajax Question

Django acts like user is logged in but isn't

I have an

AJAX
login in my Django project. The ajax_login
view
gets POST, authenticate user and returns
JsonResponse
. Everything seems to work correct but the user isn't actually logged in.

The weird is that in the view, I'm testing whether the user is logged in and they are.

VIEW

@csrf_exempt
def ajax_login_(request):
username = request.POST.get('username')
password = request.POST.get('password')

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

if user:
if user.is_authenticated():
print 'IS LOGGED IN' #THIS IS BEING PRINTED INTO CONSOLE SO USER IS LOGGED IN
return JsonResponse({'status':0})

return JsonResponse({'status':1})


AJAX

$(document).ready(function () {
$('.login-form').find('.submitButton').click(function (e) {
var next = $(this).closest('.login-form').find('input[name="next"]').val();
var password = $(this).closest('.login-form').find('#id_password').val();
var username =$(this).closest('.login-form').find('#id_username').val();
e.preventDefault();
var errors = 0;
if (username == '') {
$('#id_username_required').show();
errors += 1;
} else {
$('#id_username_required').hide();
}
if (password == '') {
$('#id_password_required').show();
errors += 1;
} else {
$('#id_password_required').hide();
}

if (errors == 0) {
$.ajax({
url: '/ajax/login/',
type: 'post',
data: {
'password': password,
'username': username,
},
success: function (data) {
if (data.status == 0) {
window.location.reload();
} else {
$('.login-modal-credentials-incorrect').show();
return false;
}
}
});
}
})
});


Can't figure out where is the problem. It suddenly stopped working.

Answer

You have forgotten to call login() after authenticate().

from django.contrib.auth import authenticate, login

def ajax_login_(request):
    ...
    user = authenticate(username=username, password=password)
    if user is not None:
        login(request, user)

See the docs on how to log a user in for more info.

Comments