def test_get_cognitor_user_pool_error_connect_cognito(self):
        attributesToGet = "email"

        # create boto3 client error
        mock_common_utils.set_error_response("500", "ERROR")
        self.create_mock_boto3_client_error()

        # call function test
        with self.assertRaises(PmError) as exception:
            aws_common.get_cognito_user_pools(trace_id, filter,
                                              attributesToGet)

        # check error
        cause_error = exception.exception.cause_error.response['Error']
        self.assertEqual(cause_error['Code'],
                         mock_common_utils.get_error_code())
        self.assertEqual(cause_error['Message'],
                         mock_common_utils.get_error_message())
    def test_get_cognitor_user_pool_success_by_not_exist_user(self):
        attributesToGet = "email"
        os.environ["COGNITO_USER_POOL_ID"] = user_pool_id

        # call function test
        list_users = aws_common.get_cognito_user_pools(trace_id, filter,
                                                       attributesToGet)

        # check result
        self.assertEqual(list_users, [])
 def test_get_cognitor_user_pool_success_with_param_require(self):
     os.environ["COGNITO_USER_POOL_ID"] = user_pool_id
     cognito_client = cognito_idp_utils.client_connect()
     with patch.object(cognito_client, 'list_users',
                       return_value=None) as mock_method:
         # call function test
         list_users = aws_common.get_cognito_user_pools(trace_id, filter)
         mock_method.assert_called_once_with(UserPoolId=user_pool_id,
                                             Filter='email= "' + filter +
                                             '\"')
     self.assertEqual([], list_users)
    def test_get_cognitor_user_pool_error_call_list_users(self):
        attributesToGet = "email"
        error_code = mock_common_utils.get_error_code()
        error_message = mock_common_utils.get_error_message()

        # create mock throw error when called function list_users
        with patch.object(boto3.client("cognito-idp"),
                          'list_users') as mock_method:
            mock_method.side_effect = ClientError(
                {'Error': {
                    'Code': error_code,
                    'Message': error_message
                }}, 'description error')

            # call function test
            with self.assertRaises(PmError) as exception:
                aws_common.get_cognito_user_pools(trace_id, filter,
                                                  attributesToGet)

        # check result
        cause_error = exception.exception.cause_error.response['Error']
        self.assertEqual(cause_error['Code'], error_code)
        self.assertEqual(cause_error['Message'], error_message)
    def test_get_cognitor_user_pool_success_by_exist_user(self):
        cognito_idp_utils.create_data_test_to_cognito_user(user_pool_id)
        list_user = []
        attributesToGet = "email"
        os.environ["COGNITO_USER_POOL_ID"] = user_pool_id

        # call function test
        list_users = aws_common.get_cognito_user_pools(trace_id, filter,
                                                       attributesToGet)

        # check result
        for user in list_users:
            for user_attr in user["Attributes"]:
                list_user.append(user_attr)
        self.assertEqual(DataTestCognitoIdp.data_response_success, list_user)
 def test_get_cognitor_user_pool_success_full_param(self):
     attributesToGet = "email"
     attributes_filter = "cognito:user_status"
     os.environ["COGNITO_USER_POOL_ID"] = user_pool_id
     cognito_client = cognito_idp_utils.client_connect()
     with patch.object(cognito_client, 'list_users',
                       return_value=None) as mock_method:
         # call function test
         list_users = aws_common.get_cognito_user_pools(
             trace_id, filter, attributesToGet, attributes_filter)
         mock_method.assert_called_once_with(
             AttributesToGet=[attributesToGet],
             UserPoolId=user_pool_id,
             Filter=attributes_filter + '= "' + filter + '\"')
     self.assertEqual([], list_users)
