Fixed password was not hashed on REST API update

* When we updated a user password with a REST API call the password was
  stored in clear in plain text in the database.
This commit is contained in:
Vincent Simonin 2023-11-23 16:27:50 +01:00
parent d52a6d3b10
commit 220e90e32e
No known key found for this signature in database
GPG Key ID: 11611F3F005E89B9
2 changed files with 43 additions and 0 deletions

View File

@ -52,6 +52,18 @@ class UserSerializer(ValidatedModelSerializer):
return user
def update(self, instance, validated_data):
"""
Ensure proper updated password hash generation.
"""
password = validated_data.pop('password', None)
if password is not None:
instance.set_password(password)
instance.save()
return instance
@extend_schema_field(OpenApiTypes.STR)
def get_display(self, obj):
if full_name := obj.get_full_name():

View File

@ -55,6 +55,37 @@ class UserTest(APIViewTestCases.APIViewTestCase):
User.objects.bulk_create(users)
class ChangeUserPasswordTest(APITestCase):
user_permissions = ['auth.change_user']
def test_that_password_is_changed(self):
"""
Test that password is changed
"""
user_credentials = {
'username': 'user1',
'password': 'abc123',
}
user = User.objects.create_user(**user_credentials)
print(user.id)
data = {
'password': 'newpassword'
}
url = reverse('users-api:user-detail', kwargs={'pk': user.id})
response = self.client.patch(url, data, format='json', **self.header)
self.assertEqual(response.status_code, 200)
updated_user = User.objects.get(id=user.id)
self.assertTrue(updated_user.check_password(data['password']))
class GroupTest(APIViewTestCases.APIViewTestCase):
model = Group
view_namespace = 'users'