[Django]-Django user logged out after password change

18👍

My understanding is being logged out after password change is new in Django 1.7. So you will need to re-auth user in your code as you said.

See Release Notes:
https://docs.djangoproject.com/en/1.8/releases/1.7/#django-contrib-auth

Here is the specific note:
“The AbstractBaseUser.get_session_auth_hash() method was added and if your AUTH_USER_MODEL inherits from AbstractBaseUser, changing a user’s password now invalidates old sessions if the SessionAuthenticationMiddleware is enabled. See Session invalidation on password change for more details including upgrade considerations when enabling this new middleware.”

See Documentation:
https://docs.djangoproject.com/en/1.7/topics/auth/default/#session-invalidation-on-password-change

31👍

For django 1.9:

from django.contrib.auth import update_session_auth_hash

def password_change(request):
    if request.method == 'POST':
        form = PasswordChangeForm(user=request.user, data=request.POST)
        if form.is_valid():
            form.save()
            update_session_auth_hash(request, form.user)

The following fields must be supplied in the POST request:

  • old_password
  • new_password1
  • new_password2

See detailed docs at update_session_auth_hash

17👍

For Django 1.8

Simply call update_session_auth_hash after set_password like so:

from django.contrib.auth import update_session_auth_hash

request.user.set_password(form.cleaned_data['password'])
update_session_auth_hash(request, request.user)

1👍

for Django 3, Django 1.8+ use this link:
https://docs.djangoproject.com/en/3.2/topics/auth/default/#django.contrib.auth.update_session_auth_hash

or use this code:

from django.contrib.auth import update_session_auth_hash

def password_change(request):
    if request.method == 'POST':
        form = PasswordChangeForm(user=request.user, data=request.POST)
        if form.is_valid():
            form.save()
            update_session_auth_hash(request, form.user)
    else:
        ...

0👍

As of Django 1.11 you can use post_reset_login=True. See details here: https://stackoverflow.com/a/47535448/10039005

Leave a comment