Skip to content

Commit 3a3d439

Browse files
authored
Fixed password was not hashed on REST API update (#14340)
* 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. * Following code review * Move test on UserTest class * Call `super().update()` in overriding `update` method * Return directly the result of `super().update()`
1 parent c43c63a commit 3a3d439

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

netbox/users/api/serializers.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,16 @@ def create(self, validated_data):
5252

5353
return user
5454

55+
def update(self, instance, validated_data):
56+
"""
57+
Ensure proper updated password hash generation.
58+
"""
59+
password = validated_data.pop('password', None)
60+
if password is not None:
61+
instance.set_password(password)
62+
63+
return super().update(instance, validated_data)
64+
5565
@extend_schema_field(OpenApiTypes.STR)
5666
def get_display(self, obj):
5767
if full_name := obj.get_full_name():

netbox/users/tests/test_api.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,38 @@ def setUpTestData(cls):
5454
)
5555
User.objects.bulk_create(users)
5656

57+
def test_that_password_is_changed(self):
58+
"""
59+
Test that password is changed
60+
"""
61+
62+
obj_perm = ObjectPermission(
63+
name='Test permission',
64+
actions=['change']
65+
)
66+
obj_perm.save()
67+
obj_perm.users.add(self.user)
68+
obj_perm.object_types.add(ContentType.objects.get_for_model(self.model))
69+
70+
user_credentials = {
71+
'username': 'user1',
72+
'password': 'abc123',
73+
}
74+
user = User.objects.create_user(**user_credentials)
75+
76+
data = {
77+
'password': 'newpassword'
78+
}
79+
url = reverse('users-api:user-detail', kwargs={'pk': user.id})
80+
81+
response = self.client.patch(url, data, format='json', **self.header)
82+
83+
self.assertEqual(response.status_code, 200)
84+
85+
updated_user = User.objects.get(id=user.id)
86+
87+
self.assertTrue(updated_user.check_password(data['password']))
88+
5789

5890
class GroupTest(APIViewTestCases.APIViewTestCase):
5991
model = Group

0 commit comments

Comments
 (0)