Esempio n. 1
0
    def setUp(self):
        dotenv_path = Path(os.getcwd()).joinpath('.env')
        if os.path.exists(dotenv_path):
            load_dotenv(dotenv_path)

        # create pm_orgNotifyMailDestinaltions
        pm_orgNotifyMailDestinations.create(
            trace_id, notify_mail_template['OrganizationID'],
            notify_mail_template['NotifyCode'],
            notify_mail_template['Destinations'])

        # create pm_orgNotifySlack
        pm_orgNotifySlack.create(trace_id,
                                 notify_slack_template['OrganizationID'],
                                 notify_slack_template['NotifyCode'],
                                 notify_slack_template['WebhookURL'],
                                 notify_slack_template['Mentions'])

        num = 1
        while num < 4:
            # Create Affiliation
            tmp_affiliation = copy.copy(affiliation_template)
            tmp_affiliation['MailAddress'] = mail_address.format(str(num))
            tmp_affiliation['UserID'] = user_id.format(str(num))
            tmp_affiliation['Authority'] = num
            pm_affiliation.create_affiliation(
                trace_id, tmp_affiliation['MailAddress'],
                tmp_affiliation['UserID'], tmp_affiliation['OrganizationID'],
                tmp_affiliation['Authority'],
                tmp_affiliation['InvitationStatus'])
            num += 1
Esempio n. 2
0
    def setUp(self):
        dotenv_path = Path(os.getcwd()).joinpath('.env')
        if os.path.exists(dotenv_path):
            load_dotenv(dotenv_path)
        num = 0
        while num < 4:
            tmp_affiliation = copy.copy(affiliation_template)
            tmp_affiliation['MailAddress'] = affiliation_template[
                'MailAddress'].format(str(num))
            tmp_affiliation['UserID'] = affiliation_template['UserID'].format(
                str(num))
            tmp_affiliation['OrganizationID'] = affiliation_template[
                'OrganizationID'].format(str(num))
            tmp_affiliation['InvitationStatus'] = num % 3 - 1
            if (num < 3):
                tmp_affiliation['Authority'] = num + 1
            else:
                tmp_affiliation['Authority'] = 3

            pm_affiliation.create_affiliation(
                trace_id, tmp_affiliation['MailAddress'],
                tmp_affiliation['UserID'], tmp_affiliation['OrganizationID'],
                tmp_affiliation['Authority'],
                tmp_affiliation['InvitationStatus'])

            # Create data table Organization
            tmp_organization = copy.copy(organization_template)
            tmp_organization[
                'OrganizationID'] = affiliation_org_id_template.format(
                    str(num))
            pm_organizations.create_organization(
                trace_id, tmp_organization['OrganizationID'],
                tmp_organization['OrganizationName'],
                tmp_organization['Contract'],
                tmp_organization['ContractStatus'])

            num += 1
