2018-11-23 02:25:35 +00:00
|
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
#
|
2020-06-10 09:34:56 +00:00
|
|
|
|
import os
|
|
|
|
|
import tarfile
|
2022-12-04 09:39:48 +00:00
|
|
|
|
from django.core.files.storage import default_storage
|
2022-07-01 11:07:42 +00:00
|
|
|
|
from django.db.models import F
|
2022-12-04 09:39:48 +00:00
|
|
|
|
from django.http import FileResponse
|
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.encoding import escape_uri_path
|
2022-12-04 09:39:48 +00:00
|
|
|
|
from django.utils.translation import ugettext as _
|
2023-02-15 06:30:57 +00:00
|
|
|
|
from django_filters import rest_framework as filters
|
2022-12-04 09:39:48 +00:00
|
|
|
|
from rest_framework import generics
|
2020-04-07 04:26:47 +00:00
|
|
|
|
from rest_framework import viewsets, views
|
2020-06-10 09:34:56 +00:00
|
|
|
|
from rest_framework.decorators import action
|
2021-12-13 02:50:10 +00:00
|
|
|
|
from rest_framework.permissions import IsAuthenticated
|
2022-12-04 09:39:48 +00:00
|
|
|
|
from rest_framework.response import Response
|
2018-11-23 02:25:35 +00:00
|
|
|
|
|
2023-02-15 06:30:57 +00:00
|
|
|
|
from common.drf.filters import BaseFilterSet
|
2020-06-10 09:34:56 +00:00
|
|
|
|
from common.const.http import GET
|
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
|
2023-01-16 11:02:09 +00:00
|
|
|
|
from common.api import AsyncApiMixin
|
2023-02-15 06:30:57 +00:00
|
|
|
|
from common.utils import data_to_json, is_uuid
|
2022-12-04 09:39:48 +00:00
|
|
|
|
from common.utils import get_logger, get_object_or_none
|
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
|
2022-12-04 09:39:48 +00:00
|
|
|
|
from terminal import serializers
|
|
|
|
|
from terminal.models import Session
|
2022-10-25 04:57:34 +00:00
|
|
|
|
from terminal.utils import (
|
|
|
|
|
find_session_replay_local, download_session_replay,
|
|
|
|
|
is_session_approver, get_session_replay_url
|
|
|
|
|
)
|
2022-12-04 09:39:48 +00:00
|
|
|
|
from users.models import User
|
2018-11-23 02:25:35 +00:00
|
|
|
|
|
2020-04-07 04:26:47 +00:00
|
|
|
|
__all__ = [
|
2022-10-25 04:57:34 +00:00
|
|
|
|
'SessionViewSet', 'SessionReplayViewSet',
|
|
|
|
|
'SessionJoinValidateAPI', 'MySessionAPIView',
|
2020-04-07 04:26:47 +00:00
|
|
|
|
]
|
2021-12-29 12:07:56 +00:00
|
|
|
|
|
2019-07-03 10:03:01 +00:00
|
|
|
|
logger = get_logger(__name__)
|
2018-11-23 02:25:35 +00:00
|
|
|
|
|
|
|
|
|
|
2021-12-13 02:50:10 +00:00
|
|
|
|
class MySessionAPIView(generics.ListAPIView):
|
2022-12-04 09:39:48 +00:00
|
|
|
|
permission_classes = (IsAuthenticated,)
|
2021-12-13 02:50:10 +00:00
|
|
|
|
serializer_class = serializers.SessionSerializer
|
|
|
|
|
|
|
|
|
|
def get_queryset(self):
|
2022-04-12 06:25:49 +00:00
|
|
|
|
user = self.request.user
|
|
|
|
|
qs = Session.objects.filter(user_id=user.id)
|
|
|
|
|
return qs
|
2021-12-13 02:50:10 +00:00
|
|
|
|
|
|
|
|
|
|
2023-02-15 06:30:57 +00:00
|
|
|
|
class SessionFilterSet(BaseFilterSet):
|
|
|
|
|
terminal = filters.CharFilter(method='filter_terminal')
|
|
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
|
model = Session
|
|
|
|
|
fields = [
|
|
|
|
|
"user", "asset", "account", "remote_addr",
|
|
|
|
|
"protocol", "is_finished", 'login_from', 'terminal'
|
|
|
|
|
]
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def filter_terminal(queryset, name, value):
|
|
|
|
|
if is_uuid(value):
|
|
|
|
|
return queryset.filter(terminal__id=value)
|
|
|
|
|
else:
|
|
|
|
|
return queryset.filter(terminal__name=value)
|
|
|
|
|
|
|
|
|
|
|
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,
|
|
|
|
|
}
|
2021-02-03 03:51:02 +00:00
|
|
|
|
search_fields = [
|
2022-08-24 08:14:32 +00:00
|
|
|
|
"user", "asset", "account", "remote_addr",
|
2022-02-17 12:13:31 +00:00
|
|
|
|
"protocol", "is_finished", 'login_from',
|
2019-07-03 14:28:20 +00:00
|
|
|
|
]
|
2023-02-15 06:30:57 +00:00
|
|
|
|
filterset_class = SessionFilterSet
|
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]
|
2022-02-17 12:13:31 +00:00
|
|
|
|
rbac_perms = {
|
2022-04-20 11:12:55 +00:00
|
|
|
|
'download': ['terminal.download_sessionreplay']
|
2022-02-17 12:13:31 +00:00
|
|
|
|
}
|
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:
|
2022-02-08 10:58:56 +00:00
|
|
|
|
serializer = serializers.SessionDisplaySerializer(session)
|
|
|
|
|
data = data_to_json(serializer.data)
|
|
|
|
|
f.write(data)
|
2020-06-10 09:34:56 +00:00
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
2021-12-08 07:35:22 +00:00
|
|
|
|
@action(methods=[GET], detail=True, renderer_classes=(PassthroughRenderer,), url_path='replay/download',
|
|
|
|
|
url_name='replay-download')
|
2020-06-10 09:34:56 +00:00
|
|
|
|
def download(self, request, *args, **kwargs):
|
|
|
|
|
session = self.get_object()
|
2022-10-25 04:57:34 +00:00
|
|
|
|
local_path, url = get_session_replay_url(session)
|
2020-06-10 09:34:56 +00:00
|
|
|
|
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
|
|
|
|
|
|
2022-07-01 11:07:42 +00:00
|
|
|
|
def get_queryset(self):
|
2022-12-04 09:39:48 +00:00
|
|
|
|
queryset = super().get_queryset().prefetch_related('terminal') \
|
2022-07-01 11:07:42 +00:00
|
|
|
|
.annotate(terminal_display=F('terminal__name'))
|
|
|
|
|
return queryset
|
|
|
|
|
|
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)
|
|
|
|
|
|
|
|
|
|
|
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
|
2020-03-12 08:24:38 +00:00
|
|
|
|
download_cache_key = "SESSION_REPLAY_DOWNLOAD_{}"
|
2022-02-17 12:13:31 +00:00
|
|
|
|
session = None
|
|
|
|
|
rbac_perms = {
|
2022-02-23 07:47:12 +00:00
|
|
|
|
'create': 'terminal.upload_sessionreplay',
|
2022-03-15 03:33:38 +00:00
|
|
|
|
'retrieve': 'terminal.view_sessionreplay',
|
2022-02-17 12:13:31 +00:00
|
|
|
|
}
|
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']
|
2021-12-08 07:35:22 +00:00
|
|
|
|
# 兼容旧版本 API 未指定 version 为 2 的情况
|
|
|
|
|
version = serializer.validated_data.get('version', 2)
|
|
|
|
|
name, err = session.save_replay_to_storage_with_version(file, version)
|
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'
|
2021-12-08 07:35:22 +00:00
|
|
|
|
if url.endswith('.cast.gz'):
|
|
|
|
|
tp = 'asciicast'
|
2018-12-19 11:55:41 +00:00
|
|
|
|
|
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,
|
2022-12-04 09:39:48 +00:00
|
|
|
|
'system_user': session.account,
|
2020-03-12 08:24:38 +00:00
|
|
|
|
'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):
|
2022-02-17 12:13:31 +00:00
|
|
|
|
"""
|
|
|
|
|
监控用
|
|
|
|
|
"""
|
2020-04-07 04:26:47 +00:00
|
|
|
|
serializer_class = serializers.SessionJoinValidateSerializer
|
2022-02-17 12:13:31 +00:00
|
|
|
|
rbac_perms = {
|
|
|
|
|
'POST': 'terminal.validate_sessionactionperm'
|
|
|
|
|
}
|
2020-04-07 04:26:47 +00:00
|
|
|
|
|
|
|
|
|
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)
|
2022-02-17 12:13:31 +00:00
|
|
|
|
|
2020-04-07 04:26:47 +00:00
|
|
|
|
with tmp_to_org(session.org):
|
2021-12-29 12:07:56 +00:00
|
|
|
|
if is_session_approver(session_id, user_id):
|
|
|
|
|
return Response({'ok': True, 'msg': ''}, status=200)
|
|
|
|
|
|
2022-02-17 12:13:31 +00:00
|
|
|
|
if not user.has_perm('terminal.monitor_session'):
|
2020-04-07 04:26:47 +00:00
|
|
|
|
msg = _('User does not have permission')
|
|
|
|
|
return Response({'ok': False, 'msg': msg}, status=401)
|
|
|
|
|
|
|
|
|
|
return Response({'ok': True, 'msg': ''}, status=200)
|