mirror of
https://github.com/inventree/InvenTree.git
synced 2026-04-14 15:28:52 +00:00
Merge commit from fork
* fix behaviour * style fixes --------- Co-authored-by: Oliver Walters <oliver.henry.walters@gmail.com>
This commit is contained in:
@@ -238,8 +238,21 @@ class ApiTokenSerializer(InvenTreeModelSerializer):
|
||||
|
||||
def validate(self, data):
|
||||
"""Validate the data for the serializer."""
|
||||
request_user = self.context['request'].user
|
||||
if not request_user:
|
||||
raise serializers.ValidationError(
|
||||
_('User must be authenticated')
|
||||
) # pragma: no cover
|
||||
|
||||
if 'user' not in data:
|
||||
data['user'] = self.context['request'].user
|
||||
data['user'] = request_user
|
||||
|
||||
# Only superusers can create tokens for other users
|
||||
if data['user'] != request_user and not request_user.is_superuser:
|
||||
raise serializers.ValidationError(
|
||||
_('Only a superuser can create a token for another user')
|
||||
)
|
||||
|
||||
return super().validate(data)
|
||||
|
||||
user_detail = UserSerializer(source='user', read_only=True)
|
||||
|
||||
@@ -259,6 +259,8 @@ class SuperuserAPITests(InvenTreeAPITestCase):
|
||||
class UserTokenTests(InvenTreeAPITestCase):
|
||||
"""Tests for user token functionality."""
|
||||
|
||||
fixtures = ['users']
|
||||
|
||||
def test_token_generation(self):
|
||||
"""Test user token generation."""
|
||||
url = reverse('api-token')
|
||||
@@ -397,6 +399,28 @@ class UserTokenTests(InvenTreeAPITestCase):
|
||||
self.client.logout()
|
||||
self.get(reverse('api-token'), expected_code=401)
|
||||
|
||||
def test_token_security(self):
|
||||
"""Test that token generation is only available to users with the correct permissions."""
|
||||
url = reverse('api-token-list')
|
||||
|
||||
# Try to generate a token for a different user (should fail)
|
||||
response = self.post(url, data={'name': 'test', 'user': 1}, expected_code=400)
|
||||
self.assertIn(
|
||||
'Only a superuser can create a token for another user', str(response.data)
|
||||
)
|
||||
|
||||
# there should be no tokens created
|
||||
self.assertEqual(ApiToken.objects.count(), 0)
|
||||
|
||||
# now with superuser permissions
|
||||
self.user.is_superuser = True
|
||||
self.user.save()
|
||||
|
||||
response = self.post(url, data={'name': 'test', 'user': 1}, expected_code=201)
|
||||
self.assertIn('token', response.data)
|
||||
|
||||
self.assertEqual(ApiToken.objects.count(), 1)
|
||||
|
||||
|
||||
class GroupDetialTests(InvenTreeAPITestCase):
|
||||
"""Tests for the GroupDetail API endpoint."""
|
||||
|
||||
Reference in New Issue
Block a user