Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Always derive the key of a typed category

Roland Geider4635e5ee5dc7
diff --git a/wger/measurements/api/serializers.py b/wger/measurements/api/serializers.py
index 9c2c913c2..32cfa28a8 100644
--- a/wger/measurements/api/serializers.py
+++ b/wger/measurements/api/serializers.py
@@ -264,9 +264,11 @@ class CategorySerializer(serializers.ModelSerializer):
metric_type = validated_data.get('metric_type', MetricType.CUSTOM)
user_id = validated_data.get('user_id') or getattr(validated_data.get('user'), 'pk', None)
- # A client that creates the category offline derives the same key, so
- # only fill it in when the payload brought none of its own
- if 'id' not in validated_data and Category.has_deterministic_id(metric_type) and user_id:
+ # The key of a typed category is not a free parameter, it follows from
+ # owner and type, so a key the payload brought is overwritten rather
+ # than trusted: our own clients derive the same value, and one that
+ # does not would create a category no other device can address
+ if Category.has_deterministic_id(metric_type) and user_id:
validated_data['id'] = Category.deterministic_id(user_id, metric_type)
category = super().create(validated_data)
diff --git a/wger/measurements/tests/test_categories.py b/wger/measurements/tests/test_categories.py
index 3815fcef6..7eddd91ee 100644
--- a/wger/measurements/tests/test_categories.py
+++ b/wger/measurements/tests/test_categories.py
@@ -213,6 +213,34 @@ class TypedCategoryTestCase(WgerTestCase):
str(Category.deterministic_id(self.user.pk, MetricType.STEPS)),
)
+ def test_derived_id_overrides_the_one_sent(self):
+ """
+ Test that a key the payload brings is replaced by the derived one
+ """
+ response = self.create_category(
+ metric_type=MetricType.STEPS,
+ id='cccccccc-cccc-cccc-cccc-0000000000ff',
+ )
+
+ self.assertEqual(response.status_code, 201)
+ self.assertEqual(
+ response.data['id'],
+ str(Category.deterministic_id(self.user.pk, MetricType.STEPS)),
+ )
+
+ def test_custom_category_keeps_the_id_sent(self):
+ """
+ Test that a free-form category is created under the key it was given
+ """
+ response = self.create_category(
+ name='Biceps',
+ unit='cm',
+ id='cccccccc-cccc-cccc-cccc-0000000000ff',
+ )
+
+ self.assertEqual(response.status_code, 201)
+ self.assertEqual(response.data['id'], 'cccccccc-cccc-cccc-cccc-0000000000ff')
+
def test_official_category_keeps_random_id(self):
"""
Test that the server-managed body weight category is not derived