Exemplo n.º 1
0
    def post(self, request, *args, **kwargs):
        req_data = request.data
        validated_data = request.validated_data
        _req_data = deepcopy(req_data)
        if "login_password" in req_data:
            _req_data["login_password"] = "******" * len(_req_data["login_password"])
        logger.info("Get a request: %s" % _req_data)

        # 在操作日志装饰器中已经做过一次校验
        # 校验是否传入了 action、zone、owner这三个必传参数
        # validator = RouterValidator(data=req_data)
        # if not validator.is_valid():
        #     return Response({"code": 1, "msg": validator.errors, "data": {}})

        # 校验action是否符合action校验器的规范
        action = validated_data["action"]
        _module, action, _action, err = get_module_from_action(action)
        if err is not None:
            resp = console_response(code=1, msg=_("The action is not valid"))
            return Response(resp, status=status.HTTP_200_OK)

        # 是否返回多个纪录值,如果是的话则需要校验传递的参数是否符合多传回值的校验规范
        many = validated_data.get("many", False)
        if many:
            many_validator = ManyObjectsValidator(data=req_data)
            if not many_validator.is_valid():
                resp = console_response(code=1, msg=_("many_validator.errors"))
                return Response(resp, status=status.HTTP_200_OK)

        # 尝试导入相应模块的views
        try:
            module = import_module("console.apps.%s.views" % _module, package=["*"])
        except ImportError as exp:
            resp = console_response(code=1, msg=_(exp.message))
            return Response(resp, status=status.HTTP_200_OK)

        # 判断相应的views里面是否实现了相应的action view类
        _view_class = getattr(module, _action, None)
        if _view_class is None:
            resp = console_response(code=1, msg=_("view class was not implemented"))
            return Response(resp, status=status.HTTP_200_OK)

        # 判断传入的owner是否是当前认证用户
        if getattr(request.user, "username", None) != req_data.get("owner") and not settings.DEBUG:
            return Response(console_response(code=1, msg="The owner is not the authenticated user"),
                            status=status.HTTP_200_OK)

        # 注入zone和owner信息到request, 方便调用
        request.zone = req_data.get("zone")
        request.owner = req_data.get("owner")

        # 调用相应模块的views的post方法
        _start = time.time()
        resp = _view_class().post(request, *args, **kwargs)
        _end = time.time()
        logger.info("Get Response: %s, cost:%f" % (resp.data, _end - _start))
        # add action
        resp.data["action"] = validated_data["action"]
        return resp
Exemplo n.º 2
0
 def post(self, request, *args, **kwargs):
     form = UnbindInstanceIpSerializer(data=request.data)
     if not form.is_valid():
         return Response(
             console_response(CommonErrorCode.PARAMETER_ERROR, form.errors))
     data = form.validated_data
     payload = Payload(request=request,
                       action='UnBindIP',
                       ip_id=data.get("ip_id"))
     resp = unbind_ip(payload.dumps())
     return Response(resp)
Exemplo n.º 3
0
 def post(self, request, *args, **kwargs):
     form = DescribeNoticeInfoValidator(data=request.data.get('data'))
     if not form.is_valid():
         return Response(
             console_response(CommonErrorCode.PARAMETER_ERROR, form.errors))
     data = form.validated_data
     payload = Payload(request=request,
                       action=self.action,
                       msgid=data.get('msgid'))
     resp = list_msg_info(payload.dumps())
     return Response(resp)
Exemplo n.º 4
0
    def post(self, request, *args, **kwargs):
        form = DescribeSafedogRiskOverviewSerializer(data=request.data)
        if not form.is_valid():
            return Response(console_response(CommonErrorCode.PARAMETER_ERROR,
                                             form.errors),
                            status=status.HTTP_200_OK)

        data = request.data
        owner = data.get('owner')
        zone = request.zone
        compute_resource = data.get('compute_resource')
        app_system_id = data.get('app_system_id')
        payload = {
            'owner': owner,
            'zone': zone,
            'compute_resource': compute_resource,
            'app_system_id': app_system_id
        }
        resp = describe_risk_overview(payload)
        return Response(console_response(total_count=len(resp), ret_set=resp))
