2
0
mirror of https://github.com/inventree/InvenTree.git synced 2026-04-14 23:38:53 +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:
Matthias Mair
2026-04-08 00:13:39 +02:00
committed by GitHub
parent 68031d504f
commit 9c0cb34106
2 changed files with 38 additions and 1 deletions

View File

@@ -238,8 +238,21 @@ class ApiTokenSerializer(InvenTreeModelSerializer):
def validate(self, data): def validate(self, data):
"""Validate the data for the serializer.""" """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: 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) return super().validate(data)
user_detail = UserSerializer(source='user', read_only=True) user_detail = UserSerializer(source='user', read_only=True)

View File

@@ -259,6 +259,8 @@ class SuperuserAPITests(InvenTreeAPITestCase):
class UserTokenTests(InvenTreeAPITestCase): class UserTokenTests(InvenTreeAPITestCase):
"""Tests for user token functionality.""" """Tests for user token functionality."""
fixtures = ['users']
def test_token_generation(self): def test_token_generation(self):
"""Test user token generation.""" """Test user token generation."""
url = reverse('api-token') url = reverse('api-token')
@@ -397,6 +399,28 @@ class UserTokenTests(InvenTreeAPITestCase):
self.client.logout() self.client.logout()
self.get(reverse('api-token'), expected_code=401) 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): class GroupDetialTests(InvenTreeAPITestCase):
"""Tests for the GroupDetail API endpoint.""" """Tests for the GroupDetail API endpoint."""