Exemplo n.º 1
0
    def get_info_list(cls, user_groups):

        try:
            ita_driver_obj_list = ItaDriver.objects.all()

        except Exception as e:
            # ここでの例外は大外で拾う
            raise

        protocol_dict = cls.get_define()['dict']
        permission_list = cls.get_permission(ita_driver_obj_list)
        editable_ids = cls.get_driver_ids(ita_driver_obj_list, user_groups, [
            defs.ALLOWED_MENTENANCE,
        ])
        ref_ids = cls.get_driver_ids(ita_driver_obj_list, user_groups,
                                     [defs.ALLOWED_MENTENANCE, defs.VIEW_ONLY])

        ita_driver_dto_list = []
        cipher = AESCipher(settings.AES_KEY)
        for ita_obj in ita_driver_obj_list:
            if ita_obj.ita_driver_id not in ref_ids:
                continue

            ita_info = ita_obj.__dict__
            ita_info['password'] = cipher.decrypt(ita_obj.password)
            ita_info['protocol_str'] = protocol_dict[ita_obj.protocol]
            ita_info[
                'editable'] = True if ita_obj.ita_driver_id in editable_ids else False
            ita_info['permission'] = permission_list[ita_obj.ita_driver_id] if ita_obj.ita_driver_id in permission_list else []
            ita_driver_dto_list.append(ita_info)

        return ita_driver_dto_list
Exemplo n.º 2
0
    def _protect(self):
        """
        [メソッド概要]
        Tablesシート全体の処理
        """
        # パスワードを取得して復号
        password = System.objects.get(config_id='PROTECTION_PW').value
        cipher = AESCipher(settings.AES_KEY)
        password = cipher.decrypt(password)

        # パスワードをセット
        self.tables_ws.protection.password = password
        self.example_ws.protection.password = password
        self.lists_ws.protection.password = password
        # シートを保護する
        self.tables_ws.protection.enable()
        self.example_ws.protection.enable()
        self.lists_ws.protection.enable()

        # 特定のセルの保護を解除
        self.tables_ws.protection.formatColumns = False
        self.tables_ws.protection.formatRows = False
        unprotection = Protection(locked=False, hidden=False)
        for c in range(1, 3 + self.len_condition + self.len_act):
            for r in range(12, 19):
                self.tables_ws.cell(row=r, column=c).protection = unprotection

        # 折り畳む
        self.tables_ws.row_dimensions.group(2, 10, hidden=True)
    def _get_system_confs(self):
        """
        [概要]
            AD認証に必要なシステム設定取得
        """

        self.__logger.logic_log('LOSI00001', os.path.abspath(__file__), sys._getframe().f_code.co_name, None)

        system_confs = System.objects.filter(category='ACTIVE_DIRECTORY').values('config_id', 'value')
        system_confs_dict = {key_value['config_id']: key_value['value'] for key_value in system_confs}

        # AccessPointのカンマ区切り文字列を、分割して配列化
        tmp_hosts = system_confs_dict['ACCESS_POINT']
        hosts = [host_str.strip() for host_str in tmp_hosts.split(',')]
        system_confs_dict['hosts'] = hosts

        # Group情報の文字列をkey-value化
        tmp_groups = system_confs_dict['TARGET_GROUP_LIST']
        groups_list = ast.literal_eval(tmp_groups)
        groups_dict = {}
        for g in groups_list:
            groups_dict.update(g)

        system_confs_dict['groups'] = groups_dict

        # パスワードの暗号化解除
        cipher = AESCipher(settings.AES_KEY)
        tmp_password = system_confs_dict['ADMINISTRATOR_PW']
        system_confs_dict['ADMINISTRATOR_PW'] = cipher.decrypt(tmp_password)

        self.__logger.logic_log('LOSI00002', '')
        return system_confs_dict
Exemplo n.º 4
0
    def __init__(self, request_rec):
        """
        Zabbix API インスタンスを返す
        [引数]
          request_rec: 対象ZABBIX監視マスタレコード
        """

        self.request_id = 1
        self.host = request_rec.hostname
        self.protocol = request_rec.protocol
        self.port = request_rec.port
        self.auth_token = None

        req_pw = request_rec.password
        cipher = AESCipher(settings.AES_KEY)
        decrypted_password = cipher.decrypt(req_pw)

        try:
            result = self._request('user.login', {
                'user': request_rec.username,
                'password': decrypted_password
            })

        except Exception as e:
            # ログインできなかった場合は上位で処理
            logger.system_log('LOSM25000', 'Zabbix Login error.')
            raise

        if self._has_error(result):
            logger.system_log('LOSM25000', 'GetResponse error.')
            raise Exception('login response has an error')

        self.auth_token = result.get('result')
Exemplo n.º 5
0
    def get_info_list(self, request):

        protocol_dict = self.get_define()['dict']
        rule_type_data_obj_dict = get_rule_type_data_obj_dict(request)

        try:
            zabbix_adapter_obj_list = ZabbixAdapter.objects.filter(
                rule_type_id__in=rule_type_data_obj_dict.keys())
        except Exception as e:
            # ここでの例外は大外で拾う
            raise

        zabbix_adapter_dto_list = []
        cipher = AESCipher(settings.AES_KEY)
        for zabbix_obj in zabbix_adapter_obj_list:
            zabbix_info = zabbix_obj.__dict__
            if zabbix_obj.password:
                zabbix_info['password'] = cipher.decrypt(zabbix_obj.password)
                zabbix_info['protocol_str'] = protocol_dict[
                    zabbix_obj.protocol]

            zabbix_info['editable'] = rule_type_data_obj_dict[
                zabbix_obj.rule_type_id]['editable']
            zabbix_info['active'] = rule_type_data_obj_dict[
                zabbix_obj.rule_type_id]['active']

            if zabbix_info['active']:
                zabbix_info['rule_type_name'] = rule_type_data_obj_dict[
                    zabbix_obj.rule_type_id]['rule_type_name']

                zmi_list = []
                # 突合情報取得
                try:
                    zmi_list = list(
                        ZabbixMatchInfo.objects.filter(
                            zabbix_adapter_id=zabbix_obj.zabbix_adapter_id).
                        values('data_object_id', 'zabbix_response_key'))
                except Exception as e:
                    # ここでの例外は大外で拾う
                    raise

                zabbix_info['match_list'] = {
                    str(match_info['data_object_id']):
                    match_info['zabbix_response_key']
                    for match_info in zmi_list
                }

            else:
                zabbix_info['rule_type_id'] = -1
                zabbix_info['rule_type_name'] = ""
                zabbix_info['match_list'] = {}

            zabbix_adapter_dto_list.append(zabbix_info)

        return zabbix_adapter_dto_list
Exemplo n.º 6
0
    def set_ary_ita_config(self):
        """
        ary_ita_configの設定
        """
        cipher = AESCipher(settings.AES_KEY)
        password = cipher.decrypt(self.ita_driver.password)

        self.ary_ita_config['Protocol'] = self.ita_driver.protocol
        self.ary_ita_config['Host'] = self.ita_driver.hostname
        self.ary_ita_config['PortNo'] = self.ita_driver.port
        self.ary_ita_config['user'] = self.ita_driver.username
        self.ary_ita_config['password'] = password
        self.ary_ita_config['menuID'] = '2100000303'