Exemplo n.º 5
0
def create_msg(payload):
    title = payload.get('title')
    content = payload.get('content')
    notice_list = payload.get('notice_list')
    username = payload.get('author')
    zone = payload.get('zone')
    departments = []
    users = []
    for name in notice_list:
        if DepartmentService.is_department_exist(name):
            departments.append(name)
        elif User.objects.filter(username=name).exists():
            users.append(name)
    msg, excep = NoticeModel.objects.create(title, content, departments, users,
                                            username, zone)
    if excep is None:
        return console_response()
    else:
        error_mag = u"消息保存失败"
        return console_response(code=1, msg=error_mag)
Exemplo n.º 6
0
    def post(self, request, *args, **kwargs):
        validator = DescribePhysicalMachineHostnameListValidator(
            data=request.data)
        if not validator.is_valid():
            return Response(
                console_response(code=1,
                                 msg=get_serializer_error(validator.errors)))

        pool_name = validator.validated_data["pool_name"]
        vm_type = validator.validated_data["VM_type"]

        total_count, hostname_list = describe_physical_machine_hostname_list(
            pool_name=pool_name, vm_type=vm_type)
        if total_count == 0:
            return Response(console_response(ret_code=0))

        return Response(
            console_response(ret_code=0,
                             total_count=total_count,
                             ret_set=hostname_list))
Exemplo n.º 7
0
 def post(self, request, *args, **kwargs):
     form = AddJumperAuthorizationUserOrDetachSerializer(data=request.data)
     if not form.is_valid():
         return Response(console_response(code=1, msg=form.errors))
     data = form.validated_data
     authorization_user_payload = {
         "request": request,
         "data": data
     }
     authorization_user_resp = add_authorization_user_or_remove(authorization_user_payload)
     return Response(authorization_user_resp)
Exemplo n.º 8
0
def create_urllist(payload):
    """
    新建url白名单
    :param payload:
    :return:
    """
    smc_ip = payload.pop("smc_ip")
    smc_port = get_smc_info(only_port=True)
    waf_id = payload.pop("waf_id")
    payload["list_type"] = "whiteurl"
    iplist_code, iplist_msg = create_white_black_list(smc_ip, smc_port, waf_id, payload)
    if iplist_code:
        return console_response(code=1, msg=iplist_msg)
    domain = ".".join(waf_id[1:].split("-")[:-1])
    action_record = dict(
        domain=domain,
        matchtype=payload.get("matchtype"),
        url=payload.get("url")
    )
    return console_response(action_record=action_record)
Exemplo n.º 9
0
 def post(self, request, *args, **kwargs):
     form = AddHostAccountSerializer(data=request.data)
     if not form.is_valid():
         return Response(console_response(code=1, msg=form.errors))
     data = form.validated_data
     add_account_payload = {
         "request": request,
         "data": data
     }
     add_account_resp = add_account(add_account_payload)
     return Response(add_account_resp)
Exemplo n.º 10
0
 def post(self, request, *args, **kwargs):
     form = ChangeJumperAccountInfoSerializer(data=request.data)
     if not form.is_valid():
         return Response(console_response(code=1, msg=form.errors))
     data = form.validated_data
     change_account_payload = {
         "request": request,
         "data": data
     }
     change_account_resp = change_account(change_account_payload)
     return Response(change_account_resp)
Exemplo n.º 11
0
 def post(self, request, *args, **kwargs):
     form = ListJumperJoinedHostSerializer(data=request.data)
     if not form.is_valid():
         return Response(console_response(code=1, msg=form.errors))
     data = form.validated_data
     joined_hosts_payload = {
         "request": request,
         "data": data
     }
     joined_hosts = list_joined_host(joined_hosts_payload)
     return Response(joined_hosts)