Пример #7
0
def apply_change_email(user_id, mail_before_change, data_body):
    pm_logger = common_utils.begin_logger(user_id, __name__,
                                          inspect.currentframe())
    # Parse JSON
    try:
        body_object = json.loads(data_body)
    except Exception as e:
        return common_utils.error_exception(MsgConst.ERR_REQUEST_202,
                                            HTTPStatus.BAD_REQUEST, e,
                                            pm_logger, True)

    mail_after_change = common_utils.get_value("mailAddress", body_object,
                                               None)
    caller_service_name = common_utils.get_value("callerServiceName",
                                                 body_object, None)

    mail_lang = common_utils.get_value("mailLang", body_object, None)

    # validate
    list_errors = validate_param_apply_change_email(user_id, mail_lang,
                                                    caller_service_name,
                                                    mail_before_change)
    if list_errors:
        return common_utils.error_validate(MsgConst.ERR_REQUEST_201,
                                           HTTPStatus.UNPROCESSABLE_ENTITY,
                                           list_errors, pm_logger)

    # Cognito UserPoolsから変更するメールアドレス{mailaddress}に該当するユーザー情報情報を取得します。
    try:
        list_users = aws_common.get_cognito_user_pools(user_id,
                                                       mail_after_change,
                                                       "email")
    except PmError as e:
        return common_utils.error_exception(MsgConst.ERR_COGNITO_501,
                                            HTTPStatus.INTERNAL_SERVER_ERROR,
                                            e, pm_logger, True)
    if list_users:
        return common_utils.error_common(MsgConst.ERR_302, HTTPStatus.CONFLICT,
                                         pm_logger)

    # メールアドレス変更申請テーブルから申請レコードを取得します。
    try:
        list_email_change_apply = pm_emailChangeApply.query_user_index(user_id)
    except PmError as e:
        return common_utils.error_exception(MsgConst.ERR_402,
                                            HTTPStatus.INTERNAL_SERVER_ERROR,
                                            e, pm_logger, True)
    if list_email_change_apply:
        return common_utils.error_common(MsgConst.ERR_302, HTTPStatus.CONFLICT,
                                         pm_logger)

    # メールアドレス変更申請テーブルに申請レコードを作成します。
    apply_id = common_utils.get_uuid4()
    time_to_live = common_utils.get_time_to_live(
        CommonConst.EMAIL_CHANGE_APPLY_EXPIRATION_DATE)
    try:
        pm_emailChangeApply.create(user_id, apply_id, mail_before_change,
                                   mail_after_change, time_to_live,
                                   caller_service_name)
    except PmError as e:
        return common_utils.error_exception(MsgConst.ERR_DB_403,
                                            HTTPStatus.INTERNAL_SERVER_ERROR,
                                            e, pm_logger, True)

    # get record PM_EmailChangeApply
    try:
        result = pm_emailChangeApply.query_key(user_id,
                                               apply_id,
                                               convert_response=True)
    except PmError as e:
        return common_utils.error_exception(MsgConst.ERR_402,
                                            HTTPStatus.INTERNAL_SERVER_ERROR,
                                            e, pm_logger, True)

    # S3から通知メール送信設定ファイルを取得します。
    try:
        config = FileUtils.read_yaml(user_id, CommonConst.S3_SETTING_BUCKET,
                                     CommonConst.NOTIFY_CONFIG_CIS_RESULT_MAIL)
    except PmError as e:
        pm_logger.error(
            "メールアドレス変更通知メール送信設定ファイルの取得に失敗しました。:s3://%s/%s",
            common_utils.get_environ(CommonConst.S3_SETTING_BUCKET),
            CommonConst.NOTIFY_CONFIG_CIS_RESULT_MAIL)
        return common_utils.error_exception(MsgConst.ERR_S3_702,
                                            HTTPStatus.INTERNAL_SERVER_ERROR,
                                            e, pm_logger, True)

    path_file_template = config[
        CommonConst.KEY_GET_PATH_FILE_TEMPLATE_MAIL_SERVICE.format(
            language=mail_lang, serviceName=caller_service_name)]
    # 通知メール本文を作成
    try:
        template_body_mail = FileUtils.read_decode(
            user_id, CommonConst.S3_SETTING_BUCKET, path_file_template)
    except PmError as e:
        pm_logger.error(
            "メールアドレス変更通知メール本文テンプレートファイルの取得に失敗しました。:s3://%s/%s",
            common_utils.get_environ(CommonConst.S3_SETTING_BUCKET),
            path_file_template)
        return common_utils.error_exception(MsgConst.ERR_S3_702,
                                            HTTPStatus.INTERNAL_SERVER_ERROR,
                                            e, pm_logger, True)

    # SESで通知メールを送信します。
    bcc_addresses = [mail_after_change]
    template_body_mail = Template(template_body_mail)
    body_mail = template_body_mail.render(ApplyID=apply_id)
    mail_subject = config[CommonConst.KEY_MAIL_SUBJECT_SERVICE.format(
        language=mail_lang, serviceName=caller_service_name)]
    mail_form = config[CommonConst.KEY_MAIL_FROM_SERVICE.format(
        serviceName=caller_service_name)]

    try:
        aws_common.send_email(user_id, config['ses.region'], mail_form,
                              bcc_addresses, mail_subject, body_mail)
    except PmError as e:
        pm_logger.error("通知メール送信に失敗しました。")
        return common_utils.error_exception(MsgConst.ERR_SES_801,
                                            HTTPStatus.INTERNAL_SERVER_ERROR,
                                            e, pm_logger, True)

    # return data response
    response = common_utils.get_response_by_response_body(
        HTTPStatus.CREATED, result)
    return common_utils.response(response, pm_logger)
