You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

57 lines
1.7 KiB

  1. import json
  2. from api import models
  3. from rest_framework import serializers
  4. from django.utils.translation import ugettext_lazy as _
  5. class JsonSettingsField(serializers.Field):
  6. default_error_messages = {
  7. 'invalid': _('Value must be valid JSON.')
  8. }
  9. def to_representation(self, value):
  10. return json.loads(value)
  11. def to_internal_value(self, data):
  12. try:
  13. return json.dumps(data)
  14. except (TypeError, ValueError):
  15. self.fail('invalid')
  16. class PasswordInfoSerializer(serializers.ModelSerializer):
  17. settings = JsonSettingsField()
  18. class Meta:
  19. model = models.PasswordInfo
  20. fields = ('counter', 'settings', 'length')
  21. class EntrySerializer(serializers.ModelSerializer):
  22. password = PasswordInfoSerializer()
  23. class Meta:
  24. model = models.Entry
  25. fields = ('id', 'site', 'password', 'title', 'username', 'email', 'description', 'url', 'created', 'modified')
  26. read_only_fields = ('created', 'modified')
  27. def create(self, validated_data):
  28. password_data = validated_data.pop('password')
  29. user = self.context['request'].user
  30. password_info = models.PasswordInfo.objects.create(**password_data)
  31. return models.Entry.objects.create(user=user, password=password_info, **validated_data)
  32. def update(self, instance, validated_data):
  33. password_data = validated_data.pop('password')
  34. passwordInfo = instance.password
  35. for attr, value in password_data.items():
  36. setattr(passwordInfo, attr, value)
  37. passwordInfo.save()
  38. for attr, value in validated_data.items():
  39. setattr(instance, attr, value)
  40. instance.save()
  41. return instance