Esempio n. 3
0
    def setUp(self):
        dotenv_path = Path(os.getcwd()).joinpath('.env')
        if os.path.exists(dotenv_path):
            load_dotenv(dotenv_path)
        # 所属ユーザー(オーナー)の作成
        registered_affiliation = copy.copy(affiliation_template)
        registered_affiliation['MailAddress'] = registered_affiliation_address
        registered_affiliation['UserID'] = affiliation_template[
            'UserID'].format("registered")

        registered_affiliation['OrganizationID'] = registered_organization_id
        registered_affiliation[
            'InvitationStatus'] = InvitationStatus.Belong.value
        registered_affiliation['Authority'] = Authority.Owner.value
        pm_affiliation.create_affiliation(
            trace_id, registered_affiliation['MailAddress'],
            registered_affiliation['UserID'],
            registered_affiliation['OrganizationID'],
            registered_affiliation['Authority'],
            registered_affiliation['InvitationStatus'])
        # 未所属ユーザーの作成
        not_belong_affiliation = copy.copy(affiliation_template)
        not_belong_affiliation['MailAddress'] = not_belong_affiliation_address
        not_belong_affiliation['UserID'] = affiliation_template[
            'UserID'].format("not_belong")
        not_belong_affiliation['OrganizationID'] = not_belong_organization_id
        not_belong_affiliation[
            'InvitationStatus'] = InvitationStatus.Belong.value
        registered_affiliation['Authority'] = Authority.Viewer.value
        not_belong_affiliation['Authority'] = registered_affiliation['Authority']

        pm_affiliation.create_affiliation(
            trace_id, not_belong_affiliation['MailAddress'],
            not_belong_affiliation['UserID'],
            not_belong_affiliation['OrganizationID'],
            not_belong_affiliation['Authority'],
            not_belong_affiliation['InvitationStatus'])
        # 権限不足ユーザー(ビューワー)の作成
        not_enough_permission_affiliation = copy.copy(affiliation_template)
        not_enough_permission_affiliation[
            'MailAddress'] = not_enough_permission_affiliation_address
        not_enough_permission_affiliation[
            'OrganizationID'] = registered_organization_id
        not_enough_permission_affiliation['UserID'] = affiliation_template[
            'UserID'].format("not_enough_permission")
        not_enough_permission_affiliation[
            'InvitationStatus'] = InvitationStatus.Belong.value
        not_enough_permission_affiliation['Authority'] = Authority.Viewer.value
        pm_affiliation.create_affiliation(
            trace_id, not_enough_permission_affiliation['MailAddress'],
            not_enough_permission_affiliation['UserID'],
            not_enough_permission_affiliation['OrganizationID'],
            not_enough_permission_affiliation['Authority'],
            not_enough_permission_affiliation['InvitationStatus'])
Esempio n. 4
0
    def setUp(self):
        dotenv_path = Path(os.getcwd()).joinpath('.env')
        if os.path.exists(dotenv_path):
            load_dotenv(dotenv_path)

        # Create Organization
        pm_organizations.create_organization(
            trace_id, organization_template['OrganizationID'],
            organization_template['OrganizationName'],
            organization_template['Contract'],
            organization_template['ContractStatus'])

        # Create Projects
        pm_projects.create_projects(trace_id, projects_template['ProjectID'],
                                    projects_template['ProjectName'],
                                    projects_template['Description'],
                                    projects_template['OrganizationID'])

        # Create awscoop
        pm_awsAccountCoops.create_awscoops(
            trace_id, awscoops_template["CoopID"],
            awscoops_template["AWSAccount"],
            awscoops_template['AWSAccountName'], awscoops_template["RoleName"],
            awscoops_template["ExternalID"], awscoops_template["Description"],
            awscoops_template["Effective"],
            awscoops_template["OrganizationID"],
            awscoops_template["ProjectID"])

        # Create awscoop members enable
        pm_awsAccountCoops.create_awscoops(
            trace_id, coop_id_members_enable, awscoops_template["AWSAccount"],
            awscoops_template['AWSAccountName'], awscoops_template["RoleName"],
            awscoops_template["ExternalID"], awscoops_template["Description"],
            awscoops_template["Effective"],
            awscoops_template["OrganizationID"],
            awscoops_template["ProjectID"])
        attribute = {'Members': {"Value": 1}}
        pm_awsAccountCoops.update_awscoops(trace_id, coop_id_members_enable,
                                           attribute)

        # Create awscoop delete
        tmp_awscoops = copy.copy(awscoops_template)
        tmp_awscoops["CoopID"] = coop_id.format(str(999))
        pm_awsAccountCoops.create_awscoops(
            trace_id, tmp_awscoops["CoopID"], tmp_awscoops["AWSAccount"],
            awscoops_template['AWSAccountName'], tmp_awscoops["RoleName"],
            tmp_awscoops["ExternalID"], tmp_awscoops["Description"],
            tmp_awscoops["Effective"], tmp_awscoops["OrganizationID"],
            tmp_awscoops["ProjectID"])

        num = 1
        while num < 4:
            # Create Affiliation
            tmp_affiliation = copy.copy(affiliation_template)
            tmp_affiliation['MailAddress'] = mail_address.format(str(num))
            tmp_affiliation['UserID'] = user_id.format(str(num))
            tmp_affiliation['Authority'] = num
            pm_affiliation.create_affiliation(
                trace_id, tmp_affiliation['MailAddress'],
                tmp_affiliation['UserID'], tmp_affiliation['OrganizationID'],
                tmp_affiliation['Authority'],
                tmp_affiliation['InvitationStatus'])
            num += 1