Exemplo n.º 12
0
 def post(self, request, *args, **kwargs):
     form = WafBaseSerializer(data=request.data)
     if not form.is_valid():
         return Response(console_response(code=1, msg=form.errors))
     data = form.validated_data
     system_info_payload = {
         "smc_ip": data.get("smc_ip"),
         "waf_id": data.get("waf_id")
     }
     system_info_response = get_sys_info(system_info_payload)
     return Response(system_info_response)
Exemplo n.º 13
0
 def post(self, request, *args, **kwargs):
     form = WafBaseSerializer(data=request.data)
     if not form.is_valid():
         return Response(console_response(code=1, msg=form.errors))
     data = form.validated_data
     base_defend_payload = {
         "smc_ip": data.get("smc_ip"),
         "waf_id": data.get("waf_id")
     }
     base_defend_response = describe_base_defend(base_defend_payload)
     return Response(base_defend_response)
Exemplo n.º 14
0
def get_rds_iops_info(payload):
    rds_info = payload.get("rds_info")
    if rds_info:
        rds_iops_record = RdsIOPSModel.get_iops_by_flavor_and_volume_type(
            rds_info.get("volume_type"), rds_info.get("flavor_id"))
        rds_iops_collection = [rds_iops_record] if rds_iops_record else None
    else:
        rds_iops_queryset = RdsIOPSModel.objects.all()
        rds_iops_collection = rds_iops_queryset
    if not rds_iops_collection:
        return console_response(RdsErrorCode.QUERY_RDS_IOPS_INFO_FAILED)
    ret_set = []
    for rds_iops_record in rds_iops_collection:
        iops = {}
        iops.update({"iops": rds_iops_record.iops})
        iops.update({"flavor_id": rds_iops_record.flavor.flavor_id})
        iops.update({"volume_type": rds_iops_record.volume_type})
        ret_set.append(iops)

    return console_response(total_count=len(ret_set), ret_set=ret_set)
Exemplo n.º 15
0
 def post(self, request, *args, **kwargs):
     form = DetachJumperAuthorizationUserSerializer(data=request.data)
     if not form.is_valid():
         return Response(console_response(code=1, msg=form.errors))
     data = form.validated_data
     detach_user_payload = {
         "request": request,
         "data": data
     }
     detach_user_resp = detach_user(detach_user_payload)
     return Response(detach_user_resp)
Exemplo n.º 16
0
def create_cookie_rule(payload):
    """
    新建cookie规则
    :param payload:
    :return:
    """
    smc_ip = payload.pop("smc_ip")
    smc_port = get_smc_info(only_port=True)
    waf_id = payload.pop("waf_id")
    cookie_code, cookie_msg = create_waf_cookie(smc_ip, smc_port, waf_id, payload)
    if cookie_code:
        return console_response(code=1, msg=cookie_msg)
    domain = ".".join(waf_id[1:].split("-")[:-1])
    action_record = dict(
        domain=domain,
        matchtype=payload.get("matchtype"),
        url=payload.get("url"),
        httponly=payload.get("httponly")
    )
    return console_response(action_record=action_record)
Exemplo n.º 17
0
 def post(self, request, *args, **kwargs):
     form = ListJumperSessionHistorySerializer(data=request.data)
     if not form.is_valid():
         return Response(console_response(code=1, msg=form.errors))
     data = form.validated_data
     session_historys_payload = {
         "request": request,
         "data": data
     }
     session_historys_resp = list_session_history(session_historys_payload)
     return Response(session_historys_resp)
Exemplo n.º 18
0
    def post(self, request, *args, **kwargs):
        form = DeleteSubnetValidator(data=request.data)
        if not form.is_valid():
            return Response(console_response(code=1,
                                             ret_msg=get_serializer_error(
                                                 form.errors)),
                            status=status.HTTP_200_OK)

        subnet_list = request.data.get("subnet_list")
        for S in subnet_list:
            payload = {
                "owner": form.validated_data.get("owner"),
                "zone": form.validated_data.get("zone"),
                "name": S.get("name"),
                "subnet_id": S.get("subnet_id"),
                "network_id": S.get("network_id"),
            }

            resp = SubnetService.delete_subnet(request, payload)
        return Response(console_response())