Пример #8
0
def execute_delete_invalid_user(trace_id):
    pm_logger = common_utils.begin_logger(trace_id, __name__,
                                          inspect.currentframe())

    # Get Cognito UserPools status UNCONFIRMED
    try:
        list_user_unconfirmed = aws_common.get_cognito_user_pools(
            trace_id,
            CommonConst.COGNITO_STATUS_UNCONFIRMED,
            attribute_filter=CommonConst.ATTRIBUTE_FILTER_USER_STATUS)
    except PmError as e:
        pm_logger.error("[%s]Cognitoユーザー一覧情報取得に失敗しました。",
                        CommonConst.COGNITO_STATUS_UNCONFIRMED)
        raise common_utils.write_log_pm_error(e, pm_logger)

    # get current date
    current_date_time = date_utils.toDate(
        date_utils.get_current_date_by_format(
            date_utils.PATTERN_YYYYMMDDHHMMSS), date_utils.UTC)

    # loop user cognito UserPools status UNCONFIRMED
    for user_unconfirmed in list_user_unconfirmed:
        user_create_date = date_utils.toDate(
            date_utils.toString(user_unconfirmed['UserCreateDate'],
                                date_utils.PATTERN_YYYYMMDDHHMM),
            date_utils.UTC)
        if date_utils.difference_days(
                user_create_date,
                current_date_time) > CommonConst.TERM_USER_UNCONFIRMED_DAY:
            # delete Cognito UserPools status UNCONFIRMED update period greater than 1 days
            try:
                aws_common.delete_cognito_user_by_user_name(
                    trace_id, user_unconfirmed['Username'])
            except PmError as e:
                pm_logger.warning("CognitoでUserName = %sのユーザー削除に失敗しました。",
                                  user_unconfirmed['Username'])
                raise common_utils.write_log_pm_error(e, pm_logger)

    # Get Cognito UserPools status FORCE_CHANGE_PASSWORD
    try:
        list_user_force_change_password = aws_common.get_cognito_user_pools(
            trace_id,
            CommonConst.COGNITO_STATUS_FORCE_CHANGE_PASSWORD,
            attribute_filter=CommonConst.ATTRIBUTE_FILTER_USER_STATUS)
    except PmError as e:
        pm_logger.error("[%s]Cognitoユーザー一覧情報取得に失敗しました。",
                        CommonConst.COGNITO_STATUS_FORCE_CHANGE_PASSWORD)
        raise common_utils.write_log_pm_error(e, pm_logger)

    current_date = date_utils.toDate(
        date_utils.toString(current_date_time,
                            date_utils.PATTERN_YYYYMMDD_SLASH), date_utils.UTC)
    # loop user cognito UserPools status FORCE_CHANGE_PASSWORD
    for user_force_change_password in list_user_force_change_password:
        user_create_date = date_utils.toDate(
            date_utils.toString(user_force_change_password['UserCreateDate'],
                                date_utils.PATTERN_YYYYMMDD_SLASH),
            date_utils.UTC)
        if date_utils.difference_days(
                user_create_date, current_date
        ) > CommonConst.TERM_USER_FORCE_CHANGE_PASSWORD_DAY:
            # get list affiliations
            try:
                affiliations = pm_affiliation.query_userid_key(
                    trace_id, user_force_change_password['Username'])
            except PmError as e:
                pm_logger.warning(
                    "PM_Affiliationテーブルにて、UserID = %sのレコード取得に失敗しました。",
                    user_force_change_password['Username'])
                raise common_utils.write_log_pm_error(e, pm_logger)

            # delete affiliations user status FORCE_CHANGE_PASSWORD update period greater than 6 days
            for affiliation in affiliations:
                try:
                    pm_affiliation.delete_affiliation(
                        affiliation['UserID'], affiliation['OrganizationID'])
                except PmError as e:
                    pm_logger.warning(
                        "PM_Affiliationテーブルのレコード削除に失敗しました。UserID : %s / OrganizationID : %s",
                        affiliation['UserID'], affiliation['OrganizationID'])
                    raise common_utils.write_log_pm_error(e, pm_logger)

            # delete Cognito UserPools status FORCE_CHANGE_PASSWORD update period greater than 6 days
            try:
                aws_common.delete_cognito_user_by_user_name(
                    trace_id, user_force_change_password['Username'])
            except PmError as e:
                pm_logger.warning("CognitoでUserName = %sのユーザー削除に失敗しました。",
                                  user_force_change_password['Username'])
                raise common_utils.write_log_pm_error(e, pm_logger)