Exemplo n.º 7
0
def setup_data_action():
    """
    テストデータのリセット
    """

    delete_data_action_stop()

    module = import_module('web_app.models.ITA_models')
    ItaDriver = getattr(module, 'ItaDriver')

    encryptpassword = AESCipher(settings.AES_KEY).encrypt('pytest')
    ita_driver = ItaDriver(
        ita_disp_name='ITA176',
        protocol='https',
        hostname='pytest-host-name',
        port='443',
        username='******',
        password=encryptpassword,
        last_update_timestamp=datetime.datetime.now(pytz.timezone('UTC')),
        last_update_user='******',
    ).save(force_insert=True)

    yield

    delete_data_action_stop()
Exemplo n.º 8
0
def set_data_ita_driver_conductor(ita_disp_name):
    """
    ITAへの確認機能のテストに必要なデータをDBに登録
    """
    module = import_module('web_app.models.ITA_models')
    ItaDriver = getattr(module, 'ItaDriver')
    ItaActionHistory = getattr(module, 'ItaActionHistory')

    # パスワードを暗号化
    cipher = AESCipher(settings.AES_KEY)

    now = datetime.datetime.now(pytz.timezone('UTC'))
    encrypted_password = cipher.encrypt('pytest')
    url = 'https://pytest-host-name:443/'

    try:
        with transaction.atomic():

            # ITAアクションマスタ
            ItaDriver(ita_disp_name=ita_disp_name,
                      protocol='https',
                      hostname='pytest-host-name',
                      port='443',
                      username='******',
                      password=encrypted_password,
                      last_update_user='******',
                      last_update_timestamp=now).save(force_insert=True)

            ItaActionHistory(ita_action_his_id=1,
                             action_his_id=1,
                             ita_disp_name=ita_disp_name,
                             symphony_instance_no=None,
                             symphony_class_id=None,
                             conductor_instance_no=1,
                             conductor_class_id=1,
                             operation_id=1,
                             symphony_workflow_confirm_url='',
                             conductor_workflow_confirm_url=url,
                             restapi_error_info=None,
                             parameter_item_info='info_test',
                             last_update_timestamp=now,
                             last_update_user='******').save(force_insert=True)

    except Exception as e:
        print(e)
Exemplo n.º 9
0
    def get_info_list(cls):

        try:
            ita_driver_obj_list = ItaDriver.objects.all()

        except Exception as e:
            # ここでの例外は大外で拾う
            raise

        protocol_dict = cls.get_define()['dict']
        ita_driver_dto_list = []
        cipher = AESCipher(settings.AES_KEY)
        for ita_obj in ita_driver_obj_list:
            ita_info = ita_obj.__dict__
            ita_info['password'] = cipher.decrypt(ita_obj.password)
            ita_info['protocol_str'] = protocol_dict[ita_obj.protocol]

            ita_driver_dto_list.append(ita_info)

        return ita_driver_dto_list
Exemplo n.º 10
0
    def __init__(self, drv_info, user_name, now=None):
        """
        [概要]
        コンストラクタ
        [引数]
        drv_info : dict : ITAアクション設定
        """

        cipher = AESCipher(settings.AES_KEY)

        self.now = now if now else datetime.datetime.now()
        self.user_name = user_name
        self.drv_id = drv_info['ita_driver_id']
        self.ita_config = {}
        self.ita_config['Protocol'] = drv_info['protocol']
        self.ita_config['Host'] = drv_info['hostname']
        self.ita_config['PortNo'] = drv_info['port']
        self.ita_config['user'] = drv_info['username']
        self.ita_config['password'] = cipher.decrypt(drv_info['password'])
        self.ita_config['menuID'] = ''
        self.ita_core = ITA1Core('TOS_Backyard_ParameterSheetMenuManager', 0, 0, 0)
Exemplo n.º 11
0
    def get_info_list(cls):

        try:
            mail_driver_obj_list = MailDriver.objects.all()

        except Exception as e:
            # ここでの例外は大外で拾う
            raise

        protocol_dict = cls.get_define()['dict']
        mail_driver_dto_list = []
        cipher = AESCipher(settings.AES_KEY)
        for mail_obj in mail_driver_obj_list:
            mail_info = mail_obj.__dict__
            if mail_obj.password:
                mail_info['password'] = cipher.decrypt(mail_obj.password)
            mail_info['protocol_str'] = protocol_dict[mail_obj.protocol]

            mail_driver_dto_list.append(mail_info)

        return mail_driver_dto_list
Exemplo n.º 12
0
    def update(self, rq, request):
        """
        [メソッド概要]
          DB更新処理
        """
        logger.logic_log('LOSI00001', 'None', request=request)
        lang = request.user.get_lang_mode()

        error_flag = False
        error_msg = {
            'zabbix_disp_name': '',
            'protocol': '',
            'hostname': '',
            'port': '',
            'username': '',
            'password': '',
            'rule_type_id': '',
            'match_list': '',
        }
        now = datetime.datetime.now(pytz.timezone('UTC'))

        # 成功時データ
        response = {
            "status": "success",
        }

        try:
            zabbix_adapter_id = rq['zabbix_adapter_id']
            # 更新または削除の時は更新前にレコードロック
            ZabbixAdapter.objects.select_for_update().get(pk=zabbix_adapter_id)

            #入力チェック
            error_flag = self._validate(rq, error_msg, request, 'edit')

            if error_flag:
                raise UserWarning('validation error.')

            # パスワードを暗号化
            cipher = AESCipher(settings.AES_KEY)
            encrypted_password = cipher.encrypt(rq['password'])

            # ZABBIXアダプタの更新
            adapter = ZabbixAdapter.objects.get(pk=zabbix_adapter_id)
            adapter.zabbix_disp_name = rq['zabbix_disp_name']
            adapter.hostname = rq['hostname']
            adapter.username = rq['username']
            adapter.password = encrypted_password
            adapter.protocol = rq['protocol']
            adapter.port = rq['port']
            adapter.rule_type_id = rq['rule_type_id']
            adapter.last_update_user = request.user.user_name
            adapter.last_update_timestamp = now
            adapter.save(force_update=True)

            # 変更の有無にかかわらず既存のZABBIX突合情報の削除
            ZabbixMatchInfo.objects.filter(
                zabbix_adapter_id=zabbix_adapter_id).delete()

            # ZABBIX突合情報の保存
            create_match_list = []
            for data_object_id, zabbix_response_key in rq['match_list'].items(
            ):
                match = ZabbixMatchInfo(
                    zabbix_adapter_id=zabbix_adapter_id,
                    data_object_id=data_object_id,
                    zabbix_response_key=zabbix_response_key,
                    last_update_user=request.user.user_name,
                    last_update_timestamp=now,
                )

                create_match_list.append(match)

            ZabbixMatchInfo.objects.bulk_create(create_match_list)

        except ZabbixAdapter.DoesNotExist:
            logger.logic_log('LOSM07006',
                             "zabbix_adapter_id",
                             zabbix_adapter_id,
                             request=request)
            response = {
                'status': 'deleted',
                'msg': get_message('MOSJA26127', lang),
            }

        except Exception as e:
            logger.logic_log('LOSI00005',
                             traceback.format_exc(),
                             request=request)
            response = {
                'status': 'failure',
                'msg': error_msg,  # エラー詳細(エラーアイコンで出す)
            }

        logger.logic_log('LOSI00002',
                         'response=%s' % response,
                         request=request)

        return response
