Reputation: 3190
I have successfully(hopefully) managed to implement a change_password action.
However, after I change the password, the client automatically logsout. (token is probably not valid anymore)
I would like the API Client to remain logged in after a password reset to make other requests with the new token.
Is there an equivalent for update_session_auth_hash(request, self.object) ?
Serializers:
class PasswordSerializer(serializers.Serializer):
"""
Serializer for password change endpoint.
"""
old_password = serializers.CharField(required=True)
new_password = serializers.CharField(required=True)
API View
@action(methods=['put'], detail=True)
def change_password(self, request, pk):
serializer = PasswordSerializer(data=request.data)
if serializer.is_valid():
user = get_object_or_404(User, pk=pk)
if user != request.user:
return Response({'error': "Cannot change other user's password"},
status=status.HTTP_403_FORBIDDEN)
else:
if not user.check_password(serializer.data.get('old_password')):
return Response({'old_password': ['Wrong password.']},
status=status.HTTP_400_BAD_REQUEST)
user.set_password(request.POST.get('new_password'))
user.save()
else:
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
return Response({'details': 'Success'}, status=status.HTTP_200_OK)
Upvotes: 1
Views: 1420
Reputation: 854
You can replaced by a new token after changing password successfully.
token, created = Token.objects.get_or_create(user=serializer.object['user'])
token.delete()
token.created = Token.objects.create(user=serializer.object['user'])
token.save()
Upvotes: 2