示例#1
0
def set_test_regist_data():
    """
    テストで使用するデータの作成
    """
    now = datetime.datetime.now(pytz.timezone('UTC'))
    trace_id = EventsRequestCommon.generate_trace_id(now)
    response_id = 1

    act_his = ActionHistory(response_id=response_id,
                            trace_id=trace_id,
                            rule_type_id=1,
                            rule_type_name='pytest_ruletable',
                            rule_name='pytest_rule',
                            execution_order=1,
                            action_start_time=now,
                            action_type_id=1,
                            status=2106,
                            status_detail=0,
                            status_update_id='pytest_id',
                            retry_flag=False,
                            retry_status=None,
                            retry_status_detail=None,
                            action_retry_count=0,
                            last_act_user='******',
                            last_update_timestamp=now,
                            last_update_user='******')
    act_his.save(force_insert=True)

    now = datetime.datetime.now(pytz.timezone('UTC'))

    user = User(
        user_id=Cstobj.DB_OASE_USER,
        user_name='unittest_procedure',
        login_id='',
        mail_address='',
        password='',
        disp_mode_id=DISP_MODE.DEFAULT,
        lang_mode_id=LANG_MODE.JP,
        password_count=0,
        password_expire=datetime.datetime.now(pytz.timezone('UTC')),
        last_update_user='******',
        last_update_timestamp=datetime.datetime.now(pytz.timezone('UTC')),
    )
    user.save(force_insert=True)
示例#2
0
    def set_test_data(self):
        """
        テストデータ作成
        """

        now = datetime.datetime.now(pytz.timezone('UTC'))

        User(
            user_id=999,
            user_name='unittest_apply',
            login_id='',
            mail_address='',
            password='',
            disp_mode_id=DISP_MODE.DEFAULT,
            lang_mode_id=LANG_MODE.JP,
            password_count=0,
            password_expire=now,
            last_update_user='******',
            last_update_timestamp=now,
        ).save(force_insert=True)

        RuleType(
            rule_type_id = 9999,
            rule_type_name = 'pytest_name',
            summary = None,
            rule_table_name = 'pytest_table',
            generation_limit = 5,
            group_id = 'pytest_com',
            artifact_id = 'pytest_oase',
            container_id_prefix_staging = 'test',
            container_id_prefix_product = 'prod',
            current_container_id_staging = None,
            current_container_id_product = None,
            label_count = 1,
            unknown_event_notification = '1',
            mail_address = '*****@*****.**',
            disuse_flag = '0',
            last_update_timestamp = now,
            last_update_user = '******'
        ).save(force_insert=True)

        AccessPermission(
            permission_id = 9999,
            group_id = 9999,
            menu_id = 9999,
            rule_type_id = 9999,
            permission_type_id = 3,
            last_update_timestamp = now,
            last_update_user = '******'
        ).save(force_insert=True)
示例#3
0
def get_user(screen_name=None):
    print(screen_name)

    twitter_user = twitter_api_client.get_user(screen_name)
    statuses = twitter_api_client.user_timeline(screen_name,
                                                tweet_mode="extended",
                                                count=150,
                                                exclude_replies=True,
                                                include_rts=False)
    print("STATUSES COUNT:", len(statuses))
    #return jsonify({"user": user._json, "tweets": [s._json for s in statuses]})

    # get existing user from the db or initialize a new one:
    db_user = User.query.get(twitter_user.id) or User(id=twitter_user.id)
    db_user.screen_name = twitter_user.screen_name
    db_user.name = twitter_user.name
    db_user.location = twitter_user.location
    db_user.followers_count = twitter_user.followers_count
    db.session.add(db_user)
    db.session.commit()
    #return "OK"
    #breakpoint()

    # all_tweet_texts = [status.full_text for status in statuses]
    # embeddings = list(basilica_api_client.embed_sentences(all_tweet_texts, model="twitter"))
    # print("NUMBER OF EMBEDDINGS", len(embeddings))

    # TODO: explore using the zip() function maybe...
    # counter = 0
    for status in statuses:
        print(status.full_text)
        print("----")
        #print(dir(status))
        # get existing tweet from the db or initialize a new one:
        db_tweet = Tweet.query.get(status.id) or Tweet(id=status.id)
        db_tweet.user_id = status.author.id  # or db_user.id
        db_tweet.full_text = status.full_text
        embedding = basilica_api_client.embed_sentence(
            status.full_text, model="twitter"
        )  # todo: prefer to make a single request to basilica with all the tweet texts, instead of a request per tweet
        # embedding = embeddings[counter]
        print(len(embedding))
        db_tweet.embedding = embedding
        db.session.add(db_tweet)
        # counter+=1
    db.session.commit()
    return "OK"
