2018-11-23 02:25:35 +00:00
|
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
#
|
2020-06-10 09:34:56 +00:00
|
|
|
|
import os
|
|
|
|
|
import tarfile
|
|
|
|
|
|
2020-03-12 08:24:38 +00:00
|
|
|
|
from django.shortcuts import get_object_or_404, reverse
|
2020-06-10 09:34:56 +00:00
|
|
|
|
from django.utils.translation import ugettext as _
|
|
|
|
|
from django.utils.encoding import escape_uri_path
|
|
|
|
|
from django.http import FileResponse, HttpResponse
|
2018-11-23 02:25:35 +00:00
|
|
|
|
from django.core.files.storage import default_storage
|
2020-04-07 04:26:47 +00:00
|
|
|
|
from rest_framework import viewsets, views
|
2019-03-18 03:34:13 +00:00
|
|
|
|
from rest_framework.response import Response
|
2020-06-10 09:34:56 +00:00
|
|
|
|
from rest_framework.decorators import action
|
2018-11-23 02:25:35 +00:00
|
|
|
|
|
2020-06-10 09:34:56 +00:00
|
|
|
|
from common.utils import model_to_json
|
|
|
|
|
from .. import utils
|
|
|
|
|
from common.const.http import GET
|
2020-04-07 04:26:47 +00:00
|
|
|
|
from common.utils import is_uuid, get_logger, get_object_or_none
|
2020-03-12 08:24:38 +00:00
|
|
|
|
from common.mixins.api import AsyncApiMixin
|
2020-04-07 04:26:47 +00:00
|
|
|
|
from common.permissions import IsOrgAdminOrAppUser, IsOrgAuditor, IsAppUser
|
2019-12-05 07:09:25 +00:00
|
|
|
|
from common.drf.filters import DatetimeRangeFilter
|
2020-06-10 09:34:56 +00:00
|
|
|
|
from common.drf.renders import PassthroughRenderer
|
2019-08-21 12:27:21 +00:00
|
|
|
|
from orgs.mixins.api import OrgBulkModelViewSet
|
2020-04-07 04:26:47 +00:00
|
|
|
|
from orgs.utils import tmp_to_root_org, tmp_to_org
|
|
|
|
|
from users.models import User
|
2020-03-12 08:24:38 +00:00
|
|
|
|
from ..utils import find_session_replay_local, download_session_replay
|
2019-03-18 03:34:13 +00:00
|
|
|
|
from ..hands import SystemUser
|
2020-03-12 08:24:38 +00:00
|
|
|
|
from ..models import Session
|
2019-03-18 03:34:13 +00:00
|
|
|
|
from .. import serializers
|
2018-11-23 02:25:35 +00:00
|
|
|
|
|
2019-07-03 10:03:01 +00:00
|
|
|
|
|
2020-04-07 04:26:47 +00:00
|
|
|
|
__all__ = [
|
|
|
|
|
'SessionViewSet', 'SessionReplayViewSet', 'SessionJoinValidateAPI'
|
|
|
|
|
]
|
2019-07-03 10:03:01 +00:00
|
|
|
|
logger = get_logger(__name__)
|
2018-11-23 02:25:35 +00:00
|
|
|
|
|
|
|
|
|
|
2019-07-03 14:28:20 +00:00
|
|
|
|
class SessionViewSet(OrgBulkModelViewSet):
|
2019-10-18 07:05:45 +00:00
|
|
|
|
model = Session
|
2020-03-12 08:24:38 +00:00
|
|
|
|
serializer_classes = {
|
|
|
|
|
'default': serializers.SessionSerializer,
|
|
|
|
|
'display': serializers.SessionDisplaySerializer,
|
|
|
|
|
}
|
2019-09-25 08:58:41 +00:00
|
|
|
|
permission_classes = (IsOrgAdminOrAppUser, )
|
2021-02-03 03:51:02 +00:00
|
|
|
|
search_fields = [
|
|
|
|
|
"user", "asset", "system_user", "remote_addr", "protocol", "is_finished", 'login_from',
|
2019-07-03 14:28:20 +00:00
|
|
|
|
]
|
2021-02-03 03:51:02 +00:00
|
|
|
|
filterset_fields = search_fields + ['terminal']
|
2019-07-03 14:28:20 +00:00
|
|
|
|
date_range_filter_fields = [
|
|
|
|
|
('date_start', ('date_from', 'date_to'))
|
|
|
|
|
]
|
2019-09-23 06:41:34 +00:00
|
|
|
|
extra_filter_backends = [DatetimeRangeFilter]
|
2019-07-03 08:29:39 +00:00
|
|
|
|
|
2020-06-10 09:34:56 +00:00
|
|
|
|
@staticmethod
|
|
|
|
|
def prepare_offline_file(session, local_path):
|
|
|
|
|
replay_path = default_storage.path(local_path)
|
|
|
|
|
current_dir = os.getcwd()
|
|
|
|
|
dir_path = os.path.dirname(replay_path)
|
|
|
|
|
replay_filename = os.path.basename(replay_path)
|
|
|
|
|
meta_filename = '{}.json'.format(session.id)
|
|
|
|
|
offline_filename = '{}.tar'.format(session.id)
|
|
|
|
|
os.chdir(dir_path)
|
|
|
|
|
|
|
|
|
|
with open(meta_filename, 'wt') as f:
|
|
|
|
|
f.write(model_to_json(session))
|
|
|
|
|
|
|
|
|
|
with tarfile.open(offline_filename, 'w') as f:
|
|
|
|
|
f.add(replay_filename)
|
|
|
|
|
f.add(meta_filename)
|
|
|
|
|
file = open(offline_filename, 'rb')
|
|
|
|
|
os.chdir(current_dir)
|
|
|
|
|
return file
|
|
|
|
|
|
|
|
|
|
@action(methods=[GET], detail=True, renderer_classes=(PassthroughRenderer,), url_path='replay/download', url_name='replay-download')
|
|
|
|
|
def download(self, request, *args, **kwargs):
|
|
|
|
|
session = self.get_object()
|
|
|
|
|
local_path, url = utils.get_session_replay_url(session)
|
|
|
|
|
if local_path is None:
|
2021-03-06 09:09:36 +00:00
|
|
|
|
return Response({"error": url}, status=404)
|
2020-06-10 09:34:56 +00:00
|
|
|
|
file = self.prepare_offline_file(session, local_path)
|
|
|
|
|
|
|
|
|
|
response = FileResponse(file)
|
|
|
|
|
response['Content-Type'] = 'application/octet-stream'
|
|
|
|
|
# 这里要注意哦,网上查到的方法都是response['Content-Disposition']='attachment;filename="filename.py"',
|
|
|
|
|
# 但是如果文件名是英文名没问题,如果文件名包含中文,下载下来的文件名会被改为url中的path。
|
|
|
|
|
filename = escape_uri_path('{}.tar'.format(session.id))
|
|
|
|
|
disposition = "attachment; filename*=UTF-8''{}".format(filename)
|
|
|
|
|
response["Content-Disposition"] = disposition
|
|
|
|
|
return response
|
|
|
|
|
|
2019-07-04 09:09:36 +00:00
|
|
|
|
def filter_queryset(self, queryset):
|
|
|
|
|
queryset = super().filter_queryset(queryset)
|
2021-05-17 06:46:40 +00:00
|
|
|
|
# 解决guacamole更新session时并发导致幽灵会话的问题,暂不处理
|
2019-07-04 09:09:36 +00:00
|
|
|
|
if self.request.method in ('PATCH',):
|
|
|
|
|
queryset = queryset.select_for_update()
|
2019-01-15 02:23:30 +00:00
|
|
|
|
return queryset
|
2018-11-23 02:25:35 +00:00
|
|
|
|
|
|
|
|
|
def perform_create(self, serializer):
|
|
|
|
|
if hasattr(self.request.user, 'terminal'):
|
|
|
|
|
serializer.validated_data["terminal"] = self.request.user.terminal
|
|
|
|
|
return super().perform_create(serializer)
|
|
|
|
|
|
2019-09-25 08:58:41 +00:00
|
|
|
|
def get_permissions(self):
|
2020-06-04 06:55:33 +00:00
|
|
|
|
if self.request.method.lower() in ['get', 'options']:
|
2019-09-25 08:58:41 +00:00
|
|
|
|
self.permission_classes = (IsOrgAdminOrAppUser | IsOrgAuditor, )
|
|
|
|
|
return super().get_permissions()
|
|
|
|
|
|
2018-11-23 02:25:35 +00:00
|
|
|
|
|
2020-03-12 08:24:38 +00:00
|
|
|
|
class SessionReplayViewSet(AsyncApiMixin, viewsets.ViewSet):
|
2018-11-23 02:25:35 +00:00
|
|
|
|
serializer_class = serializers.ReplaySerializer
|
2019-09-12 10:56:26 +00:00
|
|
|
|
permission_classes = (IsOrgAdminOrAppUser | IsOrgAuditor,)
|
2018-11-23 02:25:35 +00:00
|
|
|
|
session = None
|
2020-03-12 08:24:38 +00:00
|
|
|
|
download_cache_key = "SESSION_REPLAY_DOWNLOAD_{}"
|
2018-11-23 02:25:35 +00:00
|
|
|
|
|
|
|
|
|
def create(self, request, *args, **kwargs):
|
|
|
|
|
session_id = kwargs.get('pk')
|
2018-12-18 03:29:21 +00:00
|
|
|
|
session = get_object_or_404(Session, id=session_id)
|
2018-11-23 02:25:35 +00:00
|
|
|
|
serializer = self.serializer_class(data=request.data)
|
|
|
|
|
|
|
|
|
|
if serializer.is_valid():
|
|
|
|
|
file = serializer.validated_data['file']
|
2020-09-27 06:34:47 +00:00
|
|
|
|
name, err = session.save_replay_to_storage(file)
|
2018-11-23 02:25:35 +00:00
|
|
|
|
if not name:
|
|
|
|
|
msg = "Failed save replay `{}`: {}".format(session_id, err)
|
|
|
|
|
logger.error(msg)
|
|
|
|
|
return Response({'msg': str(err)}, status=400)
|
|
|
|
|
url = default_storage.url(name)
|
|
|
|
|
return Response({'url': url}, status=201)
|
|
|
|
|
else:
|
|
|
|
|
msg = 'Upload data invalid: {}'.format(serializer.errors)
|
|
|
|
|
logger.error(msg)
|
|
|
|
|
return Response({'msg': serializer.errors}, status=401)
|
|
|
|
|
|
2020-03-12 08:24:38 +00:00
|
|
|
|
@staticmethod
|
|
|
|
|
def get_replay_data(session, url):
|
2018-12-19 11:55:41 +00:00
|
|
|
|
tp = 'json'
|
|
|
|
|
if session.protocol in ('rdp', 'vnc'):
|
2021-05-17 06:46:40 +00:00
|
|
|
|
# 需要考虑录像播放和离线播放器的约定,暂时不处理
|
2018-12-19 11:55:41 +00:00
|
|
|
|
tp = 'guacamole'
|
|
|
|
|
|
2020-06-10 09:34:56 +00:00
|
|
|
|
download_url = reverse('api-terminal:session-replay-download', kwargs={'pk': session.id})
|
2020-03-12 08:24:38 +00:00
|
|
|
|
data = {
|
|
|
|
|
'type': tp, 'src': url,
|
|
|
|
|
'user': session.user, 'asset': session.asset,
|
|
|
|
|
'system_user': session.system_user,
|
|
|
|
|
'date_start': session.date_start,
|
|
|
|
|
'date_end': session.date_end,
|
|
|
|
|
'download_url': download_url,
|
2019-12-06 03:36:36 +00:00
|
|
|
|
}
|
2020-03-12 08:24:38 +00:00
|
|
|
|
return data
|
2018-11-23 02:25:35 +00:00
|
|
|
|
|
2020-03-12 08:24:38 +00:00
|
|
|
|
def is_need_async(self):
|
|
|
|
|
if self.action != 'retrieve':
|
|
|
|
|
return False
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
|
def retrieve(self, request, *args, **kwargs):
|
|
|
|
|
session_id = kwargs.get('pk')
|
|
|
|
|
session = get_object_or_404(Session, id=session_id)
|
|
|
|
|
local_path, url = find_session_replay_local(session)
|
|
|
|
|
|
|
|
|
|
if not local_path:
|
|
|
|
|
local_path, url = download_session_replay(session)
|
|
|
|
|
if not local_path:
|
2021-03-06 09:09:36 +00:00
|
|
|
|
return Response({"error": url}, status=404)
|
2020-03-12 08:24:38 +00:00
|
|
|
|
data = self.get_replay_data(session, url)
|
|
|
|
|
return Response(data)
|
2020-04-07 04:26:47 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class SessionJoinValidateAPI(views.APIView):
|
|
|
|
|
permission_classes = (IsAppUser, )
|
|
|
|
|
serializer_class = serializers.SessionJoinValidateSerializer
|
|
|
|
|
|
|
|
|
|
def post(self, request, *args, **kwargs):
|
|
|
|
|
serializer = self.serializer_class(data=request.data)
|
|
|
|
|
if not serializer.is_valid():
|
|
|
|
|
msg = str(serializer.errors)
|
|
|
|
|
return Response({'ok': False, 'msg': msg}, status=401)
|
|
|
|
|
user_id = serializer.validated_data['user_id']
|
|
|
|
|
session_id = serializer.validated_data['session_id']
|
|
|
|
|
|
|
|
|
|
with tmp_to_root_org():
|
|
|
|
|
session = get_object_or_none(Session, pk=session_id)
|
|
|
|
|
if not session:
|
|
|
|
|
msg = _('Session does not exist: {}'.format(session_id))
|
|
|
|
|
return Response({'ok': False, 'msg': msg}, status=401)
|
2020-04-14 08:12:24 +00:00
|
|
|
|
if not session.can_join:
|
2020-04-07 04:26:47 +00:00
|
|
|
|
msg = _('Session is finished or the protocol not supported')
|
|
|
|
|
return Response({'ok': False, 'msg': msg}, status=401)
|
|
|
|
|
|
|
|
|
|
user = get_object_or_none(User, pk=user_id)
|
|
|
|
|
if not user:
|
|
|
|
|
msg = _('User does not exist: {}'.format(user_id))
|
|
|
|
|
return Response({'ok': False, 'msg': msg}, status=401)
|
|
|
|
|
with tmp_to_org(session.org):
|
|
|
|
|
if not user.admin_or_audit_orgs:
|
|
|
|
|
msg = _('User does not have permission')
|
|
|
|
|
return Response({'ok': False, 'msg': msg}, status=401)
|
|
|
|
|
|
|
|
|
|
return Response({'ok': True, 'msg': ''}, status=200)
|