Exemplo n.º 19
0
 def post(self, request, *args, **kwargs):
     form = PlayJumperSessionAddressSerianlizer(data=request.data)
     if not form.is_valid():
         return Response(console_response(code=1, msg=form.errors))
     data = form.validated_data
     session_play_payload = {
         "request": request,
         "data": data
     }
     session_play_resp = session_play_addr(session_play_payload)
     return Response(session_play_resp)
Exemplo n.º 20
0
def list_msgs(payload):
    zone = payload.get('zone')
    zone = ZoneModel.get_zone_by_name(zone)
    page_index = payload.get('page_index')
    page_size = payload.get('page_size')
    msgs = NoticeModel.objects.filter(zone=zone).all()
    total_count = len(msgs)
    msgs = msgs.order_by('-commit_time')[(page_index - 1) *
                                         page_size:page_index * page_size]
    data = DescribeNoticeSerializer(msgs, many=True).data
    return console_response(total_count=total_count, ret_set=data)
Exemplo n.º 21
0
 def post(self, request, *args, **kwargs):
     form = ShowJumperEventDetailSerializer(data=request.data)
     if not form.is_valid():
         return Response(console_response(code=1, msg=form.errors))
     data = form.validated_data
     event_detail_payload = {
         "request": request,
         "data": data
     }
     event_detail_resp = event_detail(event_detail_payload)
     return Response(event_detail_resp)
Exemplo n.º 22
0
    def post(self, request, *args, **kwargs):
        form = DescribePhysicalMachineIPMIAddrValidator(data=request.data)
        if not form.is_valid():
            return Response(
                console_response(code=1,
                                 msg=get_serializer_error(form.errors)))

        physical_machine_id = form.validated_data['physical_machine_id']
        resp = describe_physical_machine_IPMIAddr(id=physical_machine_id)

        return Response(resp)
Exemplo n.º 23
0
 def post(self, request, *args, **kwargs):
     form = ShowJumperHostAllSudoSerializer(data=request.data)
     if not form.is_valid():
         return Response(console_response(code=1, msg=form.errors))
     data = form.validated_data
     show_sudo_payload = {
         "request": request,
         "data": data
     }
     show_sudo_resp = show_all_sudo(show_sudo_payload)
     return Response(show_sudo_resp)
Exemplo n.º 24
0
    def post(self, request, *args, **kwargs):
        form = DescribeSafedogInstanceSerializer(data=request.data)
        if not form.is_valid():
            return Response(console_response(CommonErrorCode.PARAMETER_ERROR,
                                             form.errors),
                            status=status.HTTP_200_OK)

        data = request.data
        owner = data.get('owner')
        zone = request.zone
        instance_uuid = data.get('instance_uuid')
        risk_type = data.get('risk_type')
        payload = {
            'owner': owner,
            'zone': zone,
            'instance_uuid': instance_uuid,
            'risk_type': risk_type
        }
        resp = describe_safedog_instance(payload)
        return Response(console_response(total_count=len(resp), ret_set=resp))
Exemplo n.º 25
0
 def post(self, request, *args, **kwargs):
     form = ShowJumperSessionTypeSerializer(data=request.data)
     if not form.is_valid():
         return Response(console_response(code=1, msg=form.errors))
     data = form.validated_data
     show_session_type_payload = {
         "request": request,
         "data": data
     }
     show_session_type_resp = show_session_type(show_session_type_payload)
     return Response(show_session_type_resp)
