账号模版

pull/8873/head
feng626 2022-08-24 16:36:42 +08:00
parent dca1388a67
commit 76390d013e
8 changed files with 126 additions and 52 deletions

View File

@ -8,7 +8,5 @@ from .domain import *
from .gathered_user import * from .gathered_user import *
from .favorite_asset import * from .favorite_asset import *
from .account import * from .account import *
from .account_history import *
from .account_template import *
from .backup import * from .backup import *
from .platform import * from .platform import *

View File

@ -0,0 +1,3 @@
from .account import *
from .account_history import *
from .account_template import *

View File

@ -1,45 +1,35 @@
from rest_framework import serializers
from django.utils.translation import ugettext_lazy as _
from django.db.models import F from django.db.models import F
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from assets.models import Account
from orgs.mixins.serializers import BulkOrgResourceModelSerializer from orgs.mixins.serializers import BulkOrgResourceModelSerializer
from .base import AuthSerializerMixin
from common.drf.serializers import SecretReadableMixin from common.drf.serializers import SecretReadableMixin
from assets.models import Account
from assets.serializers.base import AuthSerializerMixin
from .account_template import AccountTemplateSerializerMixin
from .common import BaseAccountSerializer
class AccountSerializer(AuthSerializerMixin, BulkOrgResourceModelSerializer): class AccountSerializer(
AccountTemplateSerializerMixin, AuthSerializerMixin, BulkOrgResourceModelSerializer
):
ip = serializers.ReadOnlyField(label=_("IP")) ip = serializers.ReadOnlyField(label=_("IP"))
asset_name = serializers.ReadOnlyField(label=_("Asset")) asset_name = serializers.ReadOnlyField(label=_("Asset"))
platform = serializers.ReadOnlyField(label=_("Platform")) platform = serializers.ReadOnlyField(label=_("Platform"))
class Meta: class Meta(BaseAccountSerializer.Meta):
model = Account model = Account
fields_mini = [ fields = BaseAccountSerializer.Meta.fields + ['account_template', ]
'id', 'privileged', 'username', 'ip', 'asset_name',
'platform', 'version'
]
fields_write_only = ['password', 'private_key', 'public_key', 'passphrase']
fields_other = ['date_created', 'date_updated', 'connectivity', 'date_verified', 'comment']
fields_small = fields_mini + fields_write_only + fields_other
fields_fk = ['asset']
fields = fields_small + fields_fk
extra_kwargs = {
'username': {'required': True},
'private_key': {'write_only': True},
'public_key': {'write_only': True},
}
ref_name = 'AssetAccountSerializer'
def validate(self, attrs): def validate(self, attrs):
attrs = self._validate_gen_key(attrs) attrs = self._validate_gen_key(attrs)
attrs = super()._validate(attrs)
return attrs return attrs
@classmethod @classmethod
def setup_eager_loading(cls, queryset): def setup_eager_loading(cls, queryset):
""" Perform necessary eager loading of data. """ """ Perform necessary eager loading of data. """
queryset = queryset.prefetch_related('asset')\ queryset = queryset.prefetch_related('asset') \
.annotate(ip=F('asset__ip')) \ .annotate(ip=F('asset__ip')) \
.annotate(asset_name=F('asset__name')) .annotate(asset_name=F('asset__name'))
return queryset return queryset

View File

@ -1,6 +1,7 @@
from assets.models import Account from assets.models import Account
from common.drf.serializers import SecretReadableMixin from common.drf.serializers import SecretReadableMixin
from .common import BaseAccountSerializer
from .account import AccountSerializer, AccountSecretSerializer from .account import AccountSerializer, AccountSecretSerializer
@ -8,9 +9,9 @@ class AccountHistorySerializer(AccountSerializer):
class Meta: class Meta:
model = Account.history.model model = Account.history.model
fields = AccountSerializer.Meta.fields_mini + \ fields = BaseAccountSerializer.Meta.fields_mini + \
AccountSerializer.Meta.fields_write_only + \ BaseAccountSerializer.Meta.fields_write_only + \
AccountSerializer.Meta.fields_fk + \ BaseAccountSerializer.Meta.fields_fk + \
['history_id', 'date_created', 'date_updated'] ['history_id', 'date_created', 'date_updated']
read_only_fields = fields read_only_fields = fields
ref_name = 'AccountHistorySerializer' ref_name = 'AccountHistorySerializer'

View File