def execute_force_invites(trace_id, body_object, organization_id):
    pm_logger = common_utils.begin_logger(trace_id, __name__,
                                          inspect.currentframe())

    # parse json
    try:
        body_object_json = json.loads(body_object)
    except Exception as e:
        return common_utils.error_exception(MsgConst.ERR_REQUEST_202,
                                            HTTPStatus.BAD_REQUEST, e,
                                            pm_logger, True)

    caller_service_name = common_utils.get_value("callerServiceName",
                                                 body_object_json, None)
    mail_lang = common_utils.get_value("mailLang", body_object_json, None)
    mail_address = common_utils.get_value("mailAddress", body_object_json,
                                          None)
    authority = common_utils.get_value("authority", body_object_json, None)

    # validate param execute invite unregistered
    list_error = validate_param_invite_unregistered_user(
        trace_id, mail_lang, caller_service_name, mail_address, authority)
    if list_error:
        return common_utils.error_validate(MsgConst.ERR_REQUEST_201,
                                           HTTPStatus.UNPROCESSABLE_ENTITY,
                                           list_error, pm_logger)

    # get list cognito users
    try:
        list_users = aws_common.get_cognito_user_pools(trace_id, mail_address)
    except PmError as e:
        return common_utils.error_exception(MsgConst.ERR_COGNITO_501,
                                            HTTPStatus.INTERNAL_SERVER_ERROR,
                                            e, pm_logger, True)
    if list_users:
        return common_utils.error_common(MsgConst.ERR_302, HTTPStatus.CONFLICT,
                                         pm_logger)

    # regist Cognito UserPools
    temporary_password = ''
    pattern = re.compile(CommonConst.FORMAT_PASSWORD_TEMPORARY)
    while pattern.match(temporary_password) is None:
        temporary_password = common_utils.get_password_temporary(
            CommonConst.NUMBER_CHARACTERS_PASSWORD_TEMPORARY)

    user_attributes = [{"Name": "email", "Value": mail_address}]
    user_name = common_utils.get_uuid4()
    message_action = MessageAction.Suppress
    try:
        aws_common.process_admin_create_user_pools(trace_id, user_name,
                                                   user_attributes,
                                                   temporary_password,
                                                   message_action)
    except PmError as e:
        return common_utils.error_exception(MsgConst.ERR_COGNITO_501,
                                            HTTPStatus.INTERNAL_SERVER_ERROR,
                                            e, pm_logger, True)

    # enable confirm email
    try:
        user_attributes = [{'Name': 'email_verified', 'Value': 'true'}]
        aws_common.update_cognito_user_attributes(trace_id, user_name,
                                                  user_attributes)
    except PmError as e:
        return common_utils.error_exception(MsgConst.ERR_COGNITO_501,
                                            HTTPStatus.INTERNAL_SERVER_ERROR,
                                            e, pm_logger, True)

    # get affiliation
    try:
        affiliation = pm_affiliation.get_affiliation(user_name,
                                                     organization_id)
    except PmError as e:
        return common_utils.error_exception(MsgConst.ERR_402,
                                            HTTPStatus.INTERNAL_SERVER_ERROR,
                                            e, pm_logger, True)
    if affiliation and affiliation["InvitationStatus"] != InvitationStatus.Deny:
        return common_utils.error_common(MsgConst.ERR_302, HTTPStatus.CONFLICT,
                                         pm_logger)

    # get organization
    try:
        organization = pm_organizations.get_organization(
            trace_id, organization_id)
    except PmError as e:
        return common_utils.error_exception(MsgConst.ERR_402,
                                            HTTPStatus.INTERNAL_SERVER_ERROR,
                                            e, pm_logger, True)
    if len(organization) == 0:
        return common_utils.error_common(MsgConst.ERR_301,
                                         HTTPStatus.NOT_FOUND, pm_logger)

    # create affiliation
    try:
        pm_affiliation.create_affiliation(trace_id, mail_address, user_name,
                                          organization_id, authority,
                                          InvitationStatus.Invited)
    except PmError as e:
        return common_utils.error_exception(MsgConst.ERR_DB_403,
                                            HTTPStatus.INTERNAL_SERVER_ERROR,
                                            e, pm_logger, True)

    # Get data affiliation
    try:
        affiliation_result = pm_affiliation.get_affiliation(
            user_name, organization_id, True)
    except PmError as e:
        return common_utils.error_exception(MsgConst.ERR_402,
                                            HTTPStatus.INTERNAL_SERVER_ERROR,
                                            e, pm_logger, True)

    # Get data user_attribute
    try:
        user_attribute = pm_userAttribute.query_key(trace_id)
    except PmError as e:
        return common_utils.error_exception(MsgConst.ERR_402,
                                            HTTPStatus.INTERNAL_SERVER_ERROR,
                                            e, pm_logger, True)

    # S3から通知メール送信設定ファイルを取得します。
    try:
        config = FileUtils.read_yaml(trace_id, CommonConst.S3_SETTING_BUCKET,
                                     CommonConst.NOTIFY_CONFIG_CIS_RESULT_MAIL)
    except PmError as e:
        pm_logger.error("メール送信設定ファイルの取得に失敗しました。:s3://{0}/{1}".format(
            common_utils.get_environ(CommonConst.S3_SETTING_BUCKET),
            CommonConst.NOTIFY_CONFIG_CIS_RESULT_MAIL))
        return common_utils.error_exception(MsgConst.ERR_S3_702,
                                            HTTPStatus.INTERNAL_SERVER_ERROR,
                                            e, pm_logger, True)

    # メッセージ本文を作成します。
    path_file_template = config[
        CommonConst.KEY_GET_PATH_FILE_TEMPLATE_USER_INVITE_MAIL.format(
            language=mail_lang, serviceName=caller_service_name)]
    try:
        template_body_mail = FileUtils.read_decode(
            trace_id, CommonConst.S3_SETTING_BUCKET, path_file_template)
    except PmError as e:
        pm_logger.error("招待メール本文テンプレートファイルの取得に失敗しました。:s3://{0}/{1}".format(
            common_utils.get_environ(CommonConst.S3_SETTING_BUCKET),
            path_file_template))
        return common_utils.error_exception(MsgConst.ERR_S3_702,
                                            HTTPStatus.INTERNAL_SERVER_ERROR,
                                            e, pm_logger, True)

    # SESで通知メールを送信します。
    bcc_addresses = [mail_address]
    user_name_sign_in = common_utils.get_value("UserName", user_attribute,
                                               None)
    if not user_name_sign_in:
        try:
            affiliation_sign_in = pm_affiliation.get_affiliation(
                trace_id, organization_id)
        except PmError as e:
            return common_utils.error_exception(
                MsgConst.ERR_402, HTTPStatus.INTERNAL_SERVER_ERROR, e,
                pm_logger, True)
        user_name_sign_in = common_utils.get_value("MailAddress",
                                                   affiliation_sign_in, None)

    organization_name = common_utils.get_value("OrganizationName",
                                               organization, None)
    time_zone = date_utils.get_time_zone_by_language(mail_lang)
    time_to_live_date = date_utils.get_current_date() + timedelta(days=6)
    time_to_live = date_utils.toString(time_to_live_date,
                                       date_utils.PATTERN_YYYYMMDD_SLASH,
                                       time_zone)
    template_body_mail = Template(template_body_mail)
    context = {
        'mailAddress': mail_address,
        'userName': user_name_sign_in,
        'organizationName': organization_name,
        'temporaryPassword': temporary_password,
        'timeToLive': time_to_live
    }
    body_mail = template_body_mail.render(context)
    mail_subject = config[CommonConst.KEY_MAIL_SUBJECT_USER_INVITE.format(
        language=mail_lang, serviceName=caller_service_name)]
    mail_from = config[CommonConst.KEY_INVITE_MAIL_FROM_SERVICE.format(
        serviceName=caller_service_name)]
    ses_region = config['ses.region']
    try:
        aws_common.send_email(user_name, ses_region, mail_from, bcc_addresses,
                              mail_subject, body_mail)
    except PmError as e:
        pm_logger.error("通知メール送信に失敗しました。")
        return common_utils.error_exception(MsgConst.ERR_SES_801,
                                            HTTPStatus.INTERNAL_SERVER_ERROR,
                                            e, pm_logger, True)

    response = common_utils.get_response_by_response_body(
        HTTPStatus.CREATED, affiliation_result)

    # return data response
    return common_utils.response(response, pm_logger)
