Reputation: 37
In my system users first enter the system and must change their password. I have a view that changes the password, The problem is when the page reloads the user session is lost and forces the user to log in again. I do not know how to change this behavior. An overview of my code
views.py
def change_password(request):
if request.method == 'POST':
data = request.body
change = json.loads(data)
id = change["id"]
password = change["password"]
user = get_object_or_404(CustomUser, pk=id)
user.set_password(password)
user.save()
return HttpResponse('success')
def login_success(request):
if request.user.groups.filter(name="group1").exists():
return redirect(group1)
elif request.user.groups.filter(name="group2").exists():
return redirect(group2)
elif request.user.groups.filter(name="group3").exists():
return redirect(group3)
else:
return redirect(group4)
I'm using a CustomUser Model
models.py
class CustomUser(AbstractBaseUser, PermissionsMixin):
...
login = models.BooleanField(_('login'), default=False, blank=True)
...
In my Templates.
{% if user.login %}
<h1>Hi User</h1>
{% else %}
<form name="changePass" method="post">
</form>
{% endif %}
I need the user remains logged in even after changing the password, I do within the templates is to change the status of the login variable in my customuser.
I appreciate any answers or help, Thanks, and sorry for my English.
Upvotes: 1
Views: 1887
Reputation: 178
Since version 1.7, Django has introduced a new feature that invalidates the current session when you update a password from a user. You can see more about it in here: https://docs.djangoproject.com/en/dev/topics/auth/default/#session-invalidation-on-password-change
All you have to do to avoid the logout is call the method update_session_auth_hash
from django.contrib.auth
as the example from the documentation:
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:
...
Upvotes: 8