def change_invite(trace_id, organization_id, user_id, invite):
    pm_logger = common_utils.begin_logger(trace_id, __name__,
                                          inspect.currentframe())

    # get affiliation
    try:
        affiliation = pm_affiliation.query_affiliation_filter_invite(
            trace_id, user_id, organization_id, InvitationStatus.Invited)
    except PmError as e:
        return common_utils.error_exception(MsgConst.ERR_402,
                                            HTTPStatus.INTERNAL_SERVER_ERROR,
                                            e, pm_logger, True)

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

    # update invite
    attribute = {'InvitationStatus': {"Value": invite}}
    updated_at = affiliation[0]['UpdatedAt']
    try:
        pm_affiliation.update_affiliation(trace_id, user_id, organization_id,
                                          attribute, updated_at)
    except PmError as err:
        return common_utils.error_exception(MsgConst.ERR_DB_404,
                                            HTTPStatus.INTERNAL_SERVER_ERROR,
                                            err, pm_logger, True)

    # Get data update
    try:
        affiliation_result = 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_result)

    # return data response
    return common_utils.response(response, pm_logger)
Exemplo n.º 2
0
def create_notifymail(trace_id, organization_id, data_body):
    pm_logger = common_utils.begin_logger(trace_id, __name__,
                                          inspect.currentframe())
    # リクエストボディのJSONでパースエラーが発生した場合は、ログを出力してエラーレスポンスを返します。
    try:
        body_object = json.loads(data_body)
        notify_code = body_object["notifyCode"]
        users = body_object["users"]
    except Exception as e:
        return common_utils.error_exception(MsgConst.ERR_REQUEST_202,
                                            HTTPStatus.BAD_REQUEST, e,
                                            pm_logger, True)

    # 全てのチェックを行い、エラーがあった場合はログを出力してエラーレスポンスを返します。
    list_error = validate_notifymail(notify_code, users)
    if list_error:
        return common_utils.error_validate(MsgConst.ERR_REQUEST_201,
                                           HTTPStatus.UNPROCESSABLE_ENTITY,
                                           list_error, pm_logger)

    # 宛先ユーザーのメールアドレスを取得します。
    destinations = []
    for user_id in users:
        try:
            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 (not affiliation):
            continue

        # 宛先ユーザー配列は、ユーザーIDとメールアドレスを属性として持つオブジェクトの配列として表現します。
        destination = {
            "UserID": user_id,
            "MailAddress": affiliation['MailAddress']
        }
        destinations.append(destination)

    if len(destinations) == 0:
        list_error = []
        list_error.append(
            common_utils.get_error_validate(MsgConst.ERR_VAL_999, "users",
                                            users))
        return common_utils.error_validate(MsgConst.ERR_REQUEST_201,
                                           HTTPStatus.UNPROCESSABLE_ENTITY,
                                           list_error, pm_logger)

    # 宛先情報を作成します。
    try:
        pm_orgNotifyMailDestinations.create(trace_id, organization_id,
                                            notify_code, destinations)
    except PmError as e:
        return common_utils.error_exception(MsgConst.ERR_DB_403,
                                            HTTPStatus.INTERNAL_SERVER_ERROR,
                                            e, pm_logger, True)

    # 宛先情報を取得します。
    try:
        result = pm_orgNotifyMailDestinations.query_key(
            trace_id, organization_id, notify_code, 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, result)

    # return data response
    return common_utils.response(response, 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)
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 update_authority(trace_id, organization_id, user_id, data_body):
    pm_logger = common_utils.begin_logger(trace_id, __name__,
                                          inspect.currentframe())

    # Parse JSON
    try:
        body_object = json.loads(data_body)
        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
    list_error = common_utils.validate_authority(trace_id, authority)
    if list_error:
        return common_utils.error_validate(MsgConst.ERR_REQUEST_201,
                                           HTTPStatus.UNPROCESSABLE_ENTITY,
                                           list_error, pm_logger)

    # check the update condition
    if user_id == trace_id and authority != Authority.Owner.value:
        try:
            count = pm_affiliation.query_users_check_authority_count(
                trace_id, user_id, organization_id, Authority.Owner)
        except PmError as e:
            return common_utils.error_exception(
                MsgConst.ERR_402, HTTPStatus.INTERNAL_SERVER_ERROR, e,
                pm_logger, True)
        if count == 0:
            return common_utils.error_common(MsgConst.ERR_REQUEST_203,
                                             HTTPStatus.PRECONDITION_FAILED,
                                             pm_logger)
    # get user to update
    try:
        user = pm_affiliation.query(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 not user:
        return common_utils.error_common(MsgConst.ERR_301,
                                         HTTPStatus.NOT_FOUND, pm_logger)

    # update user authority
    attribute = {'Authority': {"Value": authority}}
    updated_at = user[0]['UpdatedAt']
    try:
        pm_affiliation.update_affiliation(trace_id, user_id, organization_id,
                                          attribute, updated_at)
    except PmError as err:
        return common_utils.error_exception(MsgConst.ERR_DB_404,
                                            HTTPStatus.INTERNAL_SERVER_ERROR,
                                            err, pm_logger, True)

    # Get data update
    try:
        user_result = 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.OK, user_result)

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