Esempio n. 5
0
    def setUp(self):
        dotenv_path = Path(os.getcwd()).joinpath('.env')
        if os.path.exists(dotenv_path):
            load_dotenv(dotenv_path)
        num = 0
        while num < 2:
            # Create data table Affiliation
            tmp_affiliation = copy.copy(affiliation_template)
            tmp_affiliation['MailAddress'] = affiliation_template[
                'MailAddress'].format(str(num))
            tmp_affiliation['UserID'] = affiliation_template['UserID'].format(
                str(num))
            if num == 1:
                tmp_affiliation['Authority'] = 3
            else:
                tmp_affiliation['Authority'] = num
            tmp_affiliation[
                'OrganizationID'] = template_organization_id.format(
                    str(num))
            pm_affiliation.create_affiliation(
                trace_id, tmp_affiliation['MailAddress'],
                tmp_affiliation['UserID'], tmp_affiliation['OrganizationID'],
                tmp_affiliation['Authority'],
                tmp_affiliation['InvitationStatus'])

            # Create data table Organization
            tmp_organization = copy.copy(organization_template)
            tmp_organization[
                'OrganizationID'] = template_organization_id.format(
                    str(num))
            pm_organizations.create_organization(
                trace_id, tmp_organization['OrganizationID'],
                tmp_organization['OrganizationName'],
                tmp_organization['Contract'],
                tmp_organization['ContractStatus'])

            # Create data table Projects
            tmp_projects = copy.copy(projects_template)
            tmp_projects['ProjectID'] = projects_id_template.format(str(num))
            pm_projects.create_projects(trace_id, tmp_projects['ProjectID'],
                                        tmp_projects['ProjectName'],
                                        tmp_projects['Description'],
                                        tmp_projects['OrganizationID'])
            num += 1

        # creat data test function delete organaization
        while num < 4:
            tmp_affiliation = copy.copy(affiliation_template)
            tmp_affiliation['MailAddress'] = affiliation_template[
                'MailAddress'].format(str(num))
            tmp_affiliation['UserID'] = affiliation_template['UserID'].format(
                str(num))
            tmp_affiliation['OrganizationID'] = affiliation_template[
                'OrganizationID'].format(str(num))
            tmp_affiliation['InvitationStatus'] = num % 3 - 1
            if (num < 3):
                tmp_affiliation['Authority'] = num + 1
            else:
                tmp_affiliation['Authority'] = 3

            pm_affiliation.create_affiliation(
                trace_id, tmp_affiliation['MailAddress'],
                tmp_affiliation['UserID'], tmp_affiliation['OrganizationID'],
                tmp_affiliation['Authority'],
                tmp_affiliation['InvitationStatus'])

            # Create data table Organization
            tmp_organization = copy.copy(organization_template)
            tmp_organization[
                'OrganizationID'] = template_organization_id.format(str(num))
            pm_organizations.create_organization(
                trace_id, tmp_organization['OrganizationID'],
                tmp_organization['OrganizationName'],
                tmp_organization['Contract'],
                tmp_organization['ContractStatus'])

            num += 1