Exemplo n.º 26
0
 def post(self, request, *args, **kwargs):
     data = request.data
     validator = DeleteRoutersSerializer(data=data)
     if not validator.is_valid():
         code, msg = console_code(validator)
         return Response(console_response(code=code, msg=msg),
                         status=status.HTTP_200_OK)
     routers = validator.validated_data.get("routers")
     payload = Payload(request=request, action=self.action, routers=routers)
     resp = delete_routers(payload.dumps())
     return Response(resp, status=status.HTTP_200_OK)
Exemplo n.º 27
0
 def post(self, request, *args, **kwargs):
     form = ListJumperHostEventSerializer(data=request.data)
     if not form.is_valid():
         return Response(console_response(code=1, msg=form.errors))
     data = form.validated_data
     list_event_payload = {
         "request": request,
         "data": data
     }
     list_event_resp = list_event_filter(list_event_payload)
     return Response(list_event_resp)
Exemplo n.º 28
0
def get_delete_diff(payload):
    code = 0
    msg = 'success'
    ids = payload.get('ids')
    cfg_type = payload.get('type')
    cfg_model = get_cfg_model_by_type(cfg_type)
    diffs = []
    if cfg_model:
        Serializer = get_serializer_by_model(cfg_model)
        for id in ids:
            ins = cfg_model.get_item_by_id(id)
            if ins:
                tmp = {
                    'id': id,
                    'cfg_before': Serializer(ins).data,
                    'cfg_after': {}
                }
                diffs.append(tmp)
        return console_response(code, msg, len(diffs), diffs)
    return console_response(1)
Exemplo n.º 29
0
def describe_basedetail(payload):
    """
    获取基础监控信息
    :param payload:
    :return:
    """
    smc_ip = payload.get("smc_ip")
    smc_port = get_smc_info(only_port=True)
    waf_id = payload.get("waf_id")
    basedetail_code, basedetail_msg = get_waf_base(smc_ip, smc_port, waf_id)
    if basedetail_code:
        return console_response(code=1, msg=basedetail_msg)
    data = basedetail_msg
    ret_set = dict(
        cpu_usage=data.get("cpu_usage"),
        memory_usage=data.get("memory_usage"),
        qps=data.get("qps"),
        conn_current=data.get("conn", {}).get("current", 0)
    )
    return console_response(ret_set=ret_set)
Exemplo n.º 30
0
 def list(cls, payload):
     data = payload.get('data')
     owner = data.get('owner')
     zone = data.get('zone')
     zone_model = ZoneModel.get_zone_by_name(zone)
     account = AccountService.get_by_owner(owner)
     jumper_instance_set = InstancesModel.get_instances_by_owner(
         owner, zone).filter(role="jumpserver", deleted=1, destroyed=0)
     jumper_detail_list, total_count = InstanceService.render_with_detail(
         jumper_instance_set, account, zone_model)
     return console_response(code=0, ret_set=jumper_detail_list)
Exemplo n.º 31
0
def create_rds_account(payload):
    rds_id = payload.get("rds_id")
    username = payload["username"]
    rds_record = RdsModel.get_rds_by_id(rds_id)
    resp = create_rds_account_api(payload, username, payload["password"],
                                  rds_record.uuid, payload["grant"])
    if resp["code"] != 0:
        logger.error("create_rds_account failed, {}".format(resp))
        # 910015 suggest that there's already an account with the same name
        if resp["code"] == 910015:
            return console_response(RdsErrorCode.RDS_ACCOUNT_AlREADY_EXIST)
        return console_response(RdsErrorCode.CREATE_RDS_ACCOUNT_FAILED,
                                msg="response of osapi: {}".format(resp))
    _, err = RdsAccountModel.objects.create(rds_id, username, payload["notes"])
    if err:
        logger.error("create_rds_account save to db failed, {}".format(err))
        return console_response(RdsErrorCode.SAVE_RDS_ACCOUNT_FAILED)
    ret_set = [{"rds_account": username}]
    return console_response(total_count=len(ret_set), ret_set=ret_set,
                            action_record={"account": username})