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)
示例#2
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)
示例#3
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
示例#4
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")
    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
    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
示例#7
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)
示例#8
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