def set_data():
    """
    テストに必要なデータをDBに登録
    """
    now = datetime.datetime.now(pytz.timezone('UTC'))
    module = import_module('web_app.models.ZABBIX_monitoring_models')
    ZabbixAdapter           = getattr(module, 'ZabbixAdapter')
    ZabbixMatchInfo         = getattr(module, 'ZabbixMatchInfo')

    try:
        with transaction.atomic():

            # テスト用DT作成
            rule_type = RuleType(
                rule_type_name              = 'ZABBIX_TEST用',
                summary                     = '',
                rule_table_name             = 'zabbixtest',
                generation_limit            = 3,
                group_id                    = 'com.oase',
                artifact_id                 = 'zabbix',
                container_id_prefix_staging = 'testzabbix',
                container_id_prefix_product = 'prodzabbix',
                label_count                 = '2',
                last_update_timestamp       = now,
                last_update_user            = '******'
            )
            rule_type.save(force_insert=True)

            # テスト用ラベル作衛
            label0 = DataObject(
                rule_type_id              = rule_type.rule_type_id,
                conditional_name          = 'トリガーID',
                label                     = 'label0',
                conditional_expression_id = 1,
                last_update_timestamp     = now,
                last_update_user          = '******'
            )
            label0.save(force_insert=True)

            label1 = DataObject(
                rule_type_id              = rule_type.rule_type_id,
                conditional_name          = '説明',
                label                     = 'label1',
                conditional_expression_id = 2,
                last_update_timestamp     = now,
                last_update_user          = '******'
            )
            label1.save(force_insert=True)

            # テスト用ZABBIX監視アダプタ作成
            zabbix = ZabbixAdapter(
                zabbix_disp_name          = 'ZABBIX',
                hostname                  = 'pytest-host',
                username                  = '******',
                password                  = AESCipher(settings.AES_KEY).encrypt('pytest'),
                protocol                  = 'http',
                port                      = 80,
                rule_type_id              = rule_type.rule_type_id,
                last_update_timestamp     = now,
                last_update_user          = '******'
            
            )
            zabbix.save(force_insert=True)

            # テスト用ZABBIX突合情報作成
            match1 = ZabbixMatchInfo(
                zabbix_adapter_id         = zabbix.zabbix_adapter_id,
                data_object_id            = label0.data_object_id,
                zabbix_response_key       = 'triggerid',
                last_update_timestamp     = now,
                last_update_user          = '******'
            )
            match1.save(force_insert=True)

            match2 = ZabbixMatchInfo(
                zabbix_adapter_id         = zabbix.zabbix_adapter_id,
                data_object_id            = label1.data_object_id,
                zabbix_response_key       = 'description',
                last_update_timestamp     = now,
                last_update_user          = '******'
            )
            match2.save(force_insert=True)

            return rule_type.rule_type_id, zabbix.zabbix_adapter_id

    except Exception as e:
        print(e)
Exemplo n.º 14
0
    def modify(self, json_str, request):
        """
        [メソッド概要]
          グループのDB更新処理
        """

        logger.logic_log('LOSI00001', 'None', request=request)

        error_flag = False
        error_msg = {
            'mail_disp_name': '',
            'protocol': '',
            'smtp_server': '',
            'port': '',
            'user': '',
            'password': '',
        }
        now = datetime.datetime.now(pytz.timezone('UTC'))
        emo_chk = UnicodeCheck()
        # 成功時データ
        response = {
            "status": "success",
        }

        try:
            rq = json_str['json_str']
            ope = int(rq['ope'])
            #削除以外の場合の入力チェック
            if ope != defs.DABASE_OPECODE.OPE_DELETE:
                error_flag = self._validate(rq, error_msg, request)
            if error_flag:
                raise UserWarning('validation error.')

            # パスワードを暗号化 空なら空文字
            cipher = AESCipher(settings.AES_KEY)

            if ope == defs.DABASE_OPECODE.OPE_UPDATE:
                encrypted_password = cipher.encrypt(
                    rq['password']) if rq['password'] else ''

                driver_info_mod = MailDriver.objects.get(
                    mail_driver_id=rq['mail_driver_id'])
                driver_info_mod.mail_disp_name = rq['mail_disp_name']
                driver_info_mod.protocol = rq['protocol']
                driver_info_mod.smtp_server = rq['smtp_server']
                driver_info_mod.port = rq['port']
                driver_info_mod.user = rq['user']
                driver_info_mod.password = encrypted_password
                driver_info_mod.last_update_user = request.user.user_name
                driver_info_mod.last_update_timestamp = now
                driver_info_mod.save(force_update=True)

            elif ope == defs.DABASE_OPECODE.OPE_DELETE:
                MailDriver.objects.filter(pk=rq['mail_driver_id']).delete()

            elif ope == defs.DABASE_OPECODE.OPE_INSERT:
                encrypted_password = cipher.encrypt(
                    rq['password']) if rq['password'] else ''

                driver_info_reg = MailDriver(
                    mail_disp_name=rq['mail_disp_name'],
                    protocol=rq['protocol'],
                    smtp_server=rq['smtp_server'],
                    port=rq['port'],
                    user=rq['user'],
                    password=encrypted_password,
                    last_update_user=request.user.user_name,
                    last_update_timestamp=now).save(force_insert=True)

        except MailDriver.DoesNotExist:
            logger.logic_log('LOSM07006',
                             "mail_driver_id",
                             mail_driver_id,
                             request=request)

        except Exception as e:
            logger.logic_log('LOSI00005',
                             traceback.format_exc(),
                             request=request)
            response = {
                'status': 'failure',
                'error_msg': error_msg,  # エラー詳細(エラーアイコンで出す)
            }

        logger.logic_log('LOSI00002',
                         'response=%s' % response,
                         request=request)

        return response
