Browse Source

feat(api): improve authenticated action validation errors

Peter Thomassen 5 years ago
parent
commit
8663d49302
3 changed files with 11 additions and 5 deletions
  1. 4 1
      api/desecapi/serializers.py
  2. 3 3
      api/desecapi/tests/test_user_management.py
  3. 4 1
      api/desecapi/views.py

+ 4 - 1
api/desecapi/serializers.py

@@ -688,7 +688,10 @@ class AuthenticatedActionSerializer(serializers.ModelSerializer):
         except KeyError:
             raise serializers.ValidationError({'code': ['This field is required.']})
         except ValueError:
-            raise serializers.ValidationError({'code': ['Invalid code.']})
+            validity = settings.VALIDITY_PERIOD_VERIFICATION_SIGNATURE
+            raise serializers.ValidationError({
+                'code': [f'This code is invalid, most likely because it expired (validity: {validity}).']
+            })
 
         # add extra fields added by the user
         unpacked_data.update(**data)

+ 3 - 3
api/desecapi/tests/test_user_management.py

@@ -372,14 +372,14 @@ class UserManagementTestCase(DesecTestCase, PublicSuffixMockMixin):
     def assertVerificationFailureInvalidCodeResponse(self, response):
         return self.assertContains(
             response=response,
-            text="Invalid code.",
-            status_code=status.HTTP_400_BAD_REQUEST
+            text="This action cannot be carried out because another operation has been performed",
+            status_code=status.HTTP_409_CONFLICT
         )
 
     def assertVerificationFailureExpiredCodeResponse(self, response):
         return self.assertContains(
             response=response,
-            text="Invalid code.",
+            text="This code is invalid, most likely because it expired (validity: ",
             status_code=status.HTTP_400_BAD_REQUEST
         )
 

+ 4 - 1
api/desecapi/views.py

@@ -612,7 +612,10 @@ class AuthenticatedActionView(generics.GenericAPIView):
         try:
             self.action = serializer.Meta.model(**serializer.validated_data)
         except ValueError:  # this happens when state cannot be verified
-            raise ValidationError('Invalid code.')
+            ex = ValidationError('This action cannot be carried out because another operation has been performed, '
+                                 'invalidating this one. (Are you trying to perform this action twice?)')
+            ex.status_code = status.HTTP_409_CONFLICT
+            raise ex
 
         self.action.act()
         return self.finalize()