示例#4
0
def modify(request):
    """
    [メソッド概要]
      データ更新処理
    """
    #====アカウント追加時の初期値====#
    disp = defs.DISP_MODE.DEFAULT
    lang = defs.LANG_MODE.JP

    msg                  = ''
    error_msg            = ''
    error_msg_user_name  = ''
    error_msg_login_id   = ''
    error_msg_mail       = ''
    error_msg_user_group = ''

    json_str = request.POST.get('json_str',None)

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

    if json_str is None:
        msg = get_message('MOSJA24001', request.user.get_lang_mode())
        logger.user_log('LOSM05002', request=request)
        raise Http404

    try:
        with transaction.atomic():
            json_str = json.loads(json_str)

            #=================ロック=============================#
            # リクエストされたグループIDを取得
            group_ids_req = []
            for rq in json_str['insertInfo']:
                for gid in rq['add_group_id']:
                    if len(gid) != 0:
                        gid = int(gid)
                        if gid not in group_ids_req:
                            group_ids_req.append(gid)

            for rq in json_str['updateInfo']:
                for gid in rq['add_group_id']:
                    if len(gid) != 0:
                        gid = int(gid)
                        if gid not in group_ids_req:
                            group_ids_req.append(gid)

                for gid in rq['del_group_id']:
                    if len(gid) != 0:
                        gid = int(gid)
                        if gid not in group_ids_req:
                            group_ids_req.append(gid)

            group_ids_req.sort()

            # グループ管理をロック
            group_ids_db = []
            for gid in group_ids_req:
                gr = Group.objects.select_for_update().filter(group_id=gid)
                if len(gr) <= 0:
                    logger.user_log('LOSM05005', 'group_id: %s' % gid , request=request)
                    continue

                group_ids_db.append(gr[0].group_id)

            group_ids_diff = list(set(group_ids_req) ^ set(group_ids_db))


            # 更新レコードのリスト作成(administrator除く)
            update_info = []
            update_userid_list = []
            for rq in json_str['updateInfo']:
                if int(rq['user_id']) != 1:
                    update_info.append(rq)
                    update_userid_list.append(int(rq['user_id']))
                else:
                    logger.user_log('LOSM05008', 'update_user_info: %s ' % rq , request=request)

            # 削除レコードのリスト作成(administrator除く)
            del_info = []
            del_userid_list = []
            for rq in json_str['delInfo']:
                if int(rq['user_id']) != 1:
                    del_info.append(rq)
                    del_userid_list.append(int(rq['user_id']))
                else:
                    logger.user_log('LOSM05008', 'delete_user_info: %s ' % rq , request=request)

            # 更新/削除ユーザをロック
            mod_user_list = update_userid_list + del_userid_list 
            mod_user_list.sort()
            for m in mod_user_list:
                User.objects.select_for_update().filter(pk=m)


            #=================チェック===========================#
            # 入力データチェック データ不正であればresponseを返す
            error_flag, error_msg_user_name, error_msg_login_id, error_msg_mail, error_msg_user_group = _validate(json_str, group_ids_diff, request=request)
            if error_flag:
                response_json = json.dumps({
                    'status'              : 'failure',
                    'error_msg_user_name' : error_msg_user_name,
                    'error_msg_login_id'  : error_msg_login_id,
                    'error_msg_mail'      : error_msg_mail,
                    'error_msg_user_group': error_msg_user_group,
                    'msg'                 : '',
                })

                logger.user_log('LOSM05004', 'error_msg_user_name: %s' % error_msg_user_name, request=request)
                logger.user_log('LOSM05004', 'error_msg_login_id: %s' % error_msg_login_id, request=request)
                logger.user_log('LOSM05004', 'error_msg_mail: %s' % error_msg_mail, request=request)
                logger.user_log('LOSM05004', 'error_msg_user_group: %s' % error_msg_user_group, request=request)
                logger.logic_log('LOSI00002', 'json_str: %s' % json_str, request=request)

                return HttpResponse(response_json, content_type="application/json")

            #=================更新===============================#
            update_list = []
            del_usergroup_list = {}
            add_usergroup_list = {}
            user_info = {}

            logger.user_log('LOSI05000', update_info, request=request)

            for rq in update_info:
                user_info[int(rq['user_id'])] = {
                    'user_name': rq['user_name'],
                    'login_id' : rq['login_id'], 
                    'mail'     : rq['mail'],
                    'add_group_id' : rq['add_group_id'],
                    'del_group_id' : rq['del_group_id'],
                }

            users = User.objects.filter(pk__in=update_userid_list, disuse_flag='0')
            for u in users:
                u.user_name    = user_info[u.pk]['user_name']
                u.login_id     = user_info[u.pk]['login_id'] if u.sso_id == 0 else u.login_id
                u.mail_address = user_info[u.pk]['mail']
                u.last_update_timestamp = datetime.datetime.now(pytz.timezone('UTC'))
                u.last_update_user = request.user.user_name

                add_usergroup_list[u.user_id] = [int(s) for s in user_info[u.pk]['add_group_id']]
                del_usergroup_list[u.user_id] = [int(s) for s in user_info[u.pk]['del_group_id']]
                update_list.append(u)

            for u in update_list:
                u.save()
                if u.pk in add_usergroup_list:
                    for g in add_usergroup_list[u.pk]:
                        ug = UserGroup(
                            user_id = u.pk,
                            group_id = g,
                            last_update_user = request.user.user_name,
                            )
                        ug.save(force_insert=True)
                if u.pk in del_usergroup_list:
                    UserGroup.objects.filter(user_id=u.pk, group_id__in=del_usergroup_list[u.pk]).delete()

            logger.user_log('LOSI05001', update_info, request=request)

            #=================削除===============================#
            logger.user_log('LOSI05002', del_info, request=request)

            User.objects.filter(pk__in=del_userid_list).delete()
            UserGroup.objects.filter(user_id__in=del_userid_list).delete()
            PasswordHistory.objects.filter(user_id__in=del_userid_list).delete()

            logger.user_log('LOSI05003', del_info, request=request)

            #==================新規追加===============================#
            insert_list = []
            insert_usergroup_list = {}
            insert_list_pwhist = []
            create_list = []
            create_err_flag = False
            ttl_hour = int(System.objects.get(config_id='INITIAL_PASS_VALID_PERIOD').value)

            for rq in json_str['insertInfo']:
                # ランダムパスワード生成
                password = RandomPassword().get_password()
                password_hash = Common.oase_hash(password)
                password_expire = None
                if ttl_hour == 0:
                    # datetime supportで日時がずれoverflowするため9000年とした
                    password_expire = datetime.datetime.strptime('9000-12-31 23:59:59', '%Y-%m-%d %H:%M:%S')
                else:
                    password_expire = datetime.datetime.now(pytz.timezone('UTC')) + datetime.timedelta(hours=ttl_hour)

                user = User( 
                    user_name    = rq['user_name'],
                    login_id     = rq['login_id'],
                    mail_address = rq['mail'],
                    password     = password_hash,
                    disp_mode_id = disp,
                    lang_mode_id = lang,
                    password_count = 0,
                    password_expire = password_expire,
                    last_update_user = request.user.user_name,
                    last_update_timestamp = datetime.datetime.now(pytz.timezone('UTC')),
                )

                insert_list.append(user)
                insert_usergroup_list[rq['login_id']] = rq['add_group_id']

                create_info = {
                    'name' : rq['user_name'],
                    'mail' : rq['mail'],
                    'pass' : password,
                    'id'   : rq['login_id'],
                }
                create_list.append(create_info)

            Pass_generate_manage = int(System.objects.get(config_id='Pass_generate_manage').value)
            logger.user_log('LOSI05004', json_str['insertInfo'], Pass_generate_manage, request=request)
            # create処理
            for i in insert_list:
                i.save(force_insert=True)
                # userが登録できたらusergroupを登録
                for j in insert_usergroup_list[i.login_id]:
                    usergroup = UserGroup(
                        user_id = i.pk,
                        group_id = j,
                        last_update_user = request.user.user_name,
                    )
                    usergroup.save(force_insert=True)

                if Pass_generate_manage > 0:
                    passwd_history = PasswordHistory(
                       user_id  = i.user_id,
                       password = password_hash,
                       last_update_timestamp = datetime.datetime.now(pytz.timezone('UTC')),
                       last_update_user = request.user.user_name,
                    )
                    insert_list_pwhist.append(passwd_history)

            if len(insert_list_pwhist) > 0:
                PasswordHistory.objects.bulk_create(insert_list_pwhist)

            logger.user_log('LOSI05005', json_str['insertInfo'], Pass_generate_manage, request=request)

            # 署名用URL生成
            req_protcol = request.scheme
            req_host    = request.get_host()
            login_url   = reverse('web_app:top:login')
            inquiry_url = reverse('web_app:top:inquiry')
            login_url   = '%s://%s%s' % (req_protcol, req_host, login_url)
            inquiry_url = '%s://%s%s' % (req_protcol, req_host, inquiry_url)

            # 新規登録ユーザに初期ユーザIDをメールで通知
            msg_ids = []
            if len(create_list) > 0 and create_err_flag == False:
                smtp = OASEMailSMTP(request=request)
                for u in create_list:
                    user_mail = OASEMailInitialLoginID(
                        request.user.mail_address, u['mail'], u['name'], u['id'], ttl_hour, inquiry_url, login_url
                    )
                    send_result = smtp.send_mail(user_mail)

                    logger.logic_log('LOSI05006', u['mail'], u['id'], request=request)
                    if send_result and send_result not in msg_ids:
                        msg_ids.append(send_result)
                        send_result = get_message(send_result, request.user.get_lang_mode())
                        error_flag = True
                        if msg:
                            msg += '\n'
                        msg += send_result

            # 新規登録ユーザに初期パスワードをメールで通知
            if len(create_list) > 0 and create_err_flag == False:
                smtp = OASEMailSMTP(request=request)
                for u in create_list:
                    user_mail = OASEMailInitialPasswd(
                        request.user.mail_address, u['mail'], u['name'], u['pass'], ttl_hour, inquiry_url, login_url
                    )
                    send_result = smtp.send_mail(user_mail)

                    logger.logic_log('LOSI05007', u['mail'], request=request)
                    if send_result and send_result not in msg_ids:
                        msg_ids.append(send_result)
                        send_result = get_message(send_result, request.user.get_lang_mode())
                        error_flag = True
                        if msg:
                            msg += '\n'
                        msg += send_result

    except Exception as e:
        error_flag = True
        logger.logic_log('LOSM05003', 'json_str: %s, traceback: %s' % (json_str, traceback.format_exc()), request=request)

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

    # 異常処理
    if error_flag == True:

        response_data['status'] = 'failure'
        response_data['error_msg'] = error_msg
        response_data['msg'] = msg
        logger.logic_log('LOSM05007', 'json_str: %s, response_data: %s, traceback: %s' % (json_str, response_data, traceback.format_exc()), request=request)

    # 正常処理
    else:
        response_data['status'] = 'success'
        response_data['redirect_url'] = '/oase_web/system/user'

    response_json = json.dumps(response_data)

    logger.logic_log('LOSI00002', 'json_str: %s, response_json: %s' % (json_str, response_json), request=request)
    return HttpResponse(response_json, content_type="application/json")