Exemplo n.º 15
0
def edit(request):
    """
    [メソッド概要]
      システム設定ページの一覧画面
    """

    logger.logic_log('LOSI00001', 'None', request=request)

    msg = ''
    system_log_list = []
    system_session_list = []
    system_password_list = []
    system_actdir_list = []
    system_targro_list = []
    output_flag = 0
    pass_flag = 0

    permission_type = request.user_config.get_menu_auth_type(MENU_ID)
    edit = True if permission_type == defs.ALLOWED_MENTENANCE else False

    try:
        # システム設定情報取得
        system_list = System.objects.filter(
            maintenance_flag='1').order_by('item_id')

        # システム設定情報作成
        for s in system_list:

            system_info = {
                'item_id': s.item_id,
                'config_name': s.config_name,
                'category': s.category,
                'config_id': s.config_id,
                'value': s.value,
                'maintenance_flag': s.maintenance_flag,
            }

            if s.category == "LOG_STORAGE_PERIOD":
                system_log_list.append(system_info)

            elif s.category == "SESSION_TIMEOUT":
                system_session_list.append(system_info)

            elif s.category == "PASSWORD":
                system_password_list.append(system_info)

            elif s.category == "ACTIVE_DIRECTORY":

                if s.config_id == "TARGET_GROUP_LIST" and s.value:
                    system_targro_list = ast.literal_eval(s.value)

                # パスワード復号化
                if s.config_id == "ADMINISTRATOR_PW" and s.value is not None and len(
                        s.value) > 0:
                    cipher = AESCipher(settings.AES_KEY)
                    s.value = cipher.decrypt(s.value)

                # 復号化されたパスワードに更新
                system_info['value'] = s.value
                system_actdir_list.append(system_info)

                if s.config_id == "ADCOLLABORATION" and s.value == '1':
                    output_flag = 1

                    if request.user.user_id not in (1, -2140000000):
                        pass_flag = 1

    except:
        msg = get_message('MOSJA22016', request.user.get_lang_mode())
        logger.logic_log('LOSI00005', traceback.format_exc(), request=request)
        logger.system_log('LOSM09001', request=request)

    data = {
        'mainmenu_list': request.user_config.get_menu_list(),
        'user_name': request.user.user_name,
        'msg': msg,
        'edit': edit,
        'system_log_list': system_log_list,
        'system_session_list': system_session_list,
        'system_password_list': system_password_list,
        'system_actdir_list': system_actdir_list,
        'system_targro_list': system_targro_list,
        'output_flag': output_flag,
        'pass_flag': pass_flag,
        'disabled_flag': settings.DISABLE_WHITE_BLACK_LIST,
        'lang_mode': request.user.get_lang_mode(),
    }

    logger.logic_log('LOSI00002',
                     'msg:%s, edit:%s, output:%s, pass:%s' %
                     (msg, edit, output_flag, pass_flag),
                     request=request)

    return render(request, 'system/system_conf_edit.html', data)
