Commit f82d939d authored by ibuler's avatar ibuler

[Update] 使用资产树,去掉集群和资产组

parent 3bb6e089
# -*- coding: utf-8 -*-
#
from .asset import *
from .label import *
from .user import *
# -*- coding: utf-8 -*-
#
from django import forms
from django.utils.translation import gettext_lazy as _
from ..models import Asset
from common.utils import get_logger
logger = get_logger(__file__)
__all__ = ['AssetCreateForm', 'AssetUpdateForm', 'AssetBulkUpdateForm']
class AssetCreateForm(forms.ModelForm):
class Meta:
model = Asset
fields = [
'hostname', 'ip', 'public_ip', 'port', 'comment',
'nodes', 'is_active', 'admin_user', 'labels',
]
widgets = {
'nodes': forms.SelectMultiple(attrs={
'class': 'select2', 'data-placeholder': _('Nodes')
}),
'admin_user': forms.Select(attrs={
'class': 'select2', 'data-placeholder': _('Admin user')
}),
'labels': forms.SelectMultiple(attrs={
'class': 'select2', 'data-placeholder': _('Labels')
}),
'port': forms.TextInput(),
}
help_texts = {
'hostname': '* required',
'ip': '* required',
'port': '* required',
'admin_user': _('')
}
class AssetUpdateForm(forms.ModelForm):
class Meta:
model = Asset
fields = [
'hostname', 'ip', 'port', 'nodes', 'is_active',
'public_ip', 'number', 'comment', 'admin_user', 'labels',
]
widgets = {
'nodes': forms.SelectMultiple(attrs={
'class': 'select2', 'data-placeholder': _('Nodes')
}),
'admin_user': forms.Select(attrs={
'class': 'select2', 'data-placeholder': _('Admin user')
}),
'labels': forms.SelectMultiple(attrs={
'class': 'select2', 'data-placeholder': _('Labels')
}),
'port': forms.TextInput(),
}
help_texts = {
'hostname': '* required',
'ip': '* required',
'port': '* required',
'cluster': '* required',
'admin_user': _('')
}
class AssetBulkUpdateForm(forms.ModelForm):
assets = forms.ModelMultipleChoiceField(
required=True, help_text='* required',
label=_('Select assets'), queryset=Asset.objects.all(),
widget=forms.SelectMultiple(
attrs={
'class': 'select2',
'data-placeholder': _('Select assets')
}
)
)
port = forms.IntegerField(
label=_('Port'), required=False, min_value=1, max_value=65535,
)
class Meta:
model = Asset
fields = [
'assets', 'port', 'labels', 'admin_user'
]
widgets = {
'admin_user': forms.SelectMultiple(
attrs={'class': 'select2', 'data-placeholder': _('Admin user')}
),
'labels': forms.SelectMultiple(
attrs={'class': 'select2', 'data-placeholder': _('Labels')}
),
}
def save(self, commit=True):
changed_fields = []
for field in self._meta.fields:
if self.data.get(field) is not None:
changed_fields.append(field)
cleaned_data = {k: v for k, v in self.cleaned_data.items()
if k in changed_fields}
assets = cleaned_data.pop('assets')
labels = cleaned_data.pop('labels', [])
assets = Asset.objects.filter(id__in=[asset.id for asset in assets])
assets.update(**cleaned_data)
if labels:
for asset in assets:
asset.labels.set(labels)
return assets
# -*- coding: utf-8 -*-
#
from django import forms
from django.utils.translation import gettext_lazy as _
from ..models import Label, Asset
__all__ = ['LabelForm']
class LabelForm(forms.ModelForm):
assets = forms.ModelMultipleChoiceField(
queryset=Asset.objects.all(), label=_('Asset'), required=False,
widget=forms.SelectMultiple(
attrs={'class': 'select2', 'data-placeholder': _('Select assets')}
)
)
class Meta:
model = Label
fields = ['name', 'value', 'assets']
def __init__(self, *args, **kwargs):
if kwargs.get('instance', None):
initial = kwargs.get('initial', {})
initial['assets'] = kwargs['instance'].assets.all()
super().__init__(*args, **kwargs)
def save(self, commit=True):
label = super().save(commit=commit)
assets = self.cleaned_data['assets']
label.assets.set(assets)
return label
# coding:utf-8 # -*- coding: utf-8 -*-
#
from django import forms from django import forms
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
from .models import Cluster, Asset, AssetGroup, AdminUser, SystemUser, Label from ..models import AdminUser, SystemUser
from common.utils import validate_ssh_private_key, ssh_pubkey_gen, ssh_key_gen, get_logger from common.utils import validate_ssh_private_key, ssh_pubkey_gen, get_logger
logger = get_logger(__file__) logger = get_logger(__file__)
__all__ = [
'FileForm', 'SystemUserForm', 'AdminUserForm',
]
class AssetCreateForm(forms.ModelForm): class FileForm(forms.Form):
class Meta: file = forms.FileField()
model = Asset
fields = [
'hostname', 'ip', 'public_ip', 'port', 'comment', 'cluster',
'nodes', 'is_active', 'admin_user', 'labels',
]
widgets = {
'nodes': forms.SelectMultiple(attrs={
'class': 'select2', 'data-placeholder': _('Select nodes')
}),
'cluster': forms.Select(attrs={
'class': 'select2', 'data-placeholder': _('Select cluster')
}),
'admin_user': forms.Select(attrs={
'class': 'select2', 'data-placeholder': _('Select admin user')
}),
'labels': forms.SelectMultiple(attrs={
'class': 'select2', 'data-placeholder': _('Select labels')
}),
'port': forms.TextInput(),
}
help_texts = {
'hostname': '* required',
'ip': '* required',
'port': '* required',
'cluster': '* required',
'admin_user': _('Host level admin user, If not set using cluster admin user default')
}
def clean_admin_user(self):
cluster = self.cleaned_data.get('cluster')
admin_user = self.cleaned_data.get('admin_user')
if not admin_user and (cluster and not cluster.admin_user):
raise forms.ValidationError(_("You need set a admin user if cluster not have"))
return self.cleaned_data['admin_user']
def is_valid(self):
print(self.data)
result = super().is_valid()
if not result:
print(self.errors)
print(self.cleaned_data)
return result
class AssetUpdateForm(forms.ModelForm):
class Meta:
model = Asset
fields = [
'hostname', 'ip', 'port', 'nodes', "cluster", 'is_active',
'public_ip', 'number', 'comment', 'admin_user', 'labels',
]
widgets = {
'nodes': forms.SelectMultiple(attrs={
'class': 'select2', 'data-placeholder': _('Select nodes')
}),
'cluster': forms.Select(attrs={
'class': 'select2', 'data-placeholder': _('Select cluster')
}),
'admin_user': forms.Select(attrs={
'class': 'select2', 'data-placeholder': _('Select admin user')
}),
'labels': forms.SelectMultiple(attrs={
'class': 'select2', 'data-placeholder': _('Select labels')
}),
'port': forms.TextInput(),
}
help_texts = {
'hostname': '* required',
'ip': '* required',
'port': '* required',
'cluster': '* required',
'admin_user': _('Host level admin user, If not set using cluster admin user default')
}
def clean_admin_user(self):
cluster = self.cleaned_data.get('cluster')
admin_user = self.cleaned_data.get('admin_user')
if not admin_user and (cluster and not cluster.admin_user):
raise forms.ValidationError(_("You need set a admin user if cluster not have"))
return self.cleaned_data['admin_user']
class AssetBulkUpdateForm(forms.ModelForm):
assets = forms.ModelMultipleChoiceField(
required=True, help_text='* required',
label=_('Select assets'), queryset=Asset.objects.all(),
widget=forms.SelectMultiple(
attrs={
'class': 'select2',
'data-placeholder': _('Select assets')
}
)
)
port = forms.IntegerField(
label=_('Port'), required=False, min_value=1, max_value=65535,
)
cluster = forms.ModelChoiceField(
required=False, label=_("Cluster"), queryset=Cluster.objects.all(),
widget=forms.Select(
attrs={
'class': 'select2',
'data-placeholder': _('Select cluster')
}
)
)
class Meta:
model = Asset
fields = [
'assets', 'port', 'groups', "cluster", 'labels'
]
widgets = {
'groups': forms.SelectMultiple(
attrs={'class': 'select2', 'data-placeholder': _('Select asset groups')}
),
'labels': forms.SelectMultiple(
attrs={'class': 'select2', 'data-placeholder': _('Select labels')}
),
}
def save(self, commit=True):
changed_fields = []
for field in self._meta.fields:
if self.data.get(field) is not None:
changed_fields.append(field)
cleaned_data = {k: v for k, v in self.cleaned_data.items()
if k in changed_fields}
assets = cleaned_data.pop('assets')
groups = cleaned_data.pop('groups', [])
labels = cleaned_data.pop('labels', [])
assets = Asset.objects.filter(id__in=[asset.id for asset in assets])
assets.update(**cleaned_data)
if groups:
for asset in assets:
asset.groups.set(groups)
if labels:
for asset in assets:
asset.labels.set(labels)
return assets
class AssetGroupForm(forms.ModelForm):
# See AdminUserForm comment same it
assets = forms.ModelMultipleChoiceField(
queryset=Asset.objects.all(),
label=_('Asset'),
required=False,
widget=forms.SelectMultiple(
attrs={'class': 'select2', 'data-placeholder': _('Select assets')}
)
)
def __init__(self, **kwargs):
instance = kwargs.get('instance')
if instance:
initial = kwargs.get('initial', {})
initial.update({
'assets': instance.assets.all(),
})
kwargs['initial'] = initial
super().__init__(**kwargs)
def save(self, commit=True):
group = super().save(commit=commit)
assets = self.cleaned_data['assets']
group.assets.set(assets)
return group
class Meta:
model = AssetGroup
fields = [
"name", "comment",
]
help_texts = {
'name': '* required',
}
class ClusterForm(forms.ModelForm):
system_users = forms.ModelMultipleChoiceField(
queryset=SystemUser.objects.all(),
widget=forms.SelectMultiple(
attrs={'class': 'select2', 'data-placeholder': _('Select system users')}
),
label=_('System users'),
required=False,
help_text=_("Selected system users will be create at cluster assets"),
)
class Meta:
model = Cluster
fields = ['name', "bandwidth", "operator", 'contact', 'admin_user', 'system_users',
'phone', 'address', 'intranet', 'extranet', 'comment']
widgets = {
'name': forms.TextInput(attrs={'placeholder': _('Name')}),
'intranet': forms.Textarea(attrs={'placeholder': 'IP段之间用逗号隔开,如:192.168.1.0/24,192.168.1.0/24'}),
'extranet': forms.Textarea(attrs={'placeholder': 'IP段之间用逗号隔开,如:201.1.32.1/24,202.2.32.1/24'})
}
help_texts = {
'name': '* required',
'admin_user': _("Cluster level admin user"),
}
def __init__(self, *args, **kwargs):
if kwargs.get('instance', None):
initial = kwargs.get('initial', {})
initial['system_users'] = kwargs['instance'].systemuser_set.all()
super().__init__(*args, **kwargs)
def save(self, commit=True):
instance = super().save(commit=commit)
system_users = self.cleaned_data['system_users']
instance.systemuser_set.set(system_users)
return instance
class PasswordAndKeyAuthForm(forms.ModelForm): class PasswordAndKeyAuthForm(forms.ModelForm):
...@@ -344,33 +132,4 @@ class SystemUserForm(PasswordAndKeyAuthForm): ...@@ -344,33 +132,4 @@ class SystemUserForm(PasswordAndKeyAuthForm):
'cluster': _('If auto push checked, system user will be create at cluster assets'), 'cluster': _('If auto push checked, system user will be create at cluster assets'),
'auto_push': _('Auto push system user to asset'), 'auto_push': _('Auto push system user to asset'),
'priority': _('High level will be using login asset as default, if user was granted more than 2 system user'), 'priority': _('High level will be using login asset as default, if user was granted more than 2 system user'),
} }
\ No newline at end of file
class FileForm(forms.Form):
file = forms.FileField()
class LabelForm(forms.ModelForm):
assets = forms.ModelMultipleChoiceField(
queryset=Asset.objects.all(), label=_('Asset'), required=False,
widget=forms.SelectMultiple(
attrs={'class': 'select2', 'data-placeholder': _('Select assets')}
)
)
class Meta:
model = Label
fields = ['name', 'value', 'assets']
def __init__(self, *args, **kwargs):
if kwargs.get('instance', None):
initial = kwargs.get('initial', {})
initial['assets'] = kwargs['instance'].assets.all()
super().__init__(*args, **kwargs)
def save(self, commit=True):
label = super().save(commit=commit)
assets = self.cleaned_data['assets']
label.assets.set(assets)
return label
...@@ -28,19 +28,22 @@ def default_cluster(): ...@@ -28,19 +28,22 @@ def default_cluster():
return cluster.id return cluster.id
def default_node():
from .tree import Node
return Node.root()
class Asset(models.Model): class Asset(models.Model):
# Important # Important
id = models.UUIDField(default=uuid.uuid4, primary_key=True) id = models.UUIDField(default=uuid.uuid4, primary_key=True)
ip = models.GenericIPAddressField(max_length=32, verbose_name=_('IP'), db_index=True) ip = models.GenericIPAddressField(max_length=32, verbose_name=_('IP'), db_index=True)
hostname = models.CharField(max_length=128, unique=True, verbose_name=_('Hostname')) hostname = models.CharField(max_length=128, unique=True, verbose_name=_('Hostname'))
port = models.IntegerField(default=22, verbose_name=_('Port')) port = models.IntegerField(default=22, verbose_name=_('Port'))
groups = models.ManyToManyField(AssetGroup, blank=True, related_name='assets', verbose_name=_('Asset groups')) nodes = models.ManyToManyField('assets.Node', default=default_node, related_name='assets', verbose_name=_("Nodes"))
cluster = models.ForeignKey(Cluster, related_name='assets', default=default_cluster, on_delete=models.SET_DEFAULT, verbose_name=_('Cluster'))
nodes = models.ManyToManyField('assets.Node', blank=True, related_name='assets', verbose_name=_("Nodes"))
is_active = models.BooleanField(default=True, verbose_name=_('Is active')) is_active = models.BooleanField(default=True, verbose_name=_('Is active'))
# Auth # Auth
admin_user = models.ForeignKey('assets.AdminUser', null=True, blank=True, on_delete=models.SET_NULL, verbose_name=_("Admin user")) admin_user = models.ForeignKey('assets.AdminUser', on_delete=models.PROTECT, verbose_name=_("Admin user"))
# Some information # Some information
public_ip = models.GenericIPAddressField(max_length=32, blank=True, null=True, verbose_name=_('Public IP')) public_ip = models.GenericIPAddressField(max_length=32, blank=True, null=True, verbose_name=_('Public IP'))
......
...@@ -12,7 +12,6 @@ class AssetSerializer(BulkSerializerMixin, serializers.ModelSerializer): ...@@ -12,7 +12,6 @@ class AssetSerializer(BulkSerializerMixin, serializers.ModelSerializer):
""" """
资产的数据结构 资产的数据结构
""" """
cluster_name = serializers.SerializerMethodField()
class Meta: class Meta:
model = Asset model = Asset
...@@ -27,10 +26,6 @@ class AssetSerializer(BulkSerializerMixin, serializers.ModelSerializer): ...@@ -27,10 +26,6 @@ class AssetSerializer(BulkSerializerMixin, serializers.ModelSerializer):
]) ])
return fields return fields
@staticmethod
def get_cluster_name(obj):
return obj.cluster.name
class AssetGrantedSerializer(serializers.ModelSerializer): class AssetGrantedSerializer(serializers.ModelSerializer):
""" """
......
...@@ -34,8 +34,6 @@ class SystemUserSerializer(serializers.ModelSerializer): ...@@ -34,8 +34,6 @@ class SystemUserSerializer(serializers.ModelSerializer):
@staticmethod @staticmethod
def get_assets_amount(obj): def get_assets_amount(obj):
amount = 0 amount = 0
for cluster in obj.cluster.all():
amount += cluster.assets.all().count()
return amount return amount
......
...@@ -39,91 +39,78 @@ def on_asset_created(sender, instance=None, created=False, **kwargs): ...@@ -39,91 +39,78 @@ def on_asset_created(sender, instance=None, created=False, **kwargs):
logger.info("Asset `{}` create signal received".format(instance)) logger.info("Asset `{}` create signal received".format(instance))
update_asset_hardware_info_on_created(instance) update_asset_hardware_info_on_created(instance)
test_asset_conn_on_created(instance) test_asset_conn_on_created(instance)
push_cluster_system_users_to_asset(instance) # push_cluster_system_users_to_asset(instance)
@receiver(post_init, sender=Asset) # def push_to_cluster_assets_on_system_user_created_or_update(system_user):
def on_asset_init(sender, instance, created=False, **kwargs): # if not system_user.auto_push:
if instance and created is False: # return
instance.__original_cluster = instance.cluster # logger.debug("Push system user `{}` to cluster assets".format(system_user.name))
# for cluster in system_user.cluster.all():
# task_name = _("Push system user to cluster assets: {}->{}").format(
@receiver(post_save, sender=Asset) # cluster.name, system_user.name
def on_asset_cluster_changed(sender, instance=None, created=False, **kwargs): # )
if instance and created is False and instance.cluster != instance.__original_cluster: # assets = cluster.assets.all()
logger.info("Asset cluster changed signal received") # push_system_user_util.delay([system_user], assets, task_name)
push_cluster_system_users_to_asset(instance)
# @receiver(post_save, sender=SystemUser)
def push_to_cluster_assets_on_system_user_created_or_update(system_user): # def on_system_user_created_or_updated(sender, instance=None, **kwargs):
if not system_user.auto_push: # if instance and instance.auto_push:
return # logger.info("System user `{}` create or update signal received".format(instance))
logger.debug("Push system user `{}` to cluster assets".format(system_user.name)) # push_to_cluster_assets_on_system_user_created_or_update(instance)
for cluster in system_user.cluster.all(): #
task_name = _("Push system user to cluster assets: {}->{}").format( #
cluster.name, system_user.name # @receiver(post_init, sender=Cluster, dispatch_uid="my_unique_identifier")
) # def on_cluster_init(sender, instance, **kwargs):
assets = cluster.assets.all() # instance.__original_assets = tuple(instance.assets.values_list('pk', flat=True))
push_system_user_util.delay([system_user], assets, task_name) # instance.__origin_system_users = tuple(instance.systemuser_set.values_list('pk', flat=True))
#
#
@receiver(post_save, sender=SystemUser) # @receiver(post_save, sender=Cluster, dispatch_uid="my_unique_identifier")
def on_system_user_created_or_updated(sender, instance=None, **kwargs): # def on_cluster_assets_changed(sender, instance, **kwargs):
if instance and instance.auto_push: # assets_origin = instance.__original_assets
logger.info("System user `{}` create or update signal received".format(instance)) # assets_new = instance.assets.values_list('pk', flat=True)
push_to_cluster_assets_on_system_user_created_or_update(instance) # assets_added = set(assets_new) - set(assets_origin)
# if assets_added:
# logger.debug("Receive cluster change assets signal")
@receiver(post_init, sender=Cluster, dispatch_uid="my_unique_identifier") # logger.debug("Push cluster `{}` system users to: {}".format(
def on_cluster_init(sender, instance, **kwargs): # instance, ', '.join([str(asset) for asset in assets_added])
instance.__original_assets = tuple(instance.assets.values_list('pk', flat=True)) # ))
instance.__origin_system_users = tuple(instance.systemuser_set.values_list('pk', flat=True)) # assets = []
# for asset_id in assets_added:
# try:
@receiver(post_save, sender=Cluster, dispatch_uid="my_unique_identifier") # asset = Asset.objects.get(pk=asset_id)
def on_cluster_assets_changed(sender, instance, **kwargs): # except Asset.DoesNotExist:
assets_origin = instance.__original_assets # continue
assets_new = instance.assets.values_list('pk', flat=True) # else:
assets_added = set(assets_new) - set(assets_origin) # assets.append(asset)
if assets_added: # system_users = [s for s in instance.systemuser_set.all() if s.auto_push]
logger.debug("Receive cluster change assets signal") # task_name = _("Push system user to assets")
logger.debug("Push cluster `{}` system users to: {}".format( # push_system_user_util.delay(system_users, assets, task_name)
instance, ', '.join([str(asset) for asset in assets_added]) #
)) #
assets = [] # @receiver(post_save, sender=Cluster, dispatch_uid="my_unique_identifier2")
for asset_id in assets_added: # def on_cluster_system_user_changed(sender, instance, **kwargs):
try: # system_users_origin = instance.__origin_system_users
asset = Asset.objects.get(pk=asset_id) # system_user_new = instance.systemuser_set.values_list('pk', flat=True)
except Asset.DoesNotExist: # system_users_added = set(system_user_new) - set(system_users_origin)
continue # if system_users_added:
else: # logger.debug("Receive cluster change system users signal")
assets.append(asset) # system_users = []
system_users = [s for s in instance.systemuser_set.all() if s.auto_push] # for system_user_id in system_users_added:
task_name = _("Push system user to assets") # try:
push_system_user_util.delay(system_users, assets, task_name) # system_user = SystemUser.objects.get(pk=system_user_id)
# except SystemUser.DoesNotExist:
# continue
@receiver(post_save, sender=Cluster, dispatch_uid="my_unique_identifier2") # else:
def on_cluster_system_user_changed(sender, instance, **kwargs): # system_users.append(system_user)
system_users_origin = instance.__origin_system_users # logger.debug("Push new system users `{}` to cluster `{}` assets".format(
system_user_new = instance.systemuser_set.values_list('pk', flat=True) # ','.join([s.name for s in system_users]), instance
system_users_added = set(system_user_new) - set(system_users_origin) # ))
if system_users_added: # task_name = _(
logger.debug("Receive cluster change system users signal") # "Push system user to cluster assets: {}->{}").format(
system_users = [] # instance.name, ', '.join(s.name for s in system_users)
for system_user_id in system_users_added: # )
try:
system_user = SystemUser.objects.get(pk=system_user_id)
except SystemUser.DoesNotExist:
continue
else:
system_users.append(system_user)
logger.debug("Push new system users `{}` to cluster `{}` assets".format(
','.join([s.name for s in system_users]), instance
))
task_name = _(
"Push system user to cluster assets: {}->{}").format(
instance.name, ', '.join(s.name for s in system_users)
)
push_system_user_util.delay(system_users, instance.assets.all(), task_name) push_system_user_util.delay(system_users, instance.assets.all(), task_name)
...@@ -17,7 +17,6 @@ ...@@ -17,7 +17,6 @@
{% bootstrap_field form.hostname layout="horizontal" %} {% bootstrap_field form.hostname layout="horizontal" %}
{% bootstrap_field form.ip layout="horizontal" %} {% bootstrap_field form.ip layout="horizontal" %}
{% bootstrap_field form.port layout="horizontal" %} {% bootstrap_field form.port layout="horizontal" %}
{% bootstrap_field form.cluster layout="horizontal" %}
{% bootstrap_field form.public_ip layout="horizontal" %} {% bootstrap_field form.public_ip layout="horizontal" %}
<div class="hr-line-dashed"></div> <div class="hr-line-dashed"></div>
......
...@@ -22,7 +22,6 @@ ...@@ -22,7 +22,6 @@
{% bootstrap_field form.hostname layout="horizontal" %} {% bootstrap_field form.hostname layout="horizontal" %}
{% bootstrap_field form.ip layout="horizontal" %} {% bootstrap_field form.ip layout="horizontal" %}
{% bootstrap_field form.port layout="horizontal" %} {% bootstrap_field form.port layout="horizontal" %}
{% bootstrap_field form.cluster layout="horizontal" %}
{% bootstrap_field form.public_ip layout="horizontal" %} {% bootstrap_field form.public_ip layout="horizontal" %}
<div class="hr-line-dashed"></div> <div class="hr-line-dashed"></div>
......
...@@ -5,4 +5,4 @@ from .asset import * ...@@ -5,4 +5,4 @@ from .asset import *
from .system_user import * from .system_user import *
from .admin_user import * from .admin_user import *
from .label import * from .label import *
from .tree import * from .node import *
...@@ -41,7 +41,7 @@ logger = get_logger(__file__) ...@@ -41,7 +41,7 @@ logger = get_logger(__file__)
class AssetListView(AdminUserRequiredMixin, TemplateView): class AssetListView(AdminUserRequiredMixin, TemplateView):
template_name = 'assets/tree.html' template_name = 'assets/asset_list.html'
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = { context = {
......
...@@ -10,7 +10,7 @@ from users.permissions import IsValidUser, IsSuperUser, IsSuperUserOrAppUser ...@@ -10,7 +10,7 @@ from users.permissions import IsValidUser, IsSuperUser, IsSuperUserOrAppUser
from .utils import NodePermissionUtil from .utils import NodePermissionUtil
from .models import NodePermission from .models import NodePermission
from .hands import AssetGrantedSerializer, User, UserGroup, Asset, \ from .hands import AssetGrantedSerializer, User, UserGroup, Asset, \
NodeGrantedSerializer, SystemUser NodeGrantedSerializer, SystemUser, NodeSerializer
from . import serializers from . import serializers
...@@ -30,8 +30,10 @@ class AssetPermissionViewSet(viewsets.ModelViewSet): ...@@ -30,8 +30,10 @@ class AssetPermissionViewSet(viewsets.ModelViewSet):
def get_queryset(self): def get_queryset(self):
queryset = super().get_queryset() queryset = super().get_queryset()
node_id = self.request.query_params.get('node_id') node_id = self.request.query_params.get('node_id')
if node_id: if node_id:
queryset = queryset.filter(node__id=node_id) queryset = queryset.filter(node__id=node_id)
return queryset return queryset
...@@ -62,6 +64,20 @@ class UserGrantedAssetsApi(ListAPIView): ...@@ -62,6 +64,20 @@ class UserGrantedAssetsApi(ListAPIView):
return super().get_permissions() return super().get_permissions()
class UserGrantedNodesApi(ListAPIView):
permission_classes = (IsSuperUser,)
serializer_class = NodeSerializer
def get_queryset(self):
user_id = self.kwargs.get('pk', '')
if user_id:
user = get_object_or_404(User, id=user_id)
else:
user = self.request.user
nodes = NodePermissionUtil.get_user_nodes(user)
return nodes.keys()
class UserGrantedNodesWithAssetsApi(ListAPIView): class UserGrantedNodesWithAssetsApi(ListAPIView):
""" """
授权用户的资产组,注:这里的资产组并非是授权列表中授权的, 授权用户的资产组,注:这里的资产组并非是授权列表中授权的,
...@@ -134,7 +150,22 @@ class UserGroupGrantedAssetsApi(ListAPIView): ...@@ -134,7 +150,22 @@ class UserGroupGrantedAssetsApi(ListAPIView):
return queryset return queryset
class UserGroupGrantedNodeApi(ListAPIView): class UserGroupGrantedNodesApi(ListAPIView):
permission_classes = (IsSuperUser,)
serializer_class = NodeSerializer
def get_queryset(self):
group_id = self.kwargs.get('pk', '')
queryset = []
if group_id:
group = get_object_or_404(UserGroup, id=group_id)
nodes = NodePermissionUtil.get_user_group_nodes(group)
queryset = nodes.keys()
return queryset
class UserGroupGrantedNodesWithAssetsApi(ListAPIView):
permission_classes = (IsSuperUser,) permission_classes = (IsSuperUser,)
serializer_class = NodeGrantedSerializer serializer_class = NodeGrantedSerializer
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
from users.utils import AdminUserRequiredMixin from users.utils import AdminUserRequiredMixin
from users.models import User, UserGroup from users.models import User, UserGroup
from assets.models import Asset, AssetGroup, SystemUser, Node from assets.models import Asset, AssetGroup, SystemUser, Node
from assets.serializers import AssetGrantedSerializer, NodeGrantedSerializer from assets.serializers import AssetGrantedSerializer, NodeGrantedSerializer, NodeSerializer
...@@ -11,12 +11,17 @@ router.register('v1/asset-permissions', api.AssetPermissionViewSet, 'asset-permi ...@@ -11,12 +11,17 @@ router.register('v1/asset-permissions', api.AssetPermissionViewSet, 'asset-permi
urlpatterns = [ urlpatterns = [
# 查询某个用户授权的资产和资产组 # 查询某个用户授权的资产和资产组
url(r'^v1/user/(?P<pk>[0-9a-zA-Z\-]{36})?/?assets/$', api.UserGrantedAssetsApi.as_view(), name='user-assets'), url(r'^v1/user/(?P<pk>[0-9a-zA-Z\-]{36})/assets/$', api.UserGrantedAssetsApi.as_view(), name='user-assets'),
url(r'^v1/user/(?P<pk>[0-9a-zA-Z\-]{36})?/?nodes/$', api.UserGrantedNodesWithAssetsApi.as_view(), name='user-nodes'), url(r'^v1/user/assets/$', api.UserGrantedAssetsApi.as_view(), name='my-assets'),
url(r'^v1/user/(?P<pk>[0-9a-zA-Z\-]{36})/nodes/$', api.UserGrantedNodesApi.as_view(), name='user-nodes'),
url(r'^v1/user/nodes/$', api.UserGrantedNodesApi.as_view(), name='my-nodes'),
url(r'^v1/user/(?P<pk>[0-9a-zA-Z\-]{36})/nodes-assets/$', api.UserGrantedNodesWithAssetsApi.as_view(), name='user-nodes-assets'),
url(r'^v1/user/nodes-assets/$', api.UserGrantedNodesWithAssetsApi.as_view(), name='my-nodes-assets'),
# 查询某个用户组授权的资产和资产组 # 查询某个用户组授权的资产和资产组
url(r'^v1/user-group/(?P<pk>[0-9a-zA-Z\-]{36})/assets/$', api.UserGroupGrantedAssetsApi.as_view(), name='user-group-assets'), url(r'^v1/user-group/(?P<pk>[0-9a-zA-Z\-]{36})/assets/$', api.UserGroupGrantedAssetsApi.as_view(), name='user-group-assets'),
url(r'^v1/user-group/(?P<pk>[0-9a-zA-Z\-]{36})/nodes/$', api.UserGroupGrantedNodeApi.as_view(), name='user-group-asset-groups'), url(r'^v1/user-group/(?P<pk>[0-9a-zA-Z\-]{36})/nodes/$', api.UserGroupGrantedNodesApi.as_view(), name='user-group-nodes'),
url(r'^v1/user-group/(?P<pk>[0-9a-zA-Z\-]{36})/nodes-assets/$', api.UserGroupGrantedNodesWithAssetsApi.as_view(), name='user-group-nodes-assets'),
# 验证用户是否有某个资产和系统用户的权限 # 验证用户是否有某个资产和系统用户的权限
url(r'v1/asset-permission/user/validate/$', api.ValidateUserAssetPermissionView.as_view(), name='validate-user-asset-permission'), url(r'v1/asset-permission/user/validate/$', api.ValidateUserAssetPermissionView.as_view(), name='validate-user-asset-permission'),
......
...@@ -3,15 +3,12 @@ ...@@ -3,15 +3,12 @@
from __future__ import unicode_literals, absolute_import from __future__ import unicode_literals, absolute_import
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
from django.conf import settings
from django.views.generic import ListView, CreateView, UpdateView from django.views.generic import ListView, CreateView, UpdateView
from django.views.generic.edit import DeleteView from django.views.generic.edit import DeleteView
from django.urls import reverse_lazy from django.urls import reverse_lazy
from django.views.generic.detail import DetailView, SingleObjectMixin
from common.utils import get_object_or_none from common.utils import get_object_or_none
from .hands import AdminUserRequiredMixin, User, UserGroup, SystemUser, \ from .hands import AdminUserRequiredMixin, Node
Asset, AssetGroup, Node
from .models import AssetPermission, NodePermission from .models import AssetPermission, NodePermission
from .forms import AssetPermissionForm from .forms import AssetPermissionForm
...@@ -74,85 +71,9 @@ class AssetPermissionUpdateView(AdminUserRequiredMixin, UpdateView): ...@@ -74,85 +71,9 @@ class AssetPermissionUpdateView(AdminUserRequiredMixin, UpdateView):
return super().get_context_data(**kwargs) return super().get_context_data(**kwargs)
# class AssetPermissionDetailView(AdminUserRequiredMixin, DetailView):
# template_name = 'perms/asset_permission_detail.html'
# context_object_name = 'asset_permission'
# model = AssetPermission
#
# def get_context_data(self, **kwargs):
# context = {
# 'app': _('Perms'),
# 'action': _('Asset permission detail'),
# 'system_users_remain': [
# system_user for system_user in SystemUser.objects.all()
# if system_user not in self.object.system_users.all()],
# 'system_users': self.object.system_users.all(),
# }
# kwargs.update(context)
# return super().get_context_data(**kwargs)
class AssetPermissionDeleteView(AdminUserRequiredMixin, DeleteView): class AssetPermissionDeleteView(AdminUserRequiredMixin, DeleteView):
model = AssetPermission model = AssetPermission
template_name = 'delete_confirm.html' template_name = 'delete_confirm.html'
success_url = reverse_lazy('perms:asset-permission-list') success_url = reverse_lazy('perms:asset-permission-list')
# class AssetPermissionUserView(AdminUserRequiredMixin,
# SingleObjectMixin,
# ListView):
# template_name = 'perms/asset_permission_user.html'
# context_object_name = 'asset_permission'
# paginate_by = settings.DISPLAY_PER_PAGE
# object = None
#
# def get(self, request, *args, **kwargs):
# self.object = self.get_object(queryset=AssetPermission.objects.all())
# return super().get(request, *args, **kwargs)
#
# def get_queryset(self):
# queryset = self.object.get_granted_users()
# return queryset
#
# def get_context_data(self, **kwargs):
# users_granted = self.get_queryset()
# groups_granted = self.object.user_groups.all()
# context = {
# 'app': _('Perms'),
# 'action': _('Asset permission user list'),
# 'users_remain': User.objects.exclude(id__in=[user.id for user in users_granted]),
# 'user_groups': self.object.user_groups.all(),
# 'user_groups_remain': UserGroup.objects.exclude(id__in=[group.id for group in groups_granted])
# }
# kwargs.update(context)
# return super().get_context_data(**kwargs)
# class AssetPermissionAssetView(AdminUserRequiredMixin,
# SingleObjectMixin,
# ListView):
# template_name = 'perms/asset_permission_asset.html'
# context_object_name = 'asset_permission'
# paginate_by = settings.DISPLAY_PER_PAGE
# object = None
#
# def get(self, request, *args, **kwargs):
# self.object = self.get_object(queryset=AssetPermission.objects.all())
# return super().get(request, *args, **kwargs)
#
# def get_queryset(self):
# queryset = self.object.get_granted_assets()
# return queryset
#
# def get_context_data(self, **kwargs):
# assets_granted = self.get_queryset()
# groups_granted = self.object.asset_groups.all()
# context = {
# 'app': _('Perms'),
# 'action': _('Asset permission asset list'),
# 'assets_remain': Asset.objects.exclude(id__in=[asset.id for asset in assets_granted]),
# 'asset_groups': self.object.asset_groups.all(),
# 'asset_groups_remain': AssetGroup.objects.exclude(id__in=[group.id for group in groups_granted])
# }
# kwargs.update(context)
# return super().get_context_data(**kwargs)
...@@ -21,9 +21,9 @@ ...@@ -21,9 +21,9 @@
<li class="active"> <li class="active">
<a href="{% url 'users:user-group-detail' pk=user_group.id %}" class="text-center"><i class="fa fa-laptop"></i> {% trans 'User group detail' %} </a> <a href="{% url 'users:user-group-detail' pk=user_group.id %}" class="text-center"><i class="fa fa-laptop"></i> {% trans 'User group detail' %} </a>
</li> </li>
{# <li>#} <li>
{# <a href="{% url 'users:user-group-granted-asset' pk=user_group.id %}" class="text-center"><i class="fa fa-cubes"></i> {% trans 'Asset granted' %}</a>#} <a href="{% url 'users:user-group-granted-asset' pk=user_group.id %}" class="text-center"><i class="fa fa-cubes"></i> {% trans 'Asset granted' %}</a>
{# </li>#} </li>
<li class="pull-right"> <li class="pull-right">
<a class="btn btn-outline btn-default" href="{% url 'users:user-group-update' pk=user_group.id %}"><i class="fa fa-edit"></i>{% trans 'Update' %}</a> <a class="btn btn-outline btn-default" href="{% url 'users:user-group-update' pk=user_group.id %}"><i class="fa fa-edit"></i>{% trans 'Update' %}</a>
</li> </li>
......
...@@ -88,10 +88,7 @@ class UserGroupGrantedAssetView(AdminUserRequiredMixin, DetailView): ...@@ -88,10 +88,7 @@ class UserGroupGrantedAssetView(AdminUserRequiredMixin, DetailView):
model = UserGroup model = UserGroup
template_name = 'users/user_group_granted_asset.html' template_name = 'users/user_group_granted_asset.html'
context_object_name = 'user_group' context_object_name = 'user_group'
object = None
def get(self, request, *args, **kwargs):
self.object = self.get_object(queryset=self.model.objects.all())
return super().get(request, *args, **kwargs)
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = { context = {
......
...@@ -295,10 +295,6 @@ class UserGrantedAssetView(AdminUserRequiredMixin, DetailView): ...@@ -295,10 +295,6 @@ class UserGrantedAssetView(AdminUserRequiredMixin, DetailView):
template_name = 'users/user_granted_asset.html' template_name = 'users/user_granted_asset.html'
object = None object = None
def get(self, request, *args, **kwargs):
self.object = self.get_object(queryset=User.objects.all())
return super().get(request, *args, **kwargs)
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = { context = {
'app': _('Users'), 'app': _('Users'),
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment