perf: update pam

pull/14387/head
ibuler 2024-10-29 11:23:25 +08:00
parent 4db4a6dce7
commit 114a6bf87c
10 changed files with 57 additions and 44 deletions

View File

@ -42,7 +42,6 @@ class CheckAccountExecutionViewSet(AutomationExecutionViewSet):
class AccountRiskViewSet(OrgBulkModelViewSet):
model = AccountRisk
search_fields = ('username',)
filterset_class = AccountRiskFilterSet
serializer_classes = {
'default': serializers.AccountRiskSerializer,
}

View File

@ -48,12 +48,21 @@ class GatheredAccountViewSet(OrgBulkModelViewSet):
filterset_class = GatheredAccountFilterSet
serializer_classes = {
'default': serializers.GatheredAccountSerializer,
'status': serializers.GatheredAccountActionSerializer,
}
rbac_perms = {
'sync_accounts': 'assets.add_gatheredaccount',
'discover': 'assets.add_gatheredaccount',
'status': 'assets.change_gatheredaccount',
}
@action(methods=['put'], detail=True, url_path='status')
def status(self, request, *args, **kwargs):
instance = self.get_object()
instance.status = request.data.get('status')
instance.save()
return Response(status=status.HTTP_200_OK)
@action(methods=['get'], detail=False, url_path='discover')
def discover(self, request, *args, **kwargs):
asset_id = request.query_params.get('asset_id')

View File

@ -90,7 +90,6 @@ class GatherAccountsManager(AccountBasePlaybookManager):
continue
GatheredAccount.sync_accounts(gathered_accounts)
def run(self, *args, **kwargs):
super().run(*args, **kwargs)
users, change_info = self.generate_send_users_and_change_info()

View File

@ -168,7 +168,7 @@ class Migration(migrations.Migration):
('id', models.UUIDField(default=uuid.uuid4, primary_key=True, serialize=False)),
('org_id',
models.CharField(blank=True, db_index=True, default='', max_length=36, verbose_name='Organization')),
('present', models.BooleanField(default=True, verbose_name='Present')),
('present', models.BooleanField(default=True, verbose_name='Remote present')),
('date_last_login', models.DateTimeField(null=True, verbose_name='Date login')),
('username', models.CharField(blank=True, db_index=True, max_length=32, verbose_name='Username')),
('address_last_login', models.CharField(default='', max_length=39, verbose_name='Address login')),

View File

@ -28,14 +28,10 @@ class Migration(migrations.Migration):
model_name="gatheredaccount",
name="action",
field=models.CharField(
choices=[
("pending", "Pending"),
("confirm", "Confirm"),
("ignore", "Ignore"),
],
default="pending",
choices=[("confirmed", "Confirmed"), ("ignored", "Ignored")],
default="",
max_length=32,
verbose_name="Action",
verbose_name="Status",
),
),
]

View File

@ -1,28 +0,0 @@
# Generated by Django 4.1.13 on 2024-10-28 08:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("accounts", "0010_alter_accountrisk_options_and_more"),
]
operations = [
migrations.RemoveField(
model_name="gatheredaccount",
name="action",
),
migrations.AddField(
model_name="gatheredaccount",
name="status",
field=models.CharField(
blank=True,
choices=[("confirmed", "Confirmed"), ("ignored", "Ignored")],
default="",
max_length=32,
verbose_name="Action",
),
),
]

View File

@ -13,12 +13,12 @@ __all__ = ['GatherAccountsAutomation', 'GatheredAccount']
class GatheredAccount(JMSOrgBaseModel):
present = models.BooleanField(default=True, verbose_name=_("Present")) # 资产上是否还存在
present = models.BooleanField(default=True, verbose_name=_("Remote present")) # 资产上是否还存在
date_last_login = models.DateTimeField(null=True, verbose_name=_("Date login"))
asset = models.ForeignKey('assets.Asset', on_delete=models.CASCADE, verbose_name=_("Asset"))
username = models.CharField(max_length=32, blank=True, db_index=True, verbose_name=_('Username'))
address_last_login = models.CharField(max_length=39, default='', verbose_name=_("Address login"))
status = models.CharField(max_length=32, default='', blank=True, choices=ConfirmOrIgnore.choices, verbose_name=_("Action"))
status = models.CharField(max_length=32, default='', blank=True, choices=ConfirmOrIgnore.choices, verbose_name=_("Status"))
@property
def address(self):
@ -66,7 +66,7 @@ class GatheredAccount(JMSOrgBaseModel):
cls.create_accounts(gathered_account, accounts)
gathered_account.status = ConfirmOrIgnore.confirmed
gathered_account.save(update_fields=['action'])
gathered_account.save(update_fields=['status'])
class Meta:
verbose_name = _("Gather asset accounts")

View File

@ -5,6 +5,11 @@ from orgs.mixins.serializers import BulkOrgResourceModelSerializer
from .account import AccountAssetSerializer as _AccountAssetSerializer
from .base import BaseAccountSerializer
__all__ = [
'GatheredAccountSerializer',
'GatheredAccountActionSerializer',
]
class AccountAssetSerializer(_AccountAssetSerializer):
class Meta(_AccountAssetSerializer.Meta):
@ -21,9 +26,15 @@ class GatheredAccountSerializer(BulkOrgResourceModelSerializer):
'date_updated', 'address_last_login',
'date_last_login', 'status'
]
read_only_fields = fields
@classmethod
def setup_eager_loading(cls, queryset):
""" Perform necessary eager loading of data. """
queryset = queryset.prefetch_related('asset', 'asset__platform')
return queryset
class GatheredAccountActionSerializer(GatheredAccountSerializer):
class Meta(GatheredAccountSerializer.Meta):
read_only_fields = list(set(GatheredAccountSerializer.Meta.read_only_fields) - {'status'})

View File

@ -1,18 +1,26 @@
# -*- coding: utf-8 -*-
#
from accounts.const import AutomationTypes
from accounts.models import AccountCheckAutomation
from common.utils import get_logger
from rest_framework.serializers import ModelSerializer
from accounts.const import AutomationTypes
from accounts.models import AccountCheckAutomation, AccountRisk
from common.utils import get_logger
from .base import BaseAutomationSerializer
logger = get_logger(__file__)
__all__ = [
'CheckAccountsAutomationSerializer',
'AccountRiskSerializer'
]
class AccountRiskSerializer(ModelSerializer):
class Meta:
model = AccountRisk
fields = '__all__'
class CheckAccountsAutomationSerializer(BaseAutomationSerializer):
class Meta:
model = AccountCheckAutomation

View File

@ -37,6 +37,25 @@ def local_monday():
return zero_hour_time - timedelta(zero_hour_time.weekday())
def is_date_difference_than(d1, d2, threshold='1d'):
if d1 is None or d2 is None:
return False
kwargs = {}
if 'd' in threshold:
kwargs['days'] = int(threshold[:-1])
elif 'h' in threshold:
kwargs['hours'] = int(threshold[:-1])
elif 'm' in threshold:
kwargs['minutes'] = int(threshold[:-1])
else:
raise ValueError('Invalid threshold format')
delta = dj_timezone.timedelta(**kwargs)
return abs((time1 - time2).days) > threshold_in_days
_rest_dt_field = DateTimeField()
dt_parser = _rest_dt_field.to_internal_value
dt_formatter = _rest_dt_field.to_representation