Exemplo n.º 16
0
def modify(request):
    """
    [メソッド概要]
      システム設定のDB更新処理
    """

    logger.logic_log('LOSI00001', '[before_analyze_args]', request=request)

    no_output_ids = [
        'ADMINISTRATOR_PW',
    ]

    msg = {}
    error_txt = ''
    error_flag = False
    cipher = AESCipher(settings.AES_KEY)

    adlinkage_new = ''
    adlinkage_old = ''
    adlinkage_flg = 0

    try:
        with transaction.atomic():
            json_str = request.POST.get('json_str', None)
            if json_str is None:
                msg['alertMsg'] = get_message('MOSJA22014',
                                              request.user.get_lang_mode())
                logger.user_log('LOSM09002', request=request)
                raise Exception()

            json_str = json.loads(json_str)
            if 'json_str' not in json_str:
                msg['alertMsg'] = get_message('MOSJA22014',
                                              request.user.get_lang_mode())
                logger.user_log('LOSM09002', request=request)
                raise Exception()

            for data in json_str['json_str']:
                logger.logic_log(
                    'LOSI00003',
                    'id:%s, config_id:%s, val:%s' %
                    (data['item_id'], data['config_id'],
                     data['value'] if data['config_id'] not in no_output_ids
                     else len(data['value'])),
                    request=request)

            model_serializer = SystemSerializer()

            for data in json_str['json_str']:
                try:
                    model_serializer.validate(data)
                except serializers.ValidationError as e:
                    if data['config_id'] == "TARGET_GROUP_LIST":
                        targetlist = {}
                        for d in e.detail:
                            targetlist[d] = e.detail[d]

                        msg[data['config_id']] = targetlist
                    else:
                        for d in e.detail:
                            msg[data['config_id']] = str(d)

            if len(msg) > 0:
                logger.user_log('LOSM09003', error_txt, request=request)
                raise Exception()

            item_id_info = {
            }  #{ item_id : {'value'} } item_idをkeyにvalueを辞書型で格納
            # 更新データを取得
            for rq in json_str['json_str']:
                item_id_info[rq['item_id']] = rq[
                    'value']  #item_idをkeyにvalueを格納

            # 更新データをまとめてロック
            System.objects.select_for_update().filter(
                item_id__in=list(item_id_info.keys()))

            #更新処理
            for key, value in sorted(item_id_info.items()):  #item_idで昇順にソート
                system_data = System.objects.get(item_id=key)

                if system_data.maintenance_flag <= 0:
                    logger.user_log('LOSM09008',
                                    system_data.config_id,
                                    system_data.maintenance_flag,
                                    request=request)
                    msg['alertMsg'] = get_message('MOSJA22014',
                                                  request.user.get_lang_mode())
                    raise Exception()

                if system_data.value != value:

                    # 「メール通知種別:ログインID指定」のとき「既存のログインID」か確認
                    if system_data.config_id == 'NOTIFICATION_DESTINATION':
                        if value != "":
                            # フォームの入力値「input_login_list」を取得
                            input_login = value.split(',')
                            input_login_list = list(set(input_login))
                            if 'administrator' in input_login_list:
                                input_login_list.remove('administrator')
                            # DBの値「db_login_id_list」を取得(マイナスユーザを除く)
                            db_data = User.objects.values_list(
                                'user_id', 'login_id')
                            db_login_id_list = []
                            for data in db_data:
                                if data[0] > 1:
                                    db_login_id_list.append(data[1])
                            # ログインIDの登録
                            login_id_lists = []
                            error_ids = []
                            for input_login_id in input_login_list:
                                if input_login_id not in db_login_id_list:
                                    error_ids.append(input_login_id)
                                else:
                                    login_id_lists.append(str(input_login_id))
                            if len(error_ids) != 0:
                                msg['NOTIFICATION_DESTINATION'] = get_message(
                                    'MOSJA22036',
                                    request.user.get_lang_mode(),
                                    ids=error_ids)
                                logger.user_log('LOSM09007',
                                                error_ids,
                                                request=request)
                                raise Exception('validation error.')
                            value = ','.join(login_id_lists)

                    if system_data.config_id == 'ADMINISTRATOR_PW':

                        if len(value) > 64:
                            msg['ADMINISTRATOR_PW'] = get_message(
                                'MOSJA22007',
                                request.user.get_lang_mode(),
                                strConName=system_data.config_name)
                            logger.user_log(
                                'LOSM09003',
                                '%s: length %s' %
                                (system_data.config_name, len(value)),
                                request=request)
                            raise Exception('validation error.')

                        value = cipher.encrypt(value)

                    if system_data.config_id == 'AD_LINKAGE_TIMER':
                        adlinkage_old = system_data.value
                        adlinkage_new = value

                    if system_data.config_id == 'TARGET_GROUP_LIST':
                        keylist = []
                        vallist = []
                        targetlist = {}

                        for i in range(len(value)):

                            if list(value[i].keys()) not in keylist:
                                keylist.append(list(value[i].keys()))
                            else:
                                targetlist[i * 2] = get_message(
                                    'MOSJA22024',
                                    request.user.get_lang_mode(),
                                    key=list(value[i].keys()))
                                msg['TARGET_GROUP_LIST'] = targetlist
                                logger.user_log('LOSM09004', request=request)

                            if list(value[i].values()) not in vallist:
                                vallist.append(list(value[i].values()))
                            else:
                                targetlist[i * 2 + 1] = get_message(
                                    'MOSJA22024',
                                    request.user.get_lang_mode(),
                                    key=list(value[i].keys()))
                                msg['TARGET_GROUP_LIST'] = targetlist
                                logger.user_log('LOSM09005', request=request)

                        if len(msg) > 0:
                            raise Exception('validation error.')

                    if system_data.config_id == 'ADCOLLABORATION' and system_data.value == '0' and value == '1':
                        adlinkage_flg = 2  # 2:AD連携実施

                    if system_data.config_id == 'ADCOLLABORATION' and system_data.value == '1' and value == '0':
                        ad_key_list = [
                            'ADMINISTRATOR_USER', 'ADMINISTRATOR_PW',
                            'ACCESS_POINT', 'AD_LINKAGE_TIMER',
                            'CONNECTION_TIMEOUT', 'READ_TIMEOUT',
                            'AUTHSERVER_SEARCH_CHAR', 'TARGET_GROUP_LIST'
                        ]
                        for ad_key in ad_key_list:
                            adcollabo_date = System.objects.get(
                                config_id=ad_key)

                            if adcollabo_date.config_id == 'AD_LINKAGE_TIMER':
                                adlinkage_old = adcollabo_date.value

                            if adcollabo_date.config_id == 'CONNECTION_TIMEOUT' or adcollabo_date.config_id == 'READ_TIMEOUT':
                                adcollabo_date.value = '30'

                            else:
                                adcollabo_date.value = ''

                            adcollabo_date.last_update_user = request.user.user_name
                            adcollabo_date.last_update_timestamp = datetime.datetime.now(
                                pytz.timezone('UTC'))
                            adcollabo_date.save()

                        adlinkage_flg = 1  # 1:AD連携解除
                        adlinkage_new = ''

                    system_data.value = value
                    system_data.last_update_user = request.user.user_name
                    system_data.last_update_timestamp = datetime.datetime.now(
                        pytz.timezone('UTC'))
                    system_data.save()

                    # 同一パスワード設定不可世代数変更時処理
                    if system_data.config_id == 'Pass_generate_manage':
                        password_generation = int(value)
                        user_list = User.objects.select_for_update().filter(
                            disuse_flag='0')

                        for user in user_list:
                            uid = user.user_id
                            pw_history_list = PasswordHistory.objects.filter(
                                user_id=uid).order_by('last_update_timestamp')
                            pw_history_list_length = len(pw_history_list)

                            if password_generation < pw_history_list_length:
                                # パスワード履歴の削除
                                del_count = pw_history_list_length - password_generation
                                loop_count = 0

                                for pw_history in pw_history_list:
                                    if loop_count < del_count:
                                        pw_history.delete()
                                        loop_count += 1
                                    else:
                                        break

            # AD連携タイマー設定
            if adlinkage_new != adlinkage_old and getattr(
                    settings, 'EVTIMER_SERVER', None):
                try:
                    if adlinkage_new:
                        adlinkage_new = adlinkage_new.replace(',', '_')
                    else:
                        adlinkage_new = 'None'
                    query = urllib.parse.quote(adlinkage_new)
                    url = settings.EVTIMER_SERVER['path'] % (
                        settings.EVTIMER_SERVER['type'], 'AD_LINKAGE_TIMER',
                        query)
                    url = '%s//%s/%s' % (settings.EVTIMER_SERVER['protocol'],
                                         settings.EVTIMER_SERVER['location'],
                                         url)

                    te_req = urllib.request.Request(url)
                    with urllib.request.urlopen(te_req) as te_resp:
                        logger.logic_log('LOSI09001',
                                         te_resp.status,
                                         request=request)

                except urllib.error.HTTPError as e:
                    msg['alertMsg'] = get_message('MOSJA22030',
                                                  request.user.get_lang_mode())
                    logger.system_log('LOSM09006', e.code, request=request)
                    raise Exception()

                except urllib.error.URLError as e:
                    msg['alertMsg'] = get_message('MOSJA22030',
                                                  request.user.get_lang_mode())
                    logger.system_log('LOSM09006', e.reason, request=request)
                    raise Exception()

                except Exception as e:
                    msg['alertMsg'] = get_message('MOSJA22030',
                                                  request.user.get_lang_mode())
                    raise Exception()

    except Exception as e:
        if 'validation error.' != str(e):
            logger.logic_log('LOSM00001',
                             traceback.format_exc(),
                             request=request)
        error_flag = True
        adlinkage_flg = 0
        logger.system_log('LOSM09006', traceback.format_exc(), request=request)

    # 結果レスポンス
    response_data = {}

    # 異常処理
    if error_flag == True:
        response_data['status'] = 'failure'
        response_data['error_msg'] = msg
        response_data['error_txt'] = error_txt
    # 正常処理
    else:
        response_data['status'] = 'success'
        response_data['adflg'] = adlinkage_flg

    response_data['redirect_url'] = reverse('web_app:system:system_conf')

    response_json = json.dumps(response_data, ensure_ascii=False)

    logger.logic_log('LOSI00002',
                     'response_data: %s' % response_json,
                     request=request)

    return HttpResponse(response_json, content_type="application/json")
Exemplo n.º 17
0
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""
[概要]
    RabbitMQ共通処理クラス 格納