示例#5
0
def callback(request):
    """
    [メソッド概要]
      view関数 : SSO認証プロバイダーからのコールバック
    """

    code = request.GET.get('code', '')
    state_query = request.GET.get('state', '')
    sso_id = request.session['sso_id']

    logger.logic_log('LOSI00001',
                     'sso_id=%s, code=%s' % (sso_id, code),
                     request=request)

    uid = 0
    next_url = settings.LOGIN_URL

    try:
        sso_id = int(sso_id)
        state = request.session.pop('state')

        if state_query and state != state_query:
            logger.system_log('LOSM10007', sso_id, state_query, state)
            raise OASELoginError('MOSJA10010')

        ########################################
        # SSO情報取得
        ########################################
        # DBからSSO情報取得
        sso = SsoInfo.objects.get(sso_id=sso_id)

        # SSO情報チェック
        check_keys = [
            'clientid', 'clientsecret', 'accesstokenuri', 'resourceowneruri',
            'id', 'name'
        ]
        for k in check_keys:
            if not (hasattr(sso, k) and getattr(sso, k, None)):
                logger.user_log('LOSM10003', k, request=request)
                raise OASELoginError('MOSJA10044')

        ########################################
        # アクセストークン取得
        ########################################
        # プロバイダーからトークン取得要求
        func_list = [
            _token_request_ptrn1,
            _token_request_ptrn2,
        ]

        for f in func_list:
            resp = f(request, sso, code)
            if resp.status_code == 200:
                break

        else:
            logger.user_log('LOSM10005', sso_id, request=request)
            raise OASELoginError('MOSJA10010')

        try:
            resp_params = ast.literal_eval(resp.text)

        except Exception as e:
            resp_params = {
                k: v
                for k, v in [p.split('=') for p in resp.text.split('&')]
            }

        access_token = resp_params['access_token']

        ########################################
        # ユーザー情報取得
        ########################################
        # プロバイダーからユーザー情報取得要求
        func_list = [
            _user_info_request_ptrn1,
            _user_info_request_ptrn2,
        ]

        for f in func_list:
            resp_data = f(request, sso, access_token)
            if resp.status_code == 200:
                break

        else:
            logger.user_log('LOSM10006', sso_id, request=request)
            raise OASELoginError('MOSJA10010')

        user_info = resp_data.json()

        user_id = str(user_info.get(sso.id))
        user_name = str(user_info.get(sso.name))
        email = user_info.get(sso.email) if sso.email else ''
        image_url = user_info.get(sso.imageurl) if sso.imageurl else ''

        ########################################
        # ユーザー情報保存
        ########################################
        # プロバイダーから取得したユーザー情報をカラムの制限に合わせる
        user_id = user_id[:256]
        user_name = user_name[:64]
        email = email[:256] if email else ''

        user_id = '%s-%s' % (user_id, str(sso_id).zfill(11))

        # ユーザー情報をOASE側に保存
        with transaction.atomic():

            # OASE側に既に存在する場合、ユーザー情報を更新
            oase_user_info = User.objects.filter(login_id=user_id,
                                                 login_id__contains=user_id,
                                                 sso_id=sso_id)
            if len(oase_user_info) > 0:
                oase_user_info = oase_user_info[0]
                oase_user_info.user_name = user_name
                oase_user_info.mail_address = email if email else ''
                oase_user_info.disuse_flag = str(defs.ENABLE)
                oase_user_info.save(force_update=True)

            # OASE側に存在しない場合、ユーザー情報を登録
            else:
                oase_user_info = User(
                    login_id=user_id,
                    user_name=user_name,
                    password='',
                    mail_address=email if email else '',
                    lang_mode_id=defs.LANG_MODE.JP,
                    disp_mode_id=defs.DISP_MODE.DEFAULT,
                    sso_id=sso_id,
                    password_count=0,
                    password_expire=datetime.datetime.strptime(
                        '9000-12-31 23:59:59', '%Y-%m-%d %H:%M:%S'),
                    last_update_user=user_name,
                    last_update_timestamp=datetime.datetime.now(
                        pytz.timezone('UTC')),
                )
                oase_user_info.save(force_insert=True)

            # 所属グループがなければ、デフォルトを割り当て
            rcnt = UserGroup.objects.filter(
                user_id=oase_user_info.user_id).count()
            if rcnt <= 0:
                UserGroup(
                    user_id=oase_user_info.user_id,
                    group_id=defs.GROUP_DEFINE.GROUP_ID_SSO,
                    last_update_user=user_name,
                ).save(force_insert=True)

        # セッション情報作成
        backend = SSOClientAuthBackend()
        auth_login(request, oase_user_info, backend=backend.full_name)
        timeout_val = _get_value_session_timeout()
        now = datetime.datetime.now(pytz.timezone('UTC'))
        request.session['cookie_age'] = (
            now + timedelta(minutes=timeout_val)).strftime('%Y-%m-%d %H:%M:%S')
        request.session[LANGUAGE_SESSION_KEY] = oase_user_info.get_lang_mode(
        ).lower()
        request.session['sso_id'] = str(sso_id)
        request.session['sso_name'] = sso.provider_name
        request.session['sso_imageurl'] = image_url

        uid = oase_user_info.user_id
        next_url = settings.LOGIN_REDIRECT_URL

    except OASELoginError as e:
        request.session['msg'] = e.msg_id

    except SsoInfo.DoesNotExist:
        request.session['msg'] = 'MOSJA10044'
        logger.user_log('LOSM10004', sso_id, request=request)

    except Exception as e:
        request.session['msg'] = 'MOSJA10010'
        logger.logic_log('LOSI00001',
                         '%s' % (traceback.format_exc()),
                         request=request)

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

    return redirect(next_url)