Пример #10
0
def create_invite(trace_id, organization_id, data_body):
    pm_logger = common_utils.begin_logger(trace_id, __name__,
                                          inspect.currentframe())

    attributesToGet = "email_verified"
    key = "Name"
    value = "Value"

    # Parse JSON
    try:
        body_object = json.loads(data_body)
        mail_address = body_object["mailAddress"]
        authority = body_object["authority"]
    except Exception as e:
        return common_utils.error_exception(MsgConst.ERR_REQUEST_202,
                                            HTTPStatus.BAD_REQUEST, e,
                                            pm_logger, True)

    # validate authority
    list_error = validate_params_invite(trace_id, mail_address, authority)
    if list_error:
        return common_utils.error_validate(MsgConst.ERR_REQUEST_201,
                                           HTTPStatus.UNPROCESSABLE_ENTITY,
                                           list_error, pm_logger)

    # get list cognito users
    try:
        list_users = aws_common.get_cognito_user_pools(trace_id, mail_address,
                                                       attributesToGet)
        if len(list_users) == 0:
            list_error = []
            list_error.append(
                common_utils.get_error_validate(MsgConst.ERR_VAL_999,
                                                "mail_address", mail_address))
            return common_utils.error_validate(MsgConst.ERR_REQUEST_201,
                                               HTTPStatus.UNPROCESSABLE_ENTITY,
                                               list_error, pm_logger)

        list_user_verified = []
        for user in list_users:
            # get value of key email_verified in attribute
            for user_attr in user["Attributes"]:
                if common_utils.check_key(
                        key, user_attr) and user_attr[key] == attributesToGet:
                    email_verified = user_attr[value]

            # check email_verified is true
            if email_verified == "true":
                list_user_verified.append(user["Username"])
        if len(list_user_verified) == 0:
            list_error = []
            list_error.append(
                common_utils.get_error_validate(MsgConst.ERR_VAL_999,
                                                "mail_address", mail_address))
            return common_utils.error_validate(MsgConst.ERR_REQUEST_201,
                                               HTTPStatus.UNPROCESSABLE_ENTITY,
                                               list_error, pm_logger)
    except PmError as e:
        return common_utils.error_exception(MsgConst.ERR_COGNITO_501,
                                            HTTPStatus.INTERNAL_SERVER_ERROR,
                                            e, pm_logger, True)

    # get affiliation
    try:
        user_id = list_user_verified[0]
        affiliation = pm_affiliation.get_affiliation(user_id, organization_id)
    except PmError as e:
        return common_utils.error_exception(MsgConst.ERR_402,
                                            HTTPStatus.INTERNAL_SERVER_ERROR,
                                            e, pm_logger, True)
    if affiliation and affiliation["InvitationStatus"] != InvitationStatus.Deny:
        return common_utils.error_common(MsgConst.ERR_302, HTTPStatus.CONFLICT,
                                         pm_logger)

    # get organization
    try:
        organization = pm_organizations.get_organization(
            trace_id, organization_id)
    except PmError as e:
        return common_utils.error_exception(MsgConst.ERR_402,
                                            HTTPStatus.INTERNAL_SERVER_ERROR,
                                            e, pm_logger, True)

    if not organization:
        return common_utils.error_common(MsgConst.ERR_301,
                                         HTTPStatus.NOT_FOUND, pm_logger)

    # create affiliation
    try:
        pm_affiliation.create_affiliation(trace_id, mail_address, user_id,
                                          organization_id, authority,
                                          InvitationStatus.Invited)
    except PmError as e:
        return common_utils.error_exception(MsgConst.ERR_DB_403,
                                            HTTPStatus.INTERNAL_SERVER_ERROR,
                                            e, pm_logger, True)
    # get affiliation just create new to response
    try:
        affiliation_created = pm_affiliation.get_affiliation(
            user_id, organization_id, True)
    except PmError as e:
        return common_utils.error_exception(MsgConst.ERR_402,
                                            HTTPStatus.INTERNAL_SERVER_ERROR,
                                            e, pm_logger, True)

    response = common_utils.get_response_by_response_body(
        HTTPStatus.CREATED, affiliation_created)

    # return data response
    return common_utils.response(response, pm_logger)