"""

import pika
from django.conf import settings
from web_app.models.models import System
from libs.commonlibs.aes_cipher import AESCipher

cipher = AESCipher(settings.AES_KEY)


class RabbitMQ:
    @classmethod
    def settings(cls):
        """
        [概要]
          RabbitMQ設定情報読み込みメソッド
        """
        settings = {}
        rset = list(
            System.objects.filter(category='RABBITMQ').values(
                'config_id', 'value'))
        for r in rset:
            if r['config_id'] == 'MQ_USER_ID':
Exemplo n.º 18
0
from libs.commonlibs.define import *
from libs.commonlibs.dt_component import DecisionTableComponent
from libs.commonlibs.aes_cipher import AESCipher
from libs.webcommonlibs.oase_mail import OASEMailSMTP, OASEMailUnknownEventNotify

urllib3.disable_warnings(InsecureRequestWarning)
ssl._create_default_https_context = ssl._create_unverified_context

# --------------------------------
# コンフィグファイル読み込み設定
# --------------------------------
rset = list(
    System.objects.filter(category='DMSETTINGS').values('config_id', 'value'))
dmconf = {r['config_id']: r['value'] for r in rset}
# パスワードを復号
cipher = AESCipher(settings.AES_KEY)
dmconf['DM_PASSWD'] = cipher.decrypt(dmconf['DM_PASSWD'])

# --------------------------------
# 負荷テスト設定
# --------------------------------
ENABLE_LOAD_TEST = getattr(settings, 'ENABLE_LOAD_TEST', False)
if ENABLE_LOAD_TEST:
    import logging
    loadtest_logger = logging.getLogger('oase_agent')

#ホスト名 コンフィグファイルに移動すべきか?
MAX_WORKER = 5


class ActUtil:
Exemplo n.º 19
0
    def _validate(self, rq, error_msg, request, mode):
        """
        [概要]
        入力チェック
        [引数]
        rq: dict リクエストされた入力データ
        error_msg: dict
        [戻り値]
        """

        logger.logic_log('LOSI00001',
                         'data: %s, error_msg:%s' % (rq, error_msg))
        error_flag = False
        emo_chk = UnicodeCheck()
        emo_flag_zabbix_disp_name = False
        emo_flag_hostname = False
        rule_type_id_error_flag = False
        lang = request.user.get_lang_mode()

        # zabbix_disp_name未入力チェック
        if len(rq['zabbix_disp_name']) == 0:
            error_flag = True
            error_msg['zabbix_disp_name'] += get_message('MOSJA26102',
                                                         lang) + '\n'
            logger.user_log('LOSM07001', 'zabbix_disp_name', request=request)

        # zabbix_disp_name長さチェック
        if len(rq['zabbix_disp_name']) > 64:
            error_flag = True
            error_msg['zabbix_disp_name'] += get_message('MOSJA26103',
                                                         lang) + '\n'
            logger.user_log('LOSM07002',
                            'zabbix_disp_name',
                            64,
                            rq['zabbix_disp_name'],
                            request=request)

        # zabbix_disp_name絵文字使用チェック
        value_list = emo_chk.is_emotion(rq['zabbix_disp_name'])
        if len(value_list) > 0:
            error_flag = True
            emo_flag_zabbix_disp_name = True
            error_msg['zabbix_disp_name'] += get_message('MOSJA26104',
                                                         lang) + '\n'
            logger.user_log('LOSM07008',
                            rq['zabbix_disp_name'],
                            request=request)

        # protocol未入力チェック
        if len(rq['protocol']) == 0:
            error_flag = True
            error_msg['protocol'] += get_message('MOSJA26105', lang) + '\n'
            logger.user_log('LOSM07001', 'protocol', request=request)

        # protocol長さチェック
        if len(rq['protocol']) > 64:
            error_flag = True
            error_msg['protocol'] += get_message('MOSJA26106', lang) + '\n'
            logger.user_log('LOSM07002',
                            'protocol',
                            64,
                            rq['protocol'],
                            request=request)

        # hostname未入力チェック
        if len(rq['hostname']) == 0:
            error_flag = True
            error_msg['hostname'] += get_message('MOSJA26107', lang) + '\n'
            logger.user_log('LOSM07001', 'hostname', request=request)

        # hostname長さチェック
        if len(rq['hostname']) > 128:
            error_flag = True
            error_msg['hostname'] += get_message('MOSJA26108', lang) + '\n'
            logger.user_log('LOSM07002',
                            'hostname',
                            128,
                            rq['hostname'],
                            request=request)

        # hostname絵文字使用チェック
        value_list = emo_chk.is_emotion(rq['hostname'])
        if len(value_list) > 0:
            error_flag = True
            emo_flag_hostname = True
            error_msg['hostname'] += get_message('MOSJA26109', lang) + '\n'
            logger.user_log('LOSM07008', rq['hostname'], request=request)

        # port未入力チェック
        if len(rq['port']) == 0:
            error_flag = True
            error_msg['port'] += get_message('MOSJA26110', lang) + '\n'
            logger.user_log('LOSM07001', 'port', request=request)

        # port長さチェック
        try:
            tmp_port = int(rq['port'])
            if 0 > tmp_port or tmp_port > 65535:
                error_flag = True
                error_msg['port'] += get_message('MOSJA26111', lang) + '\n'
                logger.user_log('LOSM07003',
                                'port',
                                rq['port'],
                                request=request)
        except ValueError:
            error_flag = True
            error_msg['port'] += get_message('MOSJA26111', lang) + '\n'
            logger.user_log('LOSM07003', 'port', rq['port'], request=request)

        # username未入力チェック
        if len(rq['username']) == 0:
            error_flag = True
            error_msg['username'] += get_message('MOSJA26112', lang) + '\n'
            logger.user_log('LOSM07001', 'username', request=request)

        # username長さチェック
        if len(rq['username']) > 64:
            error_flag = True
            error_msg['username'] += get_message('MOSJA26113', lang) + '\n'
            logger.user_log('LOSM07002',
                            'username',
                            64,
                            rq['username'],
                            request=request)

        # username絵文字使用チェック
        value_list = emo_chk.is_emotion(rq['username'])
        if len(value_list) > 0:
            error_flag = True
            error_msg['username'] += get_message('MOSJA26114', lang) + '\n'
            logger.user_log('LOSM07008', rq['username'], request=request)

        # password未入力チェック
        if len(rq['password']) == 0:
            error_flag = True
            error_msg['password'] += get_message('MOSJA26115', lang) + '\n'
            logger.user_log('LOSM07001', 'password', request=request)

        # password長さチェック
        # 追加の場合
        if rq['zabbix_adapter_id'] == '0':
            if len(rq['password']) > 64:
                error_flag = True
                error_msg['password'] += get_message('MOSJA26116', lang) + '\n'
                logger.user_log('LOSM07002',
                                'password',
                                64,
                                rq['password'],
                                request=request)

            # password絵文字使用チェック
            value_list = emo_chk.is_emotion(rq['password'])
            if len(value_list) > 0:
                error_flag = True
                error_msg['password'] += get_message('MOSJA26117', lang) + '\n'
                logger.user_log('LOSM07008', rq['password'], request=request)

        # 変更の場合
        else:
            old_password = ZabbixAdapter.objects.get(
                zabbix_adapter_id=rq['zabbix_adapter_id']).password
            # パスワード復号
            cipher = AESCipher(settings.AES_KEY)
            old_password_dec = cipher.decrypt(old_password)
            if old_password != rq['password']:
                if len(rq['password']) > 64:
                    error_flag = True
                    error_msg['password'] += get_message('MOSJA26116',
                                                         lang) + '\n'
                    logger.user_log('LOSM07002',
                                    'password',
                                    64,
                                    rq['password'],
                                    request=request)

                # password絵文字使用チェック
                value_list = emo_chk.is_emotion(rq['password'])
                if len(value_list) > 0:
                    error_flag = True
                    error_msg['password'] += get_message('MOSJA26117',
                                                         lang) + '\n'
                    logger.user_log('LOSM07008',
                                    rq['password'],
                                    request=request)

        # rule_type_id未入力チェック
        if len(rq['rule_type_id']) == 0:
            error_flag = True
            rule_type_id_error_flag = True
            error_msg['rule_type_id'] += get_message('MOSJA26118', lang) + '\n'
            logger.user_log('LOSM07001', 'rule_type_id', request=request)

        # rule_type_id存在チェック
        else:
            check_rule_id = RuleType.objects.filter(
                rule_type_id=rq['rule_type_id'])
            if len(check_rule_id) < 1:
                error_flag = True
                rule_type_id_error_flag = True
                error_msg['rule_type_id'] += get_message('MOSJA26119',
                                                         lang) + '\n'
                logger.user_log('LOSM07001', 'rule_type_id', request=request)

        if not rule_type_id_error_flag:
            # 突合情報存在チェック

            # 条件名の数を取得
            do_list = DataObject.objects.filter(
                rule_type_id=rq['rule_type_id']).values_list('data_object_id',
                                                             flat=True)

            # Zabbix項目チェック
            for data_object_id, zabbix_response_key in rq['match_list'].items(
            ):
                id_name = 'zabbix-' + data_object_id
                error_msg.setdefault(id_name, '')

                # 条件名とZabbix項目の数があっているかチェック
                if len(do_list) != len(rq['match_list'].keys()):
                    error_flag = True
                    error_msg[id_name] += get_message(
                        'MOSJA26121', request.user.get_lang_mode()) + '\n'
                    logger.user_log('LOSM07007',
                                    len(do_list),
                                    len(rq['match_list'].items()),
                                    request=request)

                if len(zabbix_response_key) == 0:
                    error_flag = True
                    error_msg[id_name] += get_message('MOSJA26122',
                                                      lang) + '\n'
                    logger.user_log('LOSM07001',
                                    'zabbix_response_key',
                                    request=request)

                if len(zabbix_response_key) > 32:
                    error_flag = True
                    error_msg[id_name] += get_message('MOSJA26128',
                                                      lang) + '\n'
                    logger.user_log('LOSM07002',
                                    'zabbix_response_key',
                                    32,
                                    zabbix_response_key,
                                    request=request)

                # Zabbix項目絵文字使用チェック
                value_list = emo_chk.is_emotion(zabbix_response_key)
                if len(value_list) > 0:
                    error_flag = True
                    error_msg[id_name] += get_message('MOSJA26123',
                                                      lang) + '\n'
                    logger.user_log('LOSM07008',
                                    rq['zabbix_disp_name'],
                                    request=request)

                # 使用可能名チェック
                if zabbix_response_key not in ZABBIX_ITEMS:
                    error_flag = True
                    error_msg[id_name] += get_message('MOSJA26147',
                                                      lang) + '\n'
                    logger.user_log('LOSM07009',
                                    rq['zabbix_disp_name'],
                                    request=request)

        # zabbix_disp_name重複チェック
        if not emo_flag_zabbix_disp_name:
            duplication = ZabbixAdapter.objects.filter(
                zabbix_disp_name=rq['zabbix_disp_name'])
            if len(duplication) == 1 and int(
                    rq['zabbix_adapter_id']
            ) != duplication[0].zabbix_adapter_id:
                error_flag = True
                error_msg['zabbix_disp_name'] += get_message(
                    'MOSJA26124', lang) + '\n'
                logger.user_log('LOSM07004',
                                'zabbix_disp_name',
                                rq['zabbix_disp_name'],
                                request=request)

        # hostname重複チェック
        if not emo_flag_hostname:
            duplication = ZabbixAdapter.objects.filter(
                hostname=rq['hostname'], rule_type_id=rq['rule_type_id'])

            # ホスト名重複かつルール種別名が同一の場合
            if len(duplication) == 1 and int(
                    rq['zabbix_adapter_id']
            ) != duplication[0].zabbix_adapter_id:
                error_flag = True
                error_msg['hostname'] += get_message(
                    'MOSJA26125', request.user.get_lang_mode()) + '\n'
                logger.user_log('LOSM07004',
                                'hostname',
                                rq['hostname'],
                                request=request)

        # 疎通確認
        if not error_flag:
            resp_code = -1
            try:
                with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
                    resp_code = sock.connect_ex(
                        (rq['hostname'],
                         int(rq['port'])))  # host名名前解決が必要/etc/hostsとか
                    sock.close()
            except:
                pass
            if resp_code != 0:
                error_flag = True
                error_msg['hostname'] += get_message('MOSJA26126', lang) + '\n'
                logger.user_log('LOSM07005',
                                rq['hostname'],
                                rq['port'],
                                request=request)

        logger.logic_log('LOSI00002', 'return: %s' % error_flag)
        return error_flag
Exemplo n.º 20
0
    def create(self, json_str, request):
        """
        [メソッド概要]
          DB作成処理
        """

        logger.logic_log('LOSI00001',
                         'json_str: %s' % (json_str),
                         request=request)
        lang = request.user.get_lang_mode()

        error_flag = False
        error_msg = {
            'zabbix_disp_name': '',
            'protocol': '',
            'hostname': '',
            'port': '',
            'username': '',
            'password': '',
            'rule_type_id': '',
        }
        now = datetime.datetime.now(pytz.timezone('UTC'))

        # 成功時データ
        response = {
            "status": "success",
        }

        try:
            rq = json_str

            #入力チェック
            error_flag = self._validate(rq, error_msg, request, 'add')

            if error_flag:
                raise UserWarning('validation error.')

            # パスワードを暗号化
            cipher = AESCipher(settings.AES_KEY)
            encrypted_password = cipher.encrypt(rq['password'])

            # ZABBIXアダプタの追加
            zabbix_adp = ZabbixAdapter(
                zabbix_disp_name=rq['zabbix_disp_name'],
                hostname=rq['hostname'],
                username=rq['username'],
                password=encrypted_password,
                protocol=rq['protocol'],
                port=rq['port'],
                rule_type_id=rq['rule_type_id'],
                last_update_user=request.user.user_name,
                last_update_timestamp=now,
            )
            zabbix_adp.save(force_insert=True)

            # 保存したアダプタのadapter_idを取得
            zabbix_adpid = zabbix_adp.zabbix_adapter_id

            # ZABBIX突合情報の保存
            create_match_list = []
            for data_object_id, zabbix_response_key in rq['match_list'].items(
            ):

                match = ZabbixMatchInfo(
                    zabbix_adapter_id=zabbix_adpid,
                    data_object_id=data_object_id,
                    zabbix_response_key=zabbix_response_key,
                    last_update_user=request.user.user_name,
                    last_update_timestamp=now,
                )
                create_match_list.append(match)

            ZabbixMatchInfo.objects.bulk_create(create_match_list)

        except ZabbixAdapter.DoesNotExist:
            logger.logic_log('LOSM07001',
                             'hostname: %s rule_type_id: %s' %
                             (rq['hostname'], rq['rule_type_id']),
                             request=request)
            response = {
                'status': 'deleted',
                'msg': get_message('MOSJA26127', lang),
            }

        except Exception as e:
            logger.logic_log('LOSI00005',
                             traceback.format_exc(),
                             request=request)
            response = {
                'status': 'failure',
                'msg': error_msg,  # エラー詳細(エラーアイコンで出す)
            }

        logger.logic_log('LOSI00002',
                         'response=%s' % response,
                         request=request)

        return response
Exemplo n.º 21
0
oase_root_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                             '../oase-root/')
sys.path.append(oase_root_dir)

from libs.commonlibs.common import Common
from libs.commonlibs.aes_cipher import AESCipher
from confs.frameworkconfs.settings import AES_KEY

if __name__ == '__main__':

    input_value = 'P@$$w0rd'

    args = sys.argv
    if len(args) == 2:
        input_value = args[1]
    else:
        print(
            "実行方法が間違っています。実行方法を確認してください。\n実行例)python /home/centos/OASE/oase-root/tool/encrypter.py 'password@1'"
        )
        sys.exit(1)

    # AESCipher変換
    cipher = AESCipher(AES_KEY)
    encrypted = cipher.encrypt(input_value)
    # 暗号化結果
    print(encrypted)

    # 復号化結果
#    decrypted = cipher.decrypt(encrypted)
#    print(decrypted)
Exemplo n.º 22
0
def set_test_data():

    now = datetime.datetime.now(pytz.timezone('UTC'))
    group = Group(
        group_id=1,
        group_name='単体テストチーム',
        summary='単体テスト用権限',
        ad_data_flag='0',
        last_update_timestamp=now,
        last_update_user='******',
    )
    group.save()

    group = Group(
        group_id=2,
        group_name='結合テストチーム',
        summary='結合テスト用権限',
        ad_data_flag='0',
        last_update_timestamp=now,
        last_update_user='******',
    )
    group.save()

    cipher = AESCipher(settings.AES_KEY)
    encrypted_password = cipher.encrypt('pytest')
    ita_driver = ItaDriver(
        ita_driver_id=1,
        ita_disp_name='Action43',
        protocol='https',
        hostname='pytest-host-name',
        port='443',
        username='******',
        password=encrypted_password,
        last_update_user='******',
        last_update_timestamp=now,
    )
    ita_driver.save(force_insert=True)

    ita_driver = ItaDriver(
        ita_driver_id=2,
        ita_disp_name='Action44',
        protocol='https',
        hostname='pytest-host-name2',
        port='443',
        username='******',
        password=encrypted_password,
        last_update_user='******',
        last_update_timestamp=now,
    )
    ita_driver.save(force_insert=True)

    itapermission = ItaPermission(
        ita_permission_id=1,
        ita_driver_id=1,
        group_id=998,
        permission_type_id=1,
        last_update_timestamp=now,
        last_update_user='******',
    )
    itapermission.save(force_insert=True)

    user_group = UserGroup(
        user_group_id=1,
        user_id=1,
        group_id=1,
        ad_data_flag='0',
        last_update_timestamp=datetime.datetime.now(pytz.timezone('UTC')),
        last_update_user='******',
    )
    user_group.save(force_insert=True)

    user_group = UserGroup(
        user_group_id=2,
        user_id=1,
        group_id=998,
        ad_data_flag='0',
        last_update_timestamp=datetime.datetime.now(pytz.timezone('UTC')),
        last_update_user='******',
    )
    user_group.save(force_insert=True)
Exemplo n.º 23
0
    def modify(self, json_str, request):
        """
        [メソッド概要]
          グループのDB更新処理
        """

        logger.logic_log('LOSI00001', 'None', request=request)

        error_flag = False
        error_msg = {
            'ita_disp_name': '',
            'version': '',
            'protocol': '',
            'hostname': '',
            'port': '',
            'username': '',
            'password': '',
        }
        now = datetime.datetime.now(pytz.timezone('UTC'))
        # 成功時データ
        response = {
            "status": "success",
        }

        try:
            rq = json_str['json_str']

            response = self._chk_permission(request.user_config.group_id_list,
                                            rq['ita_driver_id'], response)
            if response['status'] == 'failure':
                return response

            ope = int(rq['ope'])
            #削除以外の場合の入力チェック
            if ope != defs.DABASE_OPECODE.OPE_DELETE:
                error_flag = self._validate(rq, error_msg, request)
            if error_flag:
                raise Exception('validation error.')

            # パスワードを暗号化
            cipher = AESCipher(settings.AES_KEY)

            if ope == defs.DABASE_OPECODE.OPE_UPDATE:
                encrypted_password = cipher.encrypt(rq['password'])

                driver = ItaDriver.objects.get(
                    ita_driver_id=rq['ita_driver_id'])
                driver.ita_disp_name = rq['ita_disp_name']
                driver.version = rq['version']
                driver.protocol = rq['protocol']
                driver.hostname = rq['hostname']
                driver.port = rq['port']
                driver.username = rq['username']
                driver.password = encrypted_password
                driver.last_update_user = request.user.user_name
                driver.last_update_timestamp = now
                driver.save(force_update=True)

                permission_list_reg = []
                for pm in rq['permission']:
                    rcnt = ItaPermission.objects.filter(
                        ita_driver_id=rq['ita_driver_id'],
                        group_id=pm['group_id']).count()

                    if rcnt > 0:
                        ItaPermission.objects.filter(
                            ita_driver_id=rq['ita_driver_id'],
                            group_id=pm['group_id']).update(
                                permission_type_id=pm['permission_type_id'],
                                last_update_timestamp=now,
                                last_update_user=request.user.user_name)
                    else:
                        permission_list_reg.append(
                            ItaPermission(
                                ita_driver_id=rq['ita_driver_id'],
                                group_id=pm['group_id'],
                                permission_type_id=pm['permission_type_id'],
                                last_update_timestamp=now,
                                last_update_user=request.user.user_name))

                if len(permission_list_reg) > 0:
                    ItaPermission.objects.bulk_create(permission_list_reg)

            elif ope == defs.DABASE_OPECODE.OPE_DELETE:
                ItaDriver.objects.get(pk=rq['ita_driver_id']).delete()
                ItaPermission.objects.filter(
                    ita_driver_id=rq['ita_driver_id']).delete()

            elif ope == defs.DABASE_OPECODE.OPE_INSERT:
                encrypted_password = cipher.encrypt(rq['password'])

                driver = ItaDriver(
                    ita_disp_name=rq['ita_disp_name'],
                    version=rq['version'],
                    protocol=rq['protocol'],
                    hostname=rq['hostname'],
                    port=rq['port'],
                    username=rq['username'],
                    password=encrypted_password,
                    last_update_user=request.user.user_name,
                    last_update_timestamp=now,
                ).save(force_insert=True)

                ita_driver_id = ItaDriver.objects.get(
                    ita_disp_name=rq['ita_disp_name']).ita_driver_id

                permission_list_reg = []
                for pm in rq['permission']:
                    permission = ItaPermission(
                        ita_driver_id=ita_driver_id,
                        group_id=pm['group_id'],
                        permission_type_id=pm['permission_type_id'],
                        last_update_timestamp=now,
                        last_update_user=request.user.user_name,
                    )
                    permission_list_reg.append(permission)
                ItaPermission.objects.bulk_create(permission_list_reg)
                logger.user_log('LOSI27007',
                                'web_app.models.ITA_models',
                                request=request)

        except ItaDriver.DoesNotExist:
            logger.logic_log('LOSM07006',
                             "ita_driver_id",
                             ita_driver_id,
                             request=request)

        except Exception as e:
            logger.logic_log('LOSI00005',
                             traceback.format_exc(),
                             request=request)
            response = {
                'status': 'failure',
                'error_msg': error_msg,  # エラー詳細(エラーアイコンで出す)
            }

        logger.logic_log('LOSI00002',
                         'response=%s' % response,
                         request=request)

        return response