示例#6
0
    def _collaborate_data(self, ad_data):
        """
        [概要]
            AD データ連携処理

        [引数]
            ad_data: 連携するADデータ

            # ad_data['group'] = [groupname]

            # ad_data['user'] = ad_users
            #   ad_users[login_id] = {
            #       'login_id'   : login_id,
            #       'display_name': display_name,
            #       'mail'       : mail,
            #       'group'      : [adgp],
            #   }
        """

        self.__logger.logic_log('LOSI00001',
                                'ad_data: %s' % json.dumps(ad_data))

        # --------------------------------
        # データ整理
        # --------------------------------
        ### システム設定のグループ名変換(AD_attribute->OASE_group_name) ###
        system_confs_group_list = System.objects.get(
            config_id='TARGET_GROUP_LIST').value
        groups_list = ast.literal_eval(system_confs_group_list)
        groups_dict = {}
        for g in groups_list:
            groups_dict.update(g)

        ### グループ ###
        cur_ad_grp_name_set = set(
            [groups_dict[ad_gname] for ad_gname in ad_data['group']])
        oase_ad_group = list(Group.objects.filter(ad_data_flag='1'))
        oase_ad_grp_dict = {grp.group_name: grp for grp in oase_ad_group}
        oase_ad_grp_name_set = set(oase_ad_grp_dict.keys())

        ### ユーザ ###
        cur_ad_user_dict = ad_data['user']
        cur_ad_user_login_id_set = set(cur_ad_user_dict.keys())
        oase_ad_user = list(
            User.objects.filter(ad_data_flag='1', disuse_flag='0'))
        oase_ad_user_dict = {user.login_id: user for user in oase_ad_user}
        oase_ad_user_login_id_set = set(oase_ad_user_dict.keys())

        ### ユーザグループ ###
        user_group_link = []
        for login_id, user_info in ad_data['user'].items():
            for user_group_name in user_info['group']:
                user_group_link.append(login_id + ':' +
                                       groups_dict[user_group_name])
        cur_ad_user_grp_key_set = set(user_group_link)
        oase_ad_user_group = list(UserGroup.objects.filter(ad_data_flag='1'))
        oase_ad_user_user_id_dict = {
            user.user_id: user.login_id
            for user in oase_ad_user
        }
        oase_ad_grp_grp_id_dict = {
            grp.group_id: grp.group_name
            for grp in oase_ad_group
        }
        oase_ad_user_grp_dict = {  # {login_id+group_name: user_group_id} としたい
            oase_ad_user_user_id_dict[usrgrp.user_id] + ':' +
            oase_ad_grp_grp_id_dict[usrgrp.group_id]: usrgrp
            for usrgrp in oase_ad_user_group
        }
        oase_ad_user_grp_key_set = set(oase_ad_user_grp_dict.keys())

        now = datetime.datetime.now(pytz.timezone('UTC'))
        modified_user_id_link_user_grp = []

        # --------------------------------
        # 追加系(グループ → ユーザ → ユーザグループ)
        # --------------------------------

        ### グループ ###
        add_target_grp = cur_ad_grp_name_set - oase_ad_grp_name_set
        add_grp_bulk_list = []
        tmp_grp = None
        for agrp_name in add_target_grp:
            tmp_grp = Group(group_name=agrp_name,
                            summary='',
                            ad_data_flag='1',
                            last_update_user=BACKYARD_USER.user_name,
                            last_update_timestamp=now)
            add_grp_bulk_list.append(copy.deepcopy(tmp_grp))

        self.__logger.logic_log(
            'LOSI11000', 'add_grp_bulk_list: %s' %
            ','.join([g.group_name for g in add_grp_bulk_list]))
        if len(add_grp_bulk_list) > 0:
            Group.objects.bulk_create(add_grp_bulk_list)

            # 権限を追加
            # 選択されたグループを取得
            inserted_group_name = []
            for group in add_grp_bulk_list:
                inserted_group_name.append(group.group_name)

            inserted_group_list = Group.objects.filter(
                group_name__in=inserted_group_name)

            permission_list = []
            permission_record = None
            for inserted_group in inserted_group_list:
                for menu_id in defs.MENU:

                    permission_record = AccessPermission(
                        group_id=inserted_group.group_id,
                        menu_id=menu_id,
                        permission_type_id=defs.ALLOWED_MENTENANCE
                        if menu_id == 2141003001 else defs.NO_AUTHORIZATION,
                        last_update_user=BACKYARD_USER.user_name,
                        last_update_timestamp=now)

                    permission_list.append(copy.deepcopy(permission_record))

            AccessPermission.objects.bulk_create(permission_list)

        ### ユーザ ###
        add_target_user_login_id = cur_ad_user_login_id_set - oase_ad_user_login_id_set
        add_user_bulk_list = []
        tmp_user = None
        for auser_login_id in add_target_user_login_id:
            ad_user_info = cur_ad_user_dict[auser_login_id]
            tmp_user = User(
                login_id=ad_user_info['login_id'],
                user_name=ad_user_info['display_name'],
                password='******',  # 仮...ログインでは使われない
                mail_address=ad_user_info['mail'] if
                len(ad_user_info['mail']) > 0 else 'oase_ad_collaboration_' +
                ad_user_info['login_id'],
                lang_mode_id=defs.LANG_MODE.JP,
                disp_mode_id=defs.DISP_MODE.DEFAULT,
                ad_data_flag='1',
                disuse_flag='0',
                last_update_user=BACKYARD_USER.user_name,
                last_update_timestamp=now)
            add_user_bulk_list.append(copy.deepcopy(tmp_user))

        self.__logger.logic_log(
            'LOSI11000', 'add_user_bulk_list: %s' % ','.join([
                u.user_name + '(' + u.login_id + ')'
                for u in add_user_bulk_list
            ]))
        if len(add_user_bulk_list) > 0:
            User.objects.bulk_create(add_user_bulk_list)

        ### ユーザグループ ###
        # ユーザとグループは新規分も考慮して再取得
        oase_ad_user_after = list(
            User.objects.filter(ad_data_flag='1', disuse_flag='0'))
        oase_ad_user_dict_after = {
            user.login_id: user
            for user in oase_ad_user_after
        }
        oase_ad_group_after = list(Group.objects.filter(ad_data_flag='1'))
        oase_ad_grp_dict_after = {
            grp.group_name: grp
            for grp in oase_ad_group_after
        }

        add_target_user_grp_key = cur_ad_user_grp_key_set - oase_ad_user_grp_key_set
        add_user_grp_bulk_list = []
        for auser_grp_key in add_target_user_grp_key:
            login_id, group_name = auser_grp_key.split(':')
            tmp_user_group = UserGroup(
                user_id=oase_ad_user_dict_after[login_id].user_id,
                group_id=oase_ad_grp_dict_after[group_name].group_id,
                ad_data_flag='1',
                last_update_user=BACKYARD_USER.user_name,
                last_update_timestamp=now)
            add_user_grp_bulk_list.append(copy.deepcopy(tmp_user_group))
            modified_user_id_link_user_grp.append(tmp_user_group.user_id)

        self.__logger.logic_log(
            'LOSI11000', 'add_user_grp_bulk_list: %s' % ','.join([
                str(ug.user_id) + '-' + str(ug.group_id)
                for ug in add_user_grp_bulk_list
            ]))
        if len(add_user_grp_bulk_list) > 0:
            UserGroup.objects.bulk_create(add_user_grp_bulk_list)

        # --------------------------------
        # 削除系(ユーザグループ → ユーザ → グループ)
        # --------------------------------
        ### ユーザグループ ###
        del_target_user_grp_key = oase_ad_user_grp_key_set - cur_ad_user_grp_key_set
        del_user_grp_id_list = []
        for user_grp_key in del_target_user_grp_key:
            del_user_grp_id_list.append(
                oase_ad_user_grp_dict[user_grp_key].user_group_id)
            modified_user_id_link_user_grp.append(
                oase_ad_user_grp_dict[user_grp_key].user_id)

        self.__logger.logic_log(
            'LOSI11000', 'del_user_grp_id_list: %s' %
            ','.join(map(str, del_user_grp_id_list)))
        if len(del_user_grp_id_list) > 0:
            UserGroup.objects.filter(ad_data_flag='1',
                                     pk__in=del_user_grp_id_list).delete()

        ### ユーザ ###
        del_target_user_login_id = oase_ad_user_login_id_set - cur_ad_user_login_id_set
        del_user_id_list = [
            oase_ad_user_dict[d].user_id for d in del_target_user_login_id
        ]

        if len(del_user_id_list) > 0:
            User.objects.filter(ad_data_flag='1',
                                pk__in=del_user_id_list).delete()

        ### グループ ###
        del_target_grp_name = oase_ad_grp_name_set - cur_ad_grp_name_set
        del_grp_id_list = [
            oase_ad_grp_dict[d].group_id for d in del_target_grp_name
        ]

        self.__logger.logic_log(
            'LOSI11000',
            'del_grp_id_list: %s' % ','.join(map(str, del_grp_id_list)))
        if len(del_grp_id_list) > 0:
            # delGrpQuerySet = Group.objects.filter(ad_data_flag='1',pk__in=del_grp_id_list)
            # delGrpQuerySet._raw_delete(delGrpQuerySet.db)
            AccessPermission.objects.filter(pk__in=del_grp_id_list).delete()
            Group.objects.filter(ad_data_flag='1',
                                 pk__in=del_grp_id_list).delete()

        # --------------------------------
        # 更新系(ユーザ)
        # --------------------------------
        ### ユーザ ###
        modify_target_user_login_id = oase_ad_user_login_id_set & cur_ad_user_login_id_set
        self.__logger.logic_log(
            'LOSI11000', 'modify_target_user_login_id: %s' %
            ','.join(map(str, modify_target_user_login_id)))
        for user_login_id in modify_target_user_login_id:
            db_user = oase_ad_user_dict[user_login_id]
            ad_user = cur_ad_user_dict[user_login_id]

            modify_flag = False
            if db_user.user_name != ad_user['display_name']:
                db_user.user_name = ad_user['display_name']
                modify_flag = True
            if db_user.mail_address != ad_user['mail']:
                if not (db_user.mail_address.startswith(
                        'oase_ad_collaboration_')
                        and len(ad_user['mail']) == 0):
                    db_user.mail_address = ad_user['mail']
                    modify_flag = True
            if modify_flag == True:
                db_user.last_update_user = BACKYARD_USER.user_name
                db_user.last_update_timestamp = now
                db_user.save()

        # 処理途中でユーザグループが変更されたユーザの最終更新日時を更新する
        self.__logger.logic_log(
            'LOSI11000', 'modified_user_id_link_user_grp: %s' %
            ','.join(map(str, modified_user_id_link_user_grp)))
        if len(modified_user_id_link_user_grp) > 0:
            User.objects.filter(ad_data_flag='1',pk__in=modified_user_id_link_user_grp) \
                .update(
                        last_update_user = BACKYARD_USER.user_name,
                        last_update_timestamp = now
                    )

        self.__logger.logic_log('LOSI00002', '')