Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How to destroy user session after a password reset/change?

i've recently implemented a simple change password view in my django project. The thing is that the old session should be destroyed for security reasons. What's the best way of doing this without asking the user to log in again.

I think i could just logout/login him/her, something like this:

from django.contrib.auth import login as auth_login
from django.contrib.auth import logout as auth_logout

@login_required
def change_password(request):
  # My stuff
  request.user.set_password(new_password)
  request.user.save()
  # I need this:
  logout(request)
  login(request,request.user)

But i think this is not the best idea. What do you think?

Is there another way to do this?

Am I missing something? (I mean, is this secure)

like image 733
santiagobasulto Avatar asked Feb 29 '12 22:02

santiagobasulto


2 Answers

Take a look at this app https://github.com/atugushev/django-password-session. This package makes invalidated all sessions (except a current session) after change a password.

Also this feature finally was implemented in Django 1.7. See: https://docs.djangoproject.com/en/dev/topics/auth/default/#session-invalidation-on-password-change

like image 194
Albert Tugushev Avatar answered Sep 20 '22 01:09

Albert Tugushev


I just found out that this is now a built-in feature of Django, and has been since 1.7:

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

Essentially, all sessions now include a hash of the users' password, so if the user ever changes their password, all their existing sessions are automatically invalidated.

So, the short answer to your question is: upgrade django.

One possibly undesirable side effect of this change is that, by default, a user ends up having to log in again as soon as they change their password. So you probably actually want the current user session to stay logged in. See the docs already linked, Django's built-in views for password change do that for you default, or you can manually call a function called update_session_auth_hash

like image 23
hwjp Avatar answered Sep 20 '22 01:09

hwjp