Pass user instance through to filterable child serializers (#13349) (#13351)

This commit is contained in:
Oliver authored and GitHub committed 2026-11-24 17:17:25 +11:00
1 parent 4683838b1d
commit 5bc9e140f9
2 files changed
+60 -1

No files matched your search

+12 -1
View File
@@ -1675,7 +1675,18 @@ class InvenTreeBarcodeMixin(models.Model):
match = resolve(api_url)
view_class = match.func.view_class
serializer_class = view_class.serializer_class
serializer = serializer_class(self)
kwargs = {}
# Pass the requesting user through, so that field-level permission
# checks (e.g. role-gated or nested OptionalFields) are applied
from InvenTree.serializers import FilterableSerializerMixin
if issubclass(serializer_class, FilterableSerializerMixin):
kwargs[serializer_class.PERMISSION_USER_KWARG] = user
serializer = serializer_class(self, **kwargs)
data['instance'] = serializer.data
except Exception:
pass
@@ -117,6 +117,54 @@ class BarcodeAPITest(InvenTreeAPITestCase):
for k in ['barcode_data', 'stockitem', 'success']:
self.assertIn(k, response)
def test_field_permissions(self):
"""Field-level permissions are applied to the serialized barcode instance.
A user must not be able to read role-gated or nested fields via a barcode
scan which they cannot read via the standard API endpoints.
"""
item = StockItem.objects.first()
part = item.part
# Without the 'pricing' role, pricing fields are hidden
self.assertFalse(self.user.has_perm('pricing.view_partpricing'))
part_url = reverse('api-part-detail', kwargs={'pk': part.pk})
data = self.get(part_url, expected_code=200).data
self.assertNotIn('pricing_min', data)
data = self.postBarcode(self.scan_url, part.format_barcode(), 200).data
instance = data['part']['instance']
self.assertEqual(instance['pk'], part.pk)
for key in ['pricing_min', 'pricing_max', 'pricing_updated']:
self.assertNotIn(key, instance)
# With the 'pricing' role, pricing fields are returned
self.assignRole('pricing.view')
data = self.postBarcode(self.scan_url, part.format_barcode(), 200).data
instance = data['part']['instance']
for key in ['pricing_min', 'pricing_max', 'pricing_updated']:
self.assertIn(key, instance)
# Without the 'part' role, nested part data is hidden for a stock item
self.clearRoles()
self.assignRole('stock.view')
self.assignRole('stock_location.view')
self.get(part_url, expected_code=403)
stock_url = reverse('api-stock-detail', kwargs={'pk': item.pk})
data = self.get(stock_url, {'part_detail': True}, expected_code=200).data
self.assertIsNone(data.get('part_detail'))
data = self.postBarcode(self.scan_url, item.format_barcode(), 200).data
instance = data['stockitem']['instance']
self.assertEqual(instance['pk'], item.pk)
self.assertIsNone(instance.get('part_detail'))
def test_invalid_item(self):
"""Test response for invalid stock item."""
response = self.post(