jumpserver/apps/assets/views/asset.py

326 lines
11 KiB
Python
Raw Normal View History

2017-04-04 03:37:52 +00:00
# coding:utf-8
from __future__ import absolute_import, unicode_literals
2017-04-08 16:45:28 +00:00
import csv
2017-04-04 03:37:52 +00:00
import json
import uuid
2017-04-08 16:45:28 +00:00
import codecs
import chardet
2017-04-08 16:45:28 +00:00
from io import StringIO
2017-04-04 03:37:52 +00:00
from django.db import transaction
from django.contrib import messages
2017-04-08 16:45:28 +00:00
from django.utils.translation import ugettext_lazy as _
2017-04-04 03:37:52 +00:00
from django.views.generic import TemplateView, ListView, View
from django.views.generic.edit import CreateView, DeleteView, FormView, UpdateView
from django.urls import reverse_lazy
2017-12-15 07:50:15 +00:00
from django.views.generic.detail import DetailView
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
2017-04-04 03:37:52 +00:00
from django.utils.decorators import method_decorator
from django.core.cache import cache
from django.utils import timezone
from django.contrib.auth.mixins import LoginRequiredMixin
2017-12-15 07:50:15 +00:00
from django.shortcuts import redirect
from django.contrib.messages.views import SuccessMessageMixin
2017-04-04 03:37:52 +00:00
from common.mixins import JSONResponseMixin
from common.utils import get_object_or_none, get_logger
from common.permissions import AdminUserRequiredMixin
from common.const import create_success_msg, update_success_msg
from orgs.utils import current_org
2017-04-04 03:37:52 +00:00
from .. import forms
from ..models import Asset, AdminUser, SystemUser, Label, Node, Domain
2017-04-04 03:37:52 +00:00
__all__ = [
'AssetListView', 'AssetCreateView', 'AssetUpdateView',
'UserAssetListView', 'AssetBulkUpdateView', 'AssetDetailView',
2018-02-09 07:24:44 +00:00
'AssetDeleteView', 'AssetExportView', 'BulkImportAssetView',
]
2017-12-15 07:50:15 +00:00
logger = get_logger(__file__)
2017-04-04 03:37:52 +00:00
class AssetListView(AdminUserRequiredMixin, TemplateView):
template_name = 'assets/asset_list.html'
2017-04-04 03:37:52 +00:00
def get_context_data(self, **kwargs):
if current_org.is_default():
Node.default_node()
else:
Node.root()
2017-04-04 03:37:52 +00:00
context = {
2017-12-30 12:45:54 +00:00
'app': _('Assets'),
'action': _('Asset list'),
2018-01-26 06:47:10 +00:00
'labels': Label.objects.all().order_by('name'),
2018-04-13 07:48:10 +00:00
'nodes': Node.objects.all().order_by('-key'),
2017-04-04 03:37:52 +00:00
}
kwargs.update(context)
2017-12-15 07:50:15 +00:00
return super().get_context_data(**kwargs)
2017-04-04 03:37:52 +00:00
class UserAssetListView(LoginRequiredMixin, TemplateView):
template_name = 'assets/user_asset_list.html'
def get_context_data(self, **kwargs):
context = {
2018-03-04 05:01:33 +00:00
'action': _('My assets'),
2017-04-04 03:37:52 +00:00
'system_users': SystemUser.objects.all(),
}
kwargs.update(context)
2017-12-15 07:50:15 +00:00
return super().get_context_data(**kwargs)
2017-04-04 03:37:52 +00:00
class AssetCreateView(AdminUserRequiredMixin, SuccessMessageMixin, CreateView):
2017-04-04 03:37:52 +00:00
model = Asset
form_class = forms.AssetCreateForm
template_name = 'assets/asset_create.html'
success_url = reverse_lazy('assets:asset-list')
def get_form(self, form_class=None):
form = super().get_form(form_class=form_class)
node_id = self.request.GET.get("node_id")
if node_id:
node = get_object_or_none(Node, id=node_id)
else:
node = Node.root()
form["nodes"].initial = node
return form
2017-04-04 03:37:52 +00:00
def get_context_data(self, **kwargs):
context = {
2018-01-01 07:08:33 +00:00
'app': _('Assets'),
'action': _('Create asset'),
2017-04-04 03:37:52 +00:00
}
kwargs.update(context)
2017-12-12 04:19:45 +00:00
return super().get_context_data(**kwargs)
2017-04-04 03:37:52 +00:00
def get_success_message(self, cleaned_data):
return create_success_msg % ({"name": cleaned_data["hostname"]})
2017-04-04 03:37:52 +00:00
2017-04-11 09:29:53 +00:00
class AssetBulkUpdateView(AdminUserRequiredMixin, ListView):
model = Asset
form_class = forms.AssetBulkUpdateForm
template_name = 'assets/asset_bulk_update.html'
2017-04-04 03:37:52 +00:00
success_url = reverse_lazy('assets:asset-list')
success_message = _("Bulk update asset success")
id_list = None
form = None
2017-04-04 03:37:52 +00:00
2017-04-11 09:29:53 +00:00
def get(self, request, *args, **kwargs):
assets_id = self.request.GET.get('assets_id', '')
self.id_list = [i for i in assets_id.split(',')]
2017-04-12 03:50:15 +00:00
if kwargs.get('form'):
self.form = kwargs['form']
elif assets_id:
self.form = self.form_class(
initial={'assets': self.id_list}
2017-04-12 03:50:15 +00:00
)
else:
self.form = self.form_class()
2017-12-15 07:50:15 +00:00
return super().get(request, *args, **kwargs)
2017-04-11 09:29:53 +00:00
def post(self, request, *args, **kwargs):
2017-04-12 03:50:15 +00:00
form = self.form_class(request.POST)
if form.is_valid():
form.save()
messages.success(request, self.success_message)
2017-04-12 03:50:15 +00:00
return redirect(self.success_url)
2017-04-04 03:37:52 +00:00
else:
2017-04-12 03:50:15 +00:00
return self.get(request, form=form, *args, **kwargs)
2017-04-04 03:37:52 +00:00
def get_context_data(self, **kwargs):
context = {
2018-01-01 07:08:33 +00:00
'app': _('Assets'),
'action': _('Bulk update asset'),
2017-04-11 09:29:53 +00:00
'form': self.form,
'assets_selected': self.id_list,
2017-04-04 03:37:52 +00:00
}
kwargs.update(context)
2017-12-15 07:50:15 +00:00
return super().get_context_data(**kwargs)
2017-04-04 03:37:52 +00:00
class AssetUpdateView(AdminUserRequiredMixin, SuccessMessageMixin, UpdateView):
2017-04-04 03:37:52 +00:00
model = Asset
form_class = forms.AssetUpdateForm
template_name = 'assets/asset_update.html'
success_url = reverse_lazy('assets:asset-list')
def get_context_data(self, **kwargs):
context = {
2018-01-01 07:08:33 +00:00
'app': _('Assets'),
'action': _('Update asset'),
2017-04-04 03:37:52 +00:00
}
kwargs.update(context)
2018-01-08 07:15:21 +00:00
return super().get_context_data(**kwargs)
2017-04-04 03:37:52 +00:00
def get_success_message(self, cleaned_data):
return update_success_msg % ({"name": cleaned_data["hostname"]})
2017-04-04 03:37:52 +00:00
class AssetDeleteView(AdminUserRequiredMixin, DeleteView):
model = Asset
template_name = 'delete_confirm.html'
2017-04-04 03:37:52 +00:00
success_url = reverse_lazy('assets:asset-list')
2018-08-06 02:24:51 +00:00
class AssetDetailView(LoginRequiredMixin, DetailView):
2017-04-04 03:37:52 +00:00
model = Asset
context_object_name = 'asset'
template_name = 'assets/asset_detail.html'
def get_context_data(self, **kwargs):
2018-02-09 07:24:44 +00:00
nodes_remain = Node.objects.exclude(assets=self.object)
2017-04-04 03:37:52 +00:00
context = {
2018-01-01 07:08:33 +00:00
'app': _('Assets'),
'action': _('Asset detail'),
2018-02-09 07:24:44 +00:00
'nodes_remain': nodes_remain,
2017-04-04 03:37:52 +00:00
}
kwargs.update(context)
2018-01-08 07:15:21 +00:00
return super().get_context_data(**kwargs)
2017-04-04 03:37:52 +00:00
@method_decorator(csrf_exempt, name='dispatch')
2018-08-06 02:24:51 +00:00
class AssetExportView(LoginRequiredMixin, View):
2017-12-15 07:50:15 +00:00
def get(self, request):
spm = request.GET.get('spm', '')
assets_id_default = [Asset.objects.first().id] if Asset.objects.first() else []
2017-12-15 07:50:15 +00:00
assets_id = cache.get(spm, assets_id_default)
fields = [
field for field in Asset._meta.fields
if field.name not in [
'date_created', 'org_id'
2017-12-15 07:50:15 +00:00
]
]
filename = 'assets-{}.csv'.format(
2018-02-25 10:08:00 +00:00
timezone.localtime(timezone.now()).strftime('%Y-%m-%d_%H-%M-%S')
)
2017-12-15 07:50:15 +00:00
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="%s"' % filename
response.write(codecs.BOM_UTF8)
assets = Asset.objects.filter(id__in=assets_id)
2018-02-25 10:08:00 +00:00
writer = csv.writer(response, dialect='excel', quoting=csv.QUOTE_MINIMAL)
2017-12-15 07:50:15 +00:00
header = [field.verbose_name for field in fields]
writer.writerow(header)
for asset in assets:
data = [getattr(asset, field.name) for field in fields]
writer.writerow(data)
return response
def post(self, request, *args, **kwargs):
try:
assets_id = json.loads(request.body).get('assets_id', [])
2018-04-04 11:38:32 +00:00
assets_node_id = json.loads(request.body).get('node_id', None)
2017-12-15 07:50:15 +00:00
except ValueError:
return HttpResponse('Json object not valid', status=400)
2018-04-04 11:38:32 +00:00
if not assets_id and assets_node_id:
assets_node = get_object_or_none(Node, id=assets_node_id)
assets = assets_node.get_all_assets()
for asset in assets:
assets_id.append(asset.id)
2017-12-15 07:50:15 +00:00
spm = uuid.uuid4().hex
cache.set(spm, assets_id, 300)
url = reverse_lazy('assets:asset-export') + '?spm=%s' % spm
return JsonResponse({'redirect': url})
2017-04-04 03:37:52 +00:00
class BulkImportAssetView(AdminUserRequiredMixin, JSONResponseMixin, FormView):
form_class = forms.FileForm
def form_valid(self, form):
2018-03-26 08:16:18 +00:00
node_id = self.request.GET.get("node_id")
node = get_object_or_none(Node, id=node_id) if node_id else Node.root()
f = form.cleaned_data['file']
det_result = chardet.detect(f.read())
f.seek(0) # reset file seek index
2018-02-27 04:18:36 +00:00
file_data = f.read().decode(det_result['encoding']).strip(codecs.BOM_UTF8.decode())
csv_file = StringIO(file_data)
2017-04-08 16:45:28 +00:00
reader = csv.reader(csv_file)
csv_data = [row for row in reader]
fields = [
field for field in Asset._meta.fields
if field.name not in [
'date_created'
]
]
header_ = csv_data[0]
mapping_reverse = {field.verbose_name: field.name for field in fields}
attr = [mapping_reverse.get(n, None) for n in header_]
if None in attr:
data = {'valid': False,
'msg': 'Must be same format as '
'template or export file'}
2017-04-04 03:37:52 +00:00
return self.render_json_response(data)
2017-04-08 16:45:28 +00:00
created, updated, failed = [], [], []
2017-04-09 09:59:14 +00:00
assets = []
2017-04-08 16:45:28 +00:00
for row in csv_data[1:]:
if set(row) == {''}:
continue
2018-04-12 10:50:43 +00:00
asset_dict_raw = dict(zip(attr, row))
asset_dict = dict()
for k, v in asset_dict_raw.items():
v = v.strip()
2018-02-25 10:08:00 +00:00
if k == 'is_active':
2018-04-12 10:50:43 +00:00
v = False if v in ['False', 0, 'false'] else True
2017-04-08 16:45:28 +00:00
elif k == 'admin_user':
v = get_object_or_none(AdminUser, name=v)
2018-02-25 10:08:00 +00:00
elif k in ['port', 'cpu_count', 'cpu_cores']:
2017-04-08 16:45:28 +00:00
try:
v = int(v)
except ValueError:
2018-04-12 10:50:43 +00:00
v = ''
elif k == 'domain':
v = get_object_or_none(Domain, name=v)
2017-04-08 16:45:28 +00:00
2018-04-12 10:50:43 +00:00
if v != '':
asset_dict[k] = v
asset = None
asset_id = asset_dict.pop('id', None)
if asset_id:
asset = get_object_or_none(Asset, id=asset_id)
2017-04-08 16:45:28 +00:00
if not asset:
try:
if len(Asset.objects.filter(hostname=asset_dict.get('hostname'))):
raise Exception(_('already exists'))
with transaction.atomic():
asset = Asset.objects.create(**asset_dict)
2018-03-26 08:16:18 +00:00
if node:
asset.nodes.set([node])
created.append(asset_dict['hostname'])
assets.append(asset)
except Exception as e:
2017-04-08 16:45:28 +00:00
failed.append('%s: %s' % (asset_dict['hostname'], str(e)))
else:
for k, v in asset_dict.items():
2018-04-12 10:50:43 +00:00
if v != '':
2017-04-08 16:45:28 +00:00
setattr(asset, k, v)
try:
asset.save()
updated.append(asset_dict['hostname'])
except Exception as e:
failed.append('%s: %s' % (asset_dict['hostname'], str(e)))
2017-04-04 03:37:52 +00:00
data = {
'created': created,
'created_info': 'Created {}'.format(len(created)),
'updated': updated,
'updated_info': 'Updated {}'.format(len(updated)),
'failed': failed,
'failed_info': 'Failed {}'.format(len(failed)),
'valid': True,
2017-04-08 16:45:28 +00:00
'msg': 'Created: {}. Updated: {}, Error: {}'.format(
len(created), len(updated), len(failed))
2017-04-04 03:37:52 +00:00
}
2017-04-04 11:16:34 +00:00
return self.render_json_response(data)