1
0
mirror of https://github.com/netbox-community/netbox.git synced 2024-05-10 07:54:54 +00:00

55 lines
1.7 KiB
Python
Raw Normal View History

2016-03-01 11:23:03 -05:00
from rest_framework import serializers
2017-03-17 16:01:57 -04:00
from rest_framework.validators import UniqueTogetherValidator
from taggit_serializer.serializers import TaggitSerializer, TagListSerializerField
2016-03-01 11:23:03 -05:00
from dcim.api.nested_serializers import NestedDeviceSerializer
from extras.api.customfields import CustomFieldModelSerializer
2016-03-01 11:23:03 -05:00
from secrets.models import Secret, SecretRole
from utilities.api import ValidatedModelSerializer
from .nested_serializers import *
2016-03-01 11:23:03 -05:00
#
# Secrets
2016-03-01 11:23:03 -05:00
#
class SecretRoleSerializer(ValidatedModelSerializer):
2016-03-01 11:23:03 -05:00
class Meta:
model = SecretRole
fields = ['id', 'name', 'slug']
class SecretSerializer(TaggitSerializer, CustomFieldModelSerializer):
device = NestedDeviceSerializer()
role = NestedSecretRoleSerializer()
plaintext = serializers.CharField()
tags = TagListSerializerField(required=False)
class Meta:
model = Secret
fields = [
'id', 'device', 'role', 'name', 'plaintext', 'hash', 'tags', 'custom_fields', 'created', 'last_updated',
]
2017-03-17 16:01:57 -04:00
validators = []
def validate(self, data):
2018-01-02 17:07:21 -05:00
# Encrypt plaintext data using the master key provided from the view context
if data.get('plaintext'):
s = Secret(plaintext=data['plaintext'])
s.encrypt(self.context['master_key'])
data['ciphertext'] = s.ciphertext
data['hash'] = s.hash
2017-03-17 16:01:57 -04:00
# Validate uniqueness of name if one has been provided.
2018-01-02 17:07:21 -05:00
if data.get('name'):
2017-03-17 16:01:57 -04:00
validator = UniqueTogetherValidator(queryset=Secret.objects.all(), fields=('device', 'role', 'name'))
validator.set_context(self)
validator(data)
# Enforce model validation
super().validate(data)
2017-03-17 16:01:57 -04:00
return data