2018-03-27 10:34:41 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
#
|
2022-01-27 07:06:15 +00:00
|
|
|
from django.utils.translation import ugettext_lazy as _
|
2018-03-27 10:34:41 +00:00
|
|
|
from rest_framework import serializers
|
2019-07-17 04:10:14 +00:00
|
|
|
|
2022-05-07 08:20:12 +00:00
|
|
|
from common.drf.fields import EncryptedField
|
2022-11-08 09:54:51 +00:00
|
|
|
from assets.const import SecretType
|
|
|
|
from .utils import validate_password_for_ansible, validate_ssh_key
|
2018-03-27 10:34:41 +00:00
|
|
|
|
|
|
|
|
2022-09-06 11:57:03 +00:00
|
|
|
class AuthValidateMixin(serializers.Serializer):
|
2022-11-08 09:54:51 +00:00
|
|
|
secret_type = serializers.CharField(label=_('Secret type'), max_length=16, required=True)
|
|
|
|
secret = EncryptedField(
|
|
|
|
label=_('Secret'), required=False, max_length=16384, allow_blank=True,
|
|
|
|
allow_null=True, write_only=True,
|
2022-05-16 09:28:02 +00:00
|
|
|
)
|
2021-12-30 02:47:46 +00:00
|
|
|
passphrase = serializers.CharField(
|
|
|
|
allow_blank=True, allow_null=True, required=False, max_length=512,
|
|
|
|
write_only=True, label=_('Key password')
|
|
|
|
)
|
|
|
|
|
2022-11-08 09:54:51 +00:00
|
|
|
@property
|
|
|
|
def initial_secret_type(self):
|
|
|
|
secret_type = self.initial_data.get('secret_type')
|
|
|
|
return secret_type
|
2021-12-30 02:47:46 +00:00
|
|
|
|
2022-11-08 09:54:51 +00:00
|
|
|
def validate_secret(self, secret):
|
|
|
|
if not secret:
|
|
|
|
return
|
|
|
|
secret_type = self.initial_secret_type
|
|
|
|
if secret_type == SecretType.PASSWORD:
|
|
|
|
validate_password_for_ansible(secret)
|
|
|
|
return secret
|
|
|
|
elif secret_type == SecretType.SSH_KEY:
|
|
|
|
passphrase = self.initial_data.get('passphrase')
|
|
|
|
passphrase = passphrase if passphrase else None
|
|
|
|
return validate_ssh_key(secret, passphrase)
|
|
|
|
else:
|
|
|
|
return secret
|
2019-07-08 07:35:20 +00:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def clean_auth_fields(validated_data):
|
2022-11-08 09:54:51 +00:00
|
|
|
for field in ('secret',):
|
2019-07-08 07:35:20 +00:00
|
|
|
value = validated_data.get(field)
|
|
|
|
if not value:
|
|
|
|
validated_data.pop(field, None)
|
2021-12-30 02:47:46 +00:00
|
|
|
validated_data.pop('passphrase', None)
|
2019-08-01 09:10:02 +00:00
|
|
|
|
2019-07-08 07:35:20 +00:00
|
|
|
def create(self, validated_data):
|
|
|
|
self.clean_auth_fields(validated_data)
|
|
|
|
return super().create(validated_data)
|
|
|
|
|
|
|
|
def update(self, instance, validated_data):
|
|
|
|
self.clean_auth_fields(validated_data)
|
|
|
|
return super().update(instance, validated_data)
|