Esempio n. 6
0
    for awsAccountCoop in awsAccountCoops:
        pm_awsAccountCoops.create_awscoops(
            trace_id, awsAccountCoop['CoopID'], awsAccountCoop['AWSAccount'],
            awsAccountCoop['AWSAccountName'], awsAccountCoop['RoleName'],
            awsAccountCoop['ExternalID'], awsAccountCoop['Description'],
            awsAccountCoop['Effective'], awsAccountCoop['OrganizationID'],
            awsAccountCoop['ProjectID'])

    for project in projects:
        pm_projects.create_projects(trace_id, project['ProjectID'],
                                    project['ProjectName'],
                                    project['Description'],
                                    project['OrganizationID'])

    for organization in organizations:
        pm_organizations.create_organization(trace_id,
                                             organization['OrganizationID'],
                                             organization['OrganizationName'],
                                             organization['Contract'],
                                             organization['ContractStatus'])

    for affiliation in affiliations:
        pm_affiliation.create_affiliation(trace_id, affiliation['MailAddress'],
                                          affiliation['UserID'],
                                          affiliation['OrganizationID'],
                                          affiliation['Authority'],
                                          affiliation['InvitationStatus'])

except Exception as error:
    raise PmError(cause_error=error)
Esempio n. 7
0
    def setUp(self):
        dotenv_path = Path(os.getcwd()).joinpath('.env')
        if os.path.exists(dotenv_path):
            load_dotenv(dotenv_path)

        # Create Organization
        pm_organizations.create_organization(
            trace_id, organization_template['OrganizationID'],
            organization_template['OrganizationName'],
            organization_template['Contract'],
            organization_template['ContractStatus'])

        # Create Projects
        pm_projects.create_projects(trace_id, projects_template['ProjectID'],
                                    projects_template['ProjectName'],
                                    projects_template['Description'],
                                    projects_template['OrganizationID'])

        # Create ReportJobDefs
        num = 1
        while num < 4:
            if num == 1:
                report_job_def_aws['Code'] = code_aws
                report_job_def_aws['JobDefinition'] = job_definition_aws
            elif num == 2:
                report_job_def_aws['Code'] = code_json
                report_job_def_aws['JobDefinition'] = job_definition_json
            else:
                report_job_def_aws['Code'] = code_excel
                report_job_def_aws['JobDefinition'] = job_definition_excel
            pm_batchJobDefs.create_report_job_def(
                trace_id, report_job_def_aws['Code'],
                report_job_def_aws['JobDefinition'],
                report_job_def_aws['JobQueue'], report_job_def_aws['MaxRetry'],
                report_job_def_aws['Environment'])
            num += 1

        num = 1
        while num < 4:
            # Create Affiliation
            tmp_affiliation = copy.copy(affiliation_template)
            tmp_affiliation['MailAddress'] = mail_address.format(str(num))
            tmp_affiliation['UserID'] = user_id.format(str(num))
            tmp_affiliation['Authority'] = num
            pm_affiliation.create_affiliation(
                trace_id, tmp_affiliation['MailAddress'],
                tmp_affiliation['UserID'], tmp_affiliation['OrganizationID'],
                tmp_affiliation['Authority'],
                tmp_affiliation['InvitationStatus'])
            # Create list reports
            tmp_report = copy.copy(reports_template)
            tmp_report['ReportStatus'] = num + 1
            pm_reports.create_report(
                trace_id, tmp_report['ReportID'].format(str(num)),
                tmp_report['ReportName'], tmp_report['GenerateUser'],
                tmp_report['AWSAccounts'], tmp_report['ReportStatus'],
                tmp_report['ResourceInfoPath'], tmp_report['JsonOutputPath'],
                tmp_report['JsonOutputTime'], tmp_report['HTMLOutputStatus'],
                tmp_report['HTMLPath'], tmp_report['HTMLOutputTime'],
                tmp_report['ExcelOutputStatus'], tmp_report['ExcelPath'],
                tmp_report['ExcelOutputTime'], tmp_report['SchemaVersion'],
                tmp_report['OrganizationID'], tmp_report['ProjectID'])
            num += 1

        pm_reports.create_report(
            trace_id, tmp_report['ReportID'].format(str(4)),
            tmp_report['ReportName'], tmp_report['GenerateUser'],
            tmp_report['AWSAccounts'], 4, tmp_report['ResourceInfoPath'],
            tmp_report['JsonOutputPath'], tmp_report['JsonOutputTime'],
            tmp_report['HTMLOutputStatus'], tmp_report['HTMLPath'],
            tmp_report['HTMLOutputTime'], 2, tmp_report['ExcelPath'],
            tmp_report['ExcelOutputTime'], tmp_report['SchemaVersion'],
            tmp_report['OrganizationID'], tmp_report['ProjectID'])
        pm_reports.create_report(
            trace_id, tmp_report['ReportID'].format(str(5)),
            tmp_report['ReportName'], tmp_report['GenerateUser'],
            tmp_report['AWSAccounts'], 4, tmp_report['ResourceInfoPath'],
            tmp_report['JsonOutputPath'], tmp_report['JsonOutputTime'],
            tmp_report['HTMLOutputStatus'], tmp_report['HTMLPath'],
            tmp_report['HTMLOutputTime'], 1, tmp_report['ExcelPath'],
            tmp_report['ExcelOutputTime'], tmp_report['SchemaVersion'],
            tmp_report['OrganizationID'], tmp_report['ProjectID'])
        pm_reports.create_report(
            trace_id, tmp_report['ReportID'].format(str(6)),
            tmp_report['ReportName'], tmp_report['GenerateUser'],
            tmp_report['AWSAccounts'], 2, tmp_report['ResourceInfoPath'],
            tmp_report['JsonOutputPath'], tmp_report['JsonOutputTime'],
            tmp_report['HTMLOutputStatus'], tmp_report['HTMLPath'],
            tmp_report['HTMLOutputTime'], 2, tmp_report['ExcelPath'],
            tmp_report['ExcelOutputTime'], tmp_report['SchemaVersion'],
            tmp_report['OrganizationID'], tmp_report['ProjectID'])
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)
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)
def create_organization(trace_id, email, data_body):
    pm_logger = common_utils.begin_logger(trace_id, __name__,
                                          inspect.currentframe())
    # Parse JSON
    try:
        body_object = json.loads(data_body)
        organization_name = body_object["name"]
        contract = body_object["contract"]
        contract_status = body_object["contractStatus"]
    except Exception as e:
        return common_utils.error_exception(MsgConst.ERR_REQUEST_202,
                                            HTTPStatus.BAD_REQUEST, e,
                                            pm_logger, True)

    # Validate
    list_error = validate_insert(organization_name, contract, contract_status)
    if list_error:
        return common_utils.error_validate(MsgConst.ERR_REQUEST_201,
                                           HTTPStatus.UNPROCESSABLE_ENTITY,
                                           list_error, pm_logger)

    # Create Organization
    organization_id = str(uuid.uuid4())
    try:
        pm_organizations.create_organization(trace_id, organization_id,
                                             organization_name, contract,
                                             contract_status)
    except PmError as e:
        return common_utils.error_exception(MsgConst.ERR_DB_403,
                                            HTTPStatus.INTERNAL_SERVER_ERROR,
                                            e, pm_logger, True)

    # Create Affiliation
    try:
        pm_affiliation.create_affiliation(trace_id, email, trace_id,
                                          organization_id,
                                          Authority.Owner.value,
                                          InvitationStatus.Belong.value)
    except PmError as e:
        # Delete Organizations
        pm_organizations.delete_organization(trace_id, organization_id)

        # 例外スタックトレースをログに出力する。
        return common_utils.error_exception(MsgConst.ERR_DB_403,
                                            HTTPStatus.INTERNAL_SERVER_ERROR,
                                            e, pm_logger, True)

    # 組織情報を取得します。
    try:
        organization_item = pm_organizations.get_organization(
            trace_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, organization_item)

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