@ -0,0 +1,74 @@
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from assets.models import AccountTemplate
from orgs.mixins.serializers import BulkOrgResourceModelSerializer
from assets.serializers.base import AuthSerializerMixin
from .common import BaseAccountSerializer
class AccountTemplateSerializer(AuthSerializerMixin, BulkOrgResourceModelSerializer):
class Meta:
model = AccountTemplate
fields_mini = ['id', 'privileged', 'username', 'name']
fields_write_only = BaseAccountSerializer.Meta.fields_write_only
fields_other = BaseAccountSerializer.Meta.fields_other
fields = fields_mini + fields_write_only + fields_other
extra_kwargs = {
'username': {'required': True},
'private_key': {'write_only': True},
'public_key': {'write_only': True},
}
def validate(self, attrs):
attrs = self._validate_gen_key(attrs)
return attrs
@classmethod
def validate_required(cls, attrs):
required_field_dict = {}
error = _('This field is required.')
for k, v in cls().fields.items():
if v.required and k not in attrs:
required_field_dict[k] = error
print(required_field_dict)
if not required_field_dict:
return
raise serializers.ValidationError(required_field_dict)
class AccountTemplateSerializerMixin(serializers.ModelSerializer):
account_template = serializers.UUIDField(
required=False, allow_null=True, write_only=True,
label=_('Account template')
)
@staticmethod
def validate_account_template(value):
AccountTemplate.objects.get_or_create()
model = AccountTemplate
try:
return model.objects.get(id=value)
except AccountTemplate.DoesNotExist:
raise serializers.ValidationError(_('Account template not found'))
@staticmethod
def replace_attrs(account_template: AccountTemplate, attrs: dict):
exclude_fields = [
'_state', 'org_id', 'date_verified', 'id', 'date_created', 'date_updated', 'created_by'
]
template_attrs = {k: v for k, v in account_template.__dict__.items() if k not in exclude_fields}
for k, v in template_attrs.items():
attrs.setdefault(k, v)
def _validate(self, attrs):
account_template = attrs.pop('account_template', None)
if account_template:
self.replace_attrs(account_template, attrs)
else:
AccountTemplateSerializer.validate_required(attrs)
return attrs

View File

@ -0,0 +1,26 @@
# -*- coding: utf-8 -*-
#
from rest_framework import serializers
__all__ = [
'BaseAccountSerializer',
]
class BaseAccountSerializer(serializers.ModelSerializer):
class Meta:
fields_mini = [
'id', 'privileged', 'username', 'ip', 'asset_name',
'platform', 'version'
]
fields_write_only = ['password', 'private_key', 'public_key', 'passphrase']
fields_other = ['date_created', 'date_updated', 'connectivity', 'date_verified', 'comment']
fields_small = fields_mini + fields_write_only + fields_other
fields_fk = ['asset']
fields = fields_small + fields_fk
ref_name = 'AssetAccountSerializer'
extra_kwargs = {
'username': {'required': True},
'private_key': {'write_only': True},
'public_key': {'write_only': True},
}

View File

@ -1,22 +0,0 @@
from assets.models import AccountTemplate
from orgs.mixins.serializers import BulkOrgResourceModelSerializer
from .base import AuthSerializerMixin
from .account import AccountSerializer
class AccountTemplateSerializer(AuthSerializerMixin, BulkOrgResourceModelSerializer):
class Meta:
model = AccountTemplate
fields_mini = ['id', 'privileged', 'username', 'name']
fields_write_only = AccountSerializer.Meta.fields_write_only
fields_other = AccountSerializer.Meta.fields_other
fields = fields_mini + fields_write_only + fields_other
extra_kwargs = AccountSerializer.Meta.extra_kwargs
def validate(self, attrs):
print(attrs)
raise ValueError('test')
attrs = self._validate_gen_key(attrs)
return attrs

View File

@ -2,6 +2,7 @@
# #
from rest_framework import serializers from rest_framework import serializers
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from django.db.transaction import atomic
from django.db.models import F from django.db.models import F
from common.drf.serializers import JMSWritableNestedModelSerializer from common.drf.serializers import JMSWritableNestedModelSerializer
@ -72,6 +73,7 @@ class AssetSerializer(JMSWritableNestedModelSerializer):
""" """
资产的数据结构 资产的数据结构
""" """
class Meta: class Meta:
model = Asset model = Asset
fields_mini = [ fields_mini = [
@ -108,8 +110,8 @@ class AssetSerializer(JMSWritableNestedModelSerializer):
@classmethod @classmethod
def setup_eager_loading(cls, queryset): def setup_eager_loading(cls, queryset):
""" Perform necessary eager loading of data. """ """ Perform necessary eager loading of data. """
queryset = queryset.prefetch_related('domain', 'platform', 'protocols')\ queryset = queryset.prefetch_related('domain', 'platform', 'protocols') \
.annotate(category=F("platform__category"))\ .annotate(category=F("platform__category")) \
.annotate(type=F("platform__type")) .annotate(type=F("platform__type"))
queryset = queryset.prefetch_related('nodes', 'labels') queryset = queryset.prefetch_related('nodes', 'labels')
return queryset return queryset
@ -138,6 +140,7 @@ class AssetSerializer(JMSWritableNestedModelSerializer):
raise serializers.ValidationError({'accounts': e}) raise serializers.ValidationError({'accounts': e})
serializer.save() serializer.save()
@atomic
def create(self, validated_data): def create(self, validated_data):
nodes_display = validated_data.pop('nodes_display', '') nodes_display = validated_data.pop('nodes_display', '')
instance = super().create(validated_data) instance = super().create(validated_data)
@ -146,6 +149,7 @@ class AssetSerializer(JMSWritableNestedModelSerializer):
self.perform_nodes_display_create(instance, nodes_display) self.perform_nodes_display_create(instance, nodes_display)
return instance return instance
@atomic
def update(self, instance, validated_data): def update(self, instance, validated_data):
nodes_display = validated_data.pop('nodes_display', '') nodes_display = validated_data.pop('nodes_display', '')
instance = super().update(instance, validated_data) instance = super().update(instance, validated_data)