2018-11-23 02:25:35 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
#
|
|
|
|
import logging
|
|
|
|
from rest_framework.views import APIView, Response
|
|
|
|
from rest_framework_bulk import BulkModelViewSet
|
2021-12-29 12:07:56 +00:00
|
|
|
from rest_framework import status
|
|
|
|
from rest_framework.permissions import IsAuthenticated
|
2018-11-23 02:25:35 +00:00
|
|
|
|
|
|
|
from common.utils import get_object_or_none
|
2019-03-18 03:34:13 +00:00
|
|
|
from ..models import Session, Task
|
|
|
|
from .. import serializers
|
2021-12-29 12:07:56 +00:00
|
|
|
from terminal.utils import is_session_approver
|
|
|
|
from orgs.utils import tmp_to_root_org
|
2018-11-23 02:25:35 +00:00
|
|
|
|
2021-12-29 12:07:56 +00:00
|
|
|
__all__ = ['TaskViewSet', 'KillSessionAPI', 'KillSessionForTicketAPI']
|
2018-11-23 02:25:35 +00:00
|
|
|
logger = logging.getLogger(__file__)
|
|
|
|
|
|
|
|
|
|
|
|
class TaskViewSet(BulkModelViewSet):
|
|
|
|
queryset = Task.objects.all()
|
|
|
|
serializer_class = serializers.TaskSerializer
|
2021-10-22 06:27:54 +00:00
|
|
|
filterset_fields = ('is_finished',)
|
2018-11-23 02:25:35 +00:00
|
|
|
|
|
|
|
|
2021-12-29 12:07:56 +00:00
|
|
|
def kill_sessions(session_ids, user):
|
|
|
|
validated_session = []
|
|
|
|
|
|
|
|
for session_id in session_ids:
|
|
|
|
session = get_object_or_none(Session, id=session_id)
|
|
|
|
if session and not session.is_finished:
|
|
|
|
validated_session.append(session_id)
|
|
|
|
Task.objects.create(
|
|
|
|
name="kill_session", args=session.id, terminal=session.terminal,
|
|
|
|
kwargs={
|
|
|
|
'terminated_by': str(user)
|
|
|
|
}
|
|
|
|
)
|
|
|
|
return validated_session
|
|
|
|
|
|
|
|
|
2018-11-23 02:25:35 +00:00
|
|
|
class KillSessionAPI(APIView):
|
2022-02-17 12:13:31 +00:00
|
|
|
model = Task
|
|
|
|
rbac_perms = {
|
|
|
|
'POST': 'terminal.terminate_session'
|
|
|
|
}
|
2021-12-29 12:07:56 +00:00
|
|
|
|
2022-02-23 09:09:09 +00:00
|
|
|
def post(self, request, *args, **kwargs):
|
|
|
|
session_ids = request.data
|
|
|
|
validated_session = kill_sessions(session_ids, request.user)
|
|
|
|
return Response({"ok": validated_session})
|
|
|
|
|
2021-12-29 12:07:56 +00:00
|
|
|
|
|
|
|
class KillSessionForTicketAPI(APIView):
|
|
|
|
permission_classes = (IsAuthenticated, )
|
|
|
|
|
|
|
|
def post(self, request, *args, **kwargs):
|
|
|
|
session_ids = request.data
|
|
|
|
user_id = request.user.id
|
|
|
|
|
|
|
|
for session_id in session_ids:
|
|
|
|
if not is_session_approver(session_id, user_id):
|
|
|
|
return Response({}, status=status.HTTP_403_FORBIDDEN)
|
|
|
|
|
|
|
|
with tmp_to_root_org():
|
|
|
|
validated_session = kill_sessions(session_ids, request.user)
|
|
|
|
|
2018-11-23 02:25:35 +00:00
|
|
|
return Response({"ok": validated_session})
|