Commit 653c328e authored by ibuler's avatar ibuler

[Abandon] ...

parent 2bc5e882
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# #
import uuid
from django.db import models from django.db import models
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
...@@ -9,34 +10,35 @@ __all__ = ['Node'] ...@@ -9,34 +10,35 @@ __all__ = ['Node']
class Node(models.Model): class Node(models.Model):
id = models.CharField(primary_key=True, max_length=64) # '1:1:1:1' id = models.UUIDField(default=uuid.uuid4, primary_key=True)
name = models.CharField(max_length=128, unique=True, verbose_name=_("Name")) key = models.CharField(unique=True, max_length=64, verbose_name=_("Key")) # '1:1:1:1'
value = models.CharField(max_length=128, unique=True, verbose_name=_("Value"))
child_mark = models.IntegerField(default=0) child_mark = models.IntegerField(default=0)
date_create = models.DateTimeField(auto_now_add=True) date_create = models.DateTimeField(auto_now_add=True)
def __str__(self): def __str__(self):
return self.name return self.value
@property @property
def level(self): def level(self):
return len(self.id.split(':')) return len(self.key.split(':'))
def get_next_child_id(self): def get_next_child_key(self):
mark = self.child_mark mark = self.child_mark
self.child_mark += 1 self.child_mark += 1
self.save() self.save()
return "{}:{}".format(self.id, mark) return "{}:{}".format(self.key, mark)
def create_child(self, name): def create_child(self, value):
child_id = self.get_next_child_id() child_key = self.get_next_child_key()
child = self.__class__.objects.create(id=child_id, name=name) child = self.__class__.objects.create(key=child_key, value=value)
return child return child
def get_children(self): def get_children(self):
return self.__class__.objects.filter(id__regex=r'{}:[0-9]+$'.format(self.id)) return self.__class__.objects.filter(key__regex=r'{}:[0-9]+$'.format(self.key))
def get_all_children(self): def get_all_children(self):
return self.__class__.objects.filter(id__startswith='{}:'.format(self.id)) return self.__class__.objects.filter(key__startswith='{}:'.format(self.key))
def get_assets(self): def get_assets(self):
from .asset import Asset from .asset import Asset
...@@ -53,6 +55,6 @@ class Node(models.Model): ...@@ -53,6 +55,6 @@ class Node(models.Model):
@classmethod @classmethod
def root(cls): def root(cls):
obj, created = cls.objects.get_or_create( obj, created = cls.objects.get_or_create(
id='0', defaults={"id": '0', 'name': "ROOT"} key='0', defaults={"key": '0', 'value': "ROOT"}
) )
return obj return obj
...@@ -323,19 +323,19 @@ class NodeSerializer(serializers.ModelSerializer): ...@@ -323,19 +323,19 @@ class NodeSerializer(serializers.ModelSerializer):
class Meta: class Meta:
model = Node model = Node
fields = ['id', 'name', 'parent'] fields = ['id', 'key', 'value', 'parent']
list_serializer_class = BulkListSerializer list_serializer_class = BulkListSerializer
@staticmethod @staticmethod
def get_parent(obj): def get_parent(obj):
if obj.id == "0": if obj.key == "0":
return "#" return "#"
if not obj.id.startswith("0"): if not obj.key.startswith("0"):
return "0" return "0"
return ":".join(obj.id.split(":")[:-1]) return ":".join(obj.key.split(":")[:-1])
def get_fields(self): def get_fields(self):
fields = super().get_fields() fields = super().get_fields()
field = fields["id"] field = fields["key"]
field.required = False field.required = False
return fields return fields
...@@ -38,7 +38,8 @@ function initTable() { ...@@ -38,7 +38,8 @@ function initTable() {
var update_btn = '<a href="{% url "assets:label-update" pk=DEFAULT_PK %}" class="btn btn-xs btn-info">{% trans "Update" %}</a>'.replace('{{ DEFAULT_PK }}', cellData); var update_btn = '<a href="{% url "assets:label-update" pk=DEFAULT_PK %}" class="btn btn-xs btn-info">{% trans "Update" %}</a>'.replace('{{ DEFAULT_PK }}', cellData);
var del_btn = '<a class="btn btn-xs btn-danger m-l-xs btn-delete" data-uid="{{ DEFAULT_PK }}">{% trans "Delete" %}</a>'.replace('{{ DEFAULT_PK }}', cellData); var del_btn = '<a class="btn btn-xs btn-danger m-l-xs btn-delete" data-uid="{{ DEFAULT_PK }}">{% trans "Delete" %}</a>'.replace('{{ DEFAULT_PK }}', cellData);
$(td).html(update_btn + del_btn) $(td).html(update_btn + del_btn)
}}], }}
],
ajax_url: '{% url "api-assets:label-list" %}?sort=name', ajax_url: '{% url "api-assets:label-list" %}?sort=name',
columns: [ columns: [
{data: "id"}, {data: "name" }, {data: "value" }, {data: "id"}, {data: "name" }, {data: "value" },
......
...@@ -229,7 +229,7 @@ ...@@ -229,7 +229,7 @@
if (!parentNode){ if (!parentNode){
return return
} }
var url = "{% url 'api-assets:node-children' pk='0:0' %}".replace("0:0", parentNode.id ); var url = "{% url 'api-assets:node-children' pk=DEFAULT_PK %}".replace("{{ DEFAULT_PK }}", parentNode.id );
$.post(url, {}, function (data, status){ $.post(url, {}, function (data, status){
if (status === "success") { if (status === "success") {
var newNode = { name:data["name"], id:data["id"], pId: parentNode.id }; var newNode = { name:data["name"], id:data["id"], pId: parentNode.id };
...@@ -263,9 +263,8 @@ ...@@ -263,9 +263,8 @@
} }
function onRenameNode(event, treeId, treeNode, isCancel){ function onRenameNode(event, treeId, treeNode, isCancel){
console.log(treeNode); var url = "{% url 'api-assets:node-detail' pk=DEFAULT_PK %}".replace("{{ DEFAULT_PK }}", treeNode.id);
var url = "{% url 'api-assets:node-detail' pk='0:0' %}".replace("0:0", treeNode.id); var data = {"value": treeNode.name};
var data = {"name": treeNode.name};
if (isCancel){ if (isCancel){
return return
} }
...@@ -282,8 +281,6 @@ ...@@ -282,8 +281,6 @@
if (!current_node){ if (!current_node){
return return
} }
console.log("Edit tree");
console.log(current_node);
zTree.editName(current_node); zTree.editName(current_node);
} }
...@@ -310,9 +307,10 @@ ...@@ -310,9 +307,10 @@
$.get("{% url 'api-assets:node-list' %}", function(data, status){ $.get("{% url 'api-assets:node-list' %}", function(data, status){
$.each(data, function (index, value) { $.each(data, function (index, value) {
value["pId"] = value["parent"]; value["pId"] = value["parent"];
if (value["id"] === "0") { if (value["key"] === "0") {
value["open"] = true; value["open"] = true;
} }
value["name"] = value["value"]
}); });
zNodes = data; zNodes = data;
$.fn.zTree.init($("#assetTree"), setting, zNodes); $.fn.zTree.init($("#assetTree"), setting, zNodes);
......
...@@ -43,7 +43,7 @@ urlpatterns = [ ...@@ -43,7 +43,7 @@ urlpatterns = [
api.SystemUserPushApi.as_view(), name='system-user-push'), api.SystemUserPushApi.as_view(), name='system-user-push'),
url(r'^v1/system-user/(?P<pk>[0-9a-zA-Z\-]{36})/connective/$', url(r'^v1/system-user/(?P<pk>[0-9a-zA-Z\-]{36})/connective/$',
api.SystemUserTestConnectiveApi.as_view(), name='system-user-connective'), api.SystemUserTestConnectiveApi.as_view(), name='system-user-connective'),
url(r'^v1/nodes/(?P<pk>[0-9:]+)/children/$', api.NodeChildrenApi.as_view(), name='node-children'), url(r'^v1/nodes/(?P<pk>[0-9a-zA-Z\-]{36})/children/$', api.NodeChildrenApi.as_view(), name='node-children'),
] ]
urlpatterns += router.urls urlpatterns += router.urls
......
...@@ -6,6 +6,7 @@ from django import forms ...@@ -6,6 +6,7 @@ from django import forms
from django.utils import six from django.utils import six
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
from rest_framework import serializers
class DictField(forms.Field): class DictField(forms.Field):
...@@ -36,3 +37,9 @@ class DictField(forms.Field): ...@@ -36,3 +37,9 @@ class DictField(forms.Field):
# Sometimes data or initial may be a string equivalent of a boolean # Sometimes data or initial may be a string equivalent of a boolean
# so we should run it through to_python first to get a boolean value # so we should run it through to_python first to get a boolean value
return self.to_python(initial) != self.to_python(data) return self.to_python(initial) != self.to_python(data)
class StringIDField(serializers.Field):
def to_representation(self, value):
return {"pk": value.pk, "name": value.__str__()}
...@@ -11,7 +11,7 @@ from users.permissions import IsValidUser, IsSuperUser, IsAppUser, IsSuperUserOr ...@@ -11,7 +11,7 @@ from users.permissions import IsValidUser, IsSuperUser, IsAppUser, IsSuperUserOr
from .utils import get_user_granted_assets, get_user_granted_asset_groups, \ from .utils import get_user_granted_assets, get_user_granted_asset_groups, \
get_user_asset_permissions, get_user_group_asset_permissions, \ get_user_asset_permissions, get_user_group_asset_permissions, \
get_user_group_granted_assets, get_user_group_granted_asset_groups get_user_group_granted_assets, get_user_group_granted_asset_groups
from .models import AssetPermission from .models import AssetPermission, NodePermission
from .hands import AssetGrantedSerializer, User, UserGroup, AssetGroup, Asset, \ from .hands import AssetGrantedSerializer, User, UserGroup, AssetGroup, Asset, \
AssetGroup, AssetGroupGrantedSerializer, SystemUser, MyAssetGroupGrantedSerializer AssetGroup, AssetGroupGrantedSerializer, SystemUser, MyAssetGroupGrantedSerializer
from . import serializers from . import serializers
...@@ -21,28 +21,33 @@ class AssetPermissionViewSet(viewsets.ModelViewSet): ...@@ -21,28 +21,33 @@ class AssetPermissionViewSet(viewsets.ModelViewSet):
""" """
资产授权列表的增删改查api 资产授权列表的增删改查api
""" """
queryset = AssetPermission.objects.all() queryset = NodePermission.objects.all()
serializer_class = serializers.AssetPermissionSerializer serializer_class = serializers.AssetPermissionCreateUpdateSerializer
permission_classes = (IsSuperUser,) permission_classes = (IsSuperUser,)
def get_queryset(self):
queryset = super(AssetPermissionViewSet, self).get_queryset()
user_id = self.request.query_params.get('user', '')
user_group_id = self.request.query_params.get('user_group', '')
if user_id and user_id.isdigit():
user = get_object_or_404(User, id=int(user_id))
queryset = get_user_asset_permissions(user)
if user_group_id:
user_group = get_object_or_404(UserGroup, id=user_group_id)
queryset = get_user_group_asset_permissions(user_group)
return queryset
def get_serializer_class(self): def get_serializer_class(self):
if getattr(self, 'user_id', ''): if self.action in ("list", 'retrieve'):
return serializers.UserAssetPermissionSerializer return serializers.AssetPermissionListSerializer
return serializers.AssetPermissionSerializer return self.serializer_class
# def get_queryset(self):
# queryset = super(AssetPermissionViewSet, self).get_queryset()
# user_id = self.request.query_params.get('user', '')
# user_group_id = self.request.query_params.get('user_group', '')
#
# if user_id and user_id.isdigit():
# user = get_object_or_404(User, id=int(user_id))
# queryset = get_user_asset_permissions(user)
#
# if user_group_id:
# user_group = get_object_or_404(UserGroup, id=user_group_id)
# queryset = get_user_group_asset_permissions(user_group)
# return queryset
# def get_serializer_class(self):
# if getattr(self, 'user_id', ''):
# return serializers.UserAssetPermissionCreateUpdateSerializer
# return serializers.AssetPermissionCreateUpdateSerializer
class AssetPermissionRemoveUserApi(RetrieveUpdateAPIView): class AssetPermissionRemoveUserApi(RetrieveUpdateAPIView):
......
...@@ -4,94 +4,28 @@ from __future__ import absolute_import, unicode_literals ...@@ -4,94 +4,28 @@ from __future__ import absolute_import, unicode_literals
from django import forms from django import forms
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
# from .hands import User, UserGroup, Asset, AssetGroup, SystemUser from .models import NodePermission
from .models import AssetPermission
from users.models import User
class AssetPermissionForm(forms.ModelForm): class AssetPermissionForm(forms.ModelForm):
users = forms.ModelMultipleChoiceField(
queryset=User.objects.exclude(role=User.ROLE_APP),
widget=forms.SelectMultiple(
attrs={'class': 'select2', 'data-placeholder': _('Select users')},
),
label=_("User"),
required=False,
)
class Meta: class Meta:
model = AssetPermission model = NodePermission
fields = [ fields = [
'name', 'users', 'user_groups', 'assets', 'asset_groups', 'node', 'user_group', 'system_user', 'is_active',
'system_users', 'is_active', 'date_expired', 'comment', 'date_expired', 'comment'
] ]
widgets = { widgets = {
'user_groups': forms.SelectMultiple( 'node': forms.Select(
attrs={'class': 'select2', attrs={'class': 'select2', 'data-placeholder': _("Node")}
'data-placeholder': _('Select user groups')}), ),
'assets': forms.SelectMultiple( 'user_group': forms.Select(
attrs={'class': 'select2', attrs={'class': 'select2', 'data-placeholder': _("User group")}
'data-placeholder': _('Select assets')}), ),
'asset_groups': forms.SelectMultiple( 'system_user': forms.Select(
attrs={'class': 'select2', attrs={'class': 'select2', 'data-placeholder': _('System user')}
'data-placeholder': _('Select asset groups')}), ),
'system_users': forms.SelectMultiple(
attrs={'class': 'select2',
'data-placeholder': _('Select system users')}),
} }
help_texts = {
'name': '* required',
'system_users': '* required',
}
def clean_user_groups(self):
users = self.cleaned_data.get('users')
user_groups = self.cleaned_data.get('user_groups')
if not users and not user_groups:
raise forms.ValidationError(_("User or group at least one required"))
return self.cleaned_data["user_groups"]
def clean_asset_groups(self):
assets = self.cleaned_data.get('assets')
asset_groups = self.cleaned_data.get('asset_groups')
if not assets and not asset_groups:
raise forms.ValidationError(_("Asset or group at least one required"))
return self.cleaned_data["asset_groups"]
def clean_system_users(self):
from assets.utils import check_assets_have_system_user
errors = []
assets = self.cleaned_data['assets']
asset_groups = self.cleaned_data.get('asset_groups')
system_users = self.cleaned_data.get('system_users')
if not asset_groups and not assets:
return self.cleaned_data.get("system_users")
error_data = check_assets_have_system_user(assets, system_users)
if error_data:
for asset, system_users in error_data.items():
msg = _("Asset {} of cluster {} not have [{}] system users, please check \n")
error = forms.ValidationError(msg.format(
asset.hostname,
asset.cluster.name,
", ".join(system_user.name for system_user in system_users)
))
errors.append(error)
for group in asset_groups: def clean_system_user(self):
msg = _("Asset {}(group {}) of cluster {} not have [{}] system users, please check \n") return self.cleaned_data['system_user']
assets = group.assets.all()
error_data = check_assets_have_system_user(assets, system_users)
for asset, system_users in error_data.items():
errors.append(msg.format(
asset.hostname, group.name, asset.cluster.name,
", ".join(system_user.name for system_user in system_users)
))
if errors:
raise forms.ValidationError(errors)
return self.cleaned_data['system_users']
...@@ -70,6 +70,7 @@ class AssetPermission(models.Model): ...@@ -70,6 +70,7 @@ class AssetPermission(models.Model):
class NodePermission(models.Model): class NodePermission(models.Model):
id = models.UUIDField(default=uuid.uuid4, primary_key=True)
node = models.ForeignKey('assets.Node', on_delete=models.CASCADE, verbose_name=_("Node")) node = models.ForeignKey('assets.Node', on_delete=models.CASCADE, verbose_name=_("Node"))
user_group = models.ForeignKey('users.UserGroup', on_delete=models.CASCADE, verbose_name=_("User group")) user_group = models.ForeignKey('users.UserGroup', on_delete=models.CASCADE, verbose_name=_("User group"))
system_user = models.ForeignKey('assets.SystemUser', on_delete=models.CASCADE, verbose_name=_("System user")) system_user = models.ForeignKey('assets.SystemUser', on_delete=models.CASCADE, verbose_name=_("System user"))
......
...@@ -4,40 +4,27 @@ ...@@ -4,40 +4,27 @@
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers from rest_framework import serializers
from common.utils import get_object_or_none from common.utils import get_object_or_none
from .models import AssetPermission from common.fields import StringIDField
from .hands import User from .models import AssetPermission, NodePermission
class AssetPermissionSerializer(serializers.ModelSerializer): class AssetPermissionCreateUpdateSerializer(serializers.ModelSerializer):
assets_ = serializers.SerializerMethodField()
asset_groups_ = serializers.SerializerMethodField()
users_ = serializers.SerializerMethodField()
user_groups_ = serializers.SerializerMethodField()
system_users_ = serializers.SerializerMethodField()
class Meta: class Meta:
model = AssetPermission model = NodePermission
fields = '__all__' fields = [
'node', 'user_group', 'system_user',
@staticmethod 'is_active', 'date_expired'
def get_assets_(obj): ]
return [asset.hostname for asset in obj.assets.all()]
@staticmethod
def get_asset_groups_(obj):
return [group.name for group in obj.asset_groups.all()]
@staticmethod
def get_users_(obj):
return [user.username for user in obj.users.all()]
@staticmethod class AssetPermissionListSerializer(serializers.ModelSerializer):
def get_user_groups_(obj): node = StringIDField(read_only=True)
return [group.name for group in obj.user_groups.all()] user_group = StringIDField(read_only=True)
system_user = StringIDField(read_only=True)
@staticmethod class Meta:
def get_system_users_(obj): model = NodePermission
return [user.username for user in obj.system_users.all()] fields = '__all__'
class AssetPermissionUpdateUserSerializer(serializers.ModelSerializer): class AssetPermissionUpdateUserSerializer(serializers.ModelSerializer):
...@@ -54,7 +41,7 @@ class AssetPermissionUpdateAssetSerializer(serializers.ModelSerializer): ...@@ -54,7 +41,7 @@ class AssetPermissionUpdateAssetSerializer(serializers.ModelSerializer):
fields = ['id', 'assets'] fields = ['id', 'assets']
class UserAssetPermissionSerializer(AssetPermissionSerializer): class UserAssetPermissionCreateUpdateSerializer(AssetPermissionCreateUpdateSerializer):
is_inherited = serializers.SerializerMethodField() is_inherited = serializers.SerializerMethodField()
@staticmethod @staticmethod
......
...@@ -30,17 +30,10 @@ ...@@ -30,17 +30,10 @@
<div class="ibox-content"> <div class="ibox-content">
<form method="post" class="form-horizontal" action="" > <form method="post" class="form-horizontal" action="" >
{% csrf_token %} {% csrf_token %}
<h3>{% trans 'Name' %}</h3> <h3>{% trans 'Basic' %}</h3>
{% bootstrap_field form.name layout="horizontal" %} {% bootstrap_field form.node layout="horizontal" %}
<div class="hr-line-dashed"></div> {% bootstrap_field form.user_group layout="horizontal" %}
<h3>{% trans 'User' %}</h3> {% bootstrap_field form.system_user layout="horizontal" %}
{% bootstrap_field form.users layout="horizontal" %}
{% bootstrap_field form.user_groups layout="horizontal" %}
<div class="hr-line-dashed"></div>
<h3>{% trans 'Asset' %}</h3>
{% bootstrap_field form.assets layout="horizontal" %}
{% bootstrap_field form.asset_groups layout="horizontal" %}
{% bootstrap_field form.system_users layout="horizontal" %}
<div class="hr-line-dashed"></div> <div class="hr-line-dashed"></div>
<h3>{% trans 'Other' %}</h3> <h3>{% trans 'Other' %}</h3>
<div class="form-group"> <div class="form-group">
...@@ -59,7 +52,7 @@ ...@@ -59,7 +52,7 @@
</div> </div>
<span class="help-block ">{{ form.date_expired.errors }}</span> <span class="help-block ">{{ form.date_expired.errors }}</span>
</div> </div>
</div> </div>
{% bootstrap_field form.comment layout="horizontal" %} {% bootstrap_field form.comment layout="horizontal" %}
<div class="form-group"> <div class="form-group">
......
...@@ -6,7 +6,6 @@ ...@@ -6,7 +6,6 @@
{% block help_message %} {% block help_message %}
<div class="alert alert-info help-message"> <div class="alert alert-info help-message">
提前规划好集群中的系统用户,授权时选择的资产(组内资产)必须存在该系统用户,否则可能无法成功登录
</div> </div>
{% endblock %} {% endblock %}
...@@ -20,15 +19,13 @@ ...@@ -20,15 +19,13 @@
<thead> <thead>
<tr> <tr>
<th class="text-center"> <th class="text-center">
<input type="checkbox" id="check_all" class="ipt_check_all" > <input type="checkbox" id="check_all" class="ipt_check_all" >
</th> </th>
<th class="text-center">{% trans 'Name' %}</th> <th class="text-center">{% trans 'Node' %}</th>
<th class="text-center">{% trans 'User' %}</th>
<th class="text-center">{% trans 'User group' %}</th> <th class="text-center">{% trans 'User group' %}</th>
<th class="text-center">{% trans 'Asset' %}</th>
<th class="text-center">{% trans 'Asset group' %}</th>
<th class="text-center">{% trans 'System user' %}</th> <th class="text-center">{% trans 'System user' %}</th>
<th class="text-center">{% trans 'Is valid' %}</th> <th class="text-center">{% trans 'Is active' %}</th>
<th class="text-center">{% trans 'Date expired' %}</th>
<th class="text-center">{% trans 'Action' %}</th> <th class="text-center">{% trans 'Action' %}</th>
</tr> </tr>
</thead> </thead>
...@@ -43,38 +40,27 @@ function initTable() { ...@@ -43,38 +40,27 @@ function initTable() {
var options = { var options = {
ele: $('#permission_list_table'), ele: $('#permission_list_table'),
columnDefs: [ columnDefs: [
{targets: 1, createdCell: function (td, cellData, rowData) { {targets: 1, createdCell: function (td, cellData) {
var detail_btn = '<a href="{% url "perms:asset-permission-detail" pk=DEFAULT_PK %}">' + cellData + '</a>'; var html = '<a href="">' + cellData.name + '</a>';
$(td).html(detail_btn.replace('{{ DEFAULT_PK }}', rowData.id)); $(td).html(html)
}}, }},
{targets: 2, createdCell: function (td, cellData) { {targets: 2, createdCell: function (td, cellData) {
var html = createPopover(cellData); var html = '<a href="">' + cellData.name + '</a>';
$(td).html(html); $(td).html(html)
}}, }},
{targets: 3, createdCell: function (td, cellData) { {targets: 3, createdCell: function (td, cellData) {
var html = createPopover(cellData); var html = '<a href="">' + cellData.name + '</a>';
$(td).html(html); $(td).html(html)
}}, }},
{targets: 4, createdCell: function (td, cellData) { {targets: 4, createdCell: function (td, cellData) {
var html = createPopover(cellData);
$(td).html(html);
}},
{targets: 5, createdCell: function (td, cellData) {
var html = createPopover(cellData);
$(td).html(html);
}},
{targets: 6, createdCell: function (td, cellData) {
var html = createPopover(cellData);
$(td).html(html);
}},
{targets: 7, createdCell: function (td, cellData) {
if (!cellData) { if (!cellData) {
$(td).html('<i class="fa fa-times text-danger"></i>') $(td).html('<i class="fa fa-times text-danger"></i>')
} else { } else {
$(td).html('<i class="fa fa-check text-navy"></i>') $(td).html('<i class="fa fa-check text-navy"></i>')
} }
}}, }},
{targets: 8, createdCell: function (td, cellData, rowData) {
{targets: 6, createdCell: function (td, cellData, rowData) {
var update_btn = '<a href="{% url "perms:asset-permission-update" pk=DEFAULT_PK %}" class="btn btn-xs m-l-xs btn-info">{% trans "Update" %}</a>'.replace('{{ DEFAULT_PK }}', cellData); var update_btn = '<a href="{% url "perms:asset-permission-update" pk=DEFAULT_PK %}" class="btn btn-xs m-l-xs btn-info">{% trans "Update" %}</a>'.replace('{{ DEFAULT_PK }}', cellData);
var del_btn = '<a class="btn btn-xs btn-danger m-l-xs btn-del" data-uid="{{ DEFAULT_PK }}" data-name="99991938">{% trans "Delete" %}</a>' var del_btn = '<a class="btn btn-xs btn-danger m-l-xs btn-del" data-uid="{{ DEFAULT_PK }}" data-name="99991938">{% trans "Delete" %}</a>'
.replace('{{ DEFAULT_PK }}', cellData) .replace('{{ DEFAULT_PK }}', cellData)
...@@ -85,16 +71,12 @@ function initTable() { ...@@ -85,16 +71,12 @@ function initTable() {
], ],
ajax_url: '{% url "api-perms:asset-permission-list" %}', ajax_url: '{% url "api-perms:asset-permission-list" %}',
columns: [ columns: [
{data: "id" }, {data: "name"}, {data: "users_" }, {data: "user_groups_" }, {data: "assets_" }, {data: "id"}, {data: "node"}, {data: "user_group" }, {data: "system_user"},
{data: "asset_groups_"}, {data: "system_users_"}, {data: "is_active"}, {data: "id" } {data: "is_active"}, {data: "date_expired"}, {data: "id"}
], ],
op_html: $('#actions').html() op_html: $('#actions').html()
}; };
jumpserver.initDataTable(options).on('daw', function () { jumpserver.initDataTable(options)
$('[data-toggle="popover"]').popover({
html: true
});
});
} }
$(document).ready(function(){ $(document).ready(function(){
......
...@@ -5,21 +5,20 @@ from __future__ import unicode_literals, absolute_import ...@@ -5,21 +5,20 @@ 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.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, FormView from django.views.generic.edit import DeleteView
from django.urls import reverse_lazy from django.urls import reverse_lazy
from django.contrib.messages.views import SuccessMessageMixin from django.contrib.messages.views import SuccessMessageMixin
from django.views.generic.detail import DetailView, SingleObjectMixin from django.views.generic.detail import DetailView, SingleObjectMixin
from django.contrib import messages
from common.const import create_success_msg, update_success_msg from common.const import create_success_msg, update_success_msg
from .hands import AdminUserRequiredMixin, User, UserGroup, SystemUser, \ from .hands import AdminUserRequiredMixin, User, UserGroup, SystemUser, \
Asset, AssetGroup Asset, AssetGroup
from .models import AssetPermission from .models import AssetPermission, NodePermission
from .forms import AssetPermissionForm from .forms import AssetPermissionForm
class AssetPermissionListView(AdminUserRequiredMixin, ListView): class AssetPermissionListView(AdminUserRequiredMixin, ListView):
model = AssetPermission model = NodePermission
context_object_name = 'asset_permission_list' context_object_name = 'asset_permission_list'
template_name = 'perms/asset_permission_list.html' template_name = 'perms/asset_permission_list.html'
...@@ -32,12 +31,11 @@ class AssetPermissionListView(AdminUserRequiredMixin, ListView): ...@@ -32,12 +31,11 @@ class AssetPermissionListView(AdminUserRequiredMixin, ListView):
return super().get_context_data(**kwargs) return super().get_context_data(**kwargs)
class AssetPermissionCreateView(AdminUserRequiredMixin, SuccessMessageMixin, CreateView): class AssetPermissionCreateView(AdminUserRequiredMixin, CreateView):
model = AssetPermission model = NodePermission
form_class = AssetPermissionForm form_class = AssetPermissionForm
template_name = 'perms/asset_permission_create_update.html' template_name = 'perms/asset_permission_create_update.html'
success_url = reverse_lazy('perms:asset-permission-list') success_url = reverse_lazy('perms:asset-permission-list')
success_message = create_success_msg
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = { context = {
...@@ -48,12 +46,11 @@ class AssetPermissionCreateView(AdminUserRequiredMixin, SuccessMessageMixin, Cre ...@@ -48,12 +46,11 @@ class AssetPermissionCreateView(AdminUserRequiredMixin, SuccessMessageMixin, Cre
return super().get_context_data(**kwargs) return super().get_context_data(**kwargs)
class AssetPermissionUpdateView(AdminUserRequiredMixin, SuccessMessageMixin, UpdateView): class AssetPermissionUpdateView(AdminUserRequiredMixin, UpdateView):
model = AssetPermission model = NodePermission
form_class = AssetPermissionForm form_class = AssetPermissionForm
template_name = 'perms/asset_permission_create_update.html' template_name = 'perms/asset_permission_create_update.html'
success_url = reverse_lazy("perms:asset-permission-list") success_url = reverse_lazy("perms:asset-permission-list")
success_message = update_success_msg
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = { context = {
......
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