Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat(users): Send email to a user when it's role is deleted. (#11373)
Grovy-31704948dbc8155b
diff --git a/crates/api_models/src/events/user_role.rs b/crates/api_models/src/events/user_role.rsindex 7b6413b27f..6a89f4ead0 100644--- a/crates/api_models/src/events/user_role.rs+++ b/crates/api_models/src/events/user_role.rs@@ -7,8 +7,8 @@ use crate::user_role::{ParentGroupInfoRequest, RoleInfoResponseNew, RoleInfoResponseWithParentsGroup,RoleInfoWithGroupsResponse, RoleInfoWithParents, UpdateRoleRequest,},- AuthorizationInfoResponse, DeleteUserRoleRequest, ListUsersInEntityRequest,- UpdateUserRoleRequest,+ AuthorizationInfoResponse, DeleteUserRoleRequest, DeleteUserRoleResponse,+ ListUsersInEntityRequest, UpdateUserRoleRequest,};common_utils::impl_api_event_type!(@@ -19,6 +19,7 @@ common_utils::impl_api_event_type!(AuthorizationInfoResponse,UpdateUserRoleRequest,DeleteUserRoleRequest,+ DeleteUserRoleResponse,CreateRoleRequest,CreateRoleV2Request,UpdateRoleRequest,diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rsindex 19027c3cbf..2c8df401e5 100644--- a/crates/api_models/src/user_role.rs+++ b/crates/api_models/src/user_role.rs@@ -45,6 +45,11 @@ pub struct DeleteUserRoleRequest {pub email: pii::Email,}+#[derive(Debug, serde::Serialize)]+pub struct DeleteUserRoleResponse {+ pub is_email_sent: bool,+}+#[derive(Debug, serde::Serialize)]pub struct ListUsersInEntityResponse {pub email: pii::Email,diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rsindex 023794950e..b456153845 100644--- a/crates/router/src/core/user_role.rs+++ b/crates/router/src/core/user_role.rs@@ -513,7 +513,7 @@ pub async fn delete_user_role(user_from_token: auth::UserFromToken,request: user_role_api::DeleteUserRoleRequest,_req_state: ReqState,-) -> UserResponse<()> {+) -> UserResponse<user_role_api::DeleteUserRoleResponse> {let user_from_db: domain::UserFromStorage = state.global_store.find_active_user_by_user_email(&domain::UserEmail::from_pii_email(request.email)?)@@ -545,7 +545,7 @@ pub async fn delete_user_role(.await.change_context(UserErrors::InternalServerError)?;- let mut user_role_deleted_flag = false;+ let mut deleted_user_role_info: Option<roles::RoleInfo> = None;// Find in V2let user_role_v2 = match state@@ -603,7 +603,7 @@ pub async fn delete_user_role());}- user_role_deleted_flag = true;+ deleted_user_role_info = Some(target_role_info.clone());state.global_store.delete_user_role_by_user_id_and_lineage(@@ -678,7 +678,9 @@ pub async fn delete_user_role());}- user_role_deleted_flag = true;+ if deleted_user_role_info.is_none() {+ deleted_user_role_info = Some(target_role_info.clone());+ }state.global_store.delete_user_role_by_user_id_and_lineage(@@ -697,10 +699,27 @@ pub async fn delete_user_role(.attach_printable("Error while deleting user role")?;}- if !user_role_deleted_flag {+ let Some(deleted_user_role_info) = deleted_user_role_info else {return Err(report!(UserErrors::InvalidDeleteOperation)).attach_printable("User is not associated with the merchant");- }+ };++ #[cfg(feature = "email")]+ let is_email_sent = utils::user_role::send_role_deletion_email_using_db(+ &state,+ &user_from_db,+ &deleted_user_role_info,+ &user_from_token,+ )+ .await+ .map_err(|err| {+ logger::error!("Failed to send role deletion email: {}", err);+ err+ })+ .is_ok();++ #[cfg(not(feature = "email"))]+ let is_email_sent = false;// Check if user has any more role associationslet remaining_roles = state@@ -742,7 +761,9 @@ pub async fn delete_user_role(}auth::blacklist::insert_user_in_blacklist(&state, user_from_db.get_user_id()).await?;- Ok(ApplicationResponse::StatusOk)+ Ok(ApplicationResponse::Json(+ user_role_api::DeleteUserRoleResponse { is_email_sent },+ ))}pub async fn list_users_in_lineage(diff --git a/crates/router/src/services/email/assets/role_deleted.html b/crates/router/src/services/email/assets/role_deleted.htmlnew file mode 100644index 0000000000..65c35c681d--- /dev/null+++ b/crates/router/src/services/email/assets/role_deleted.html@@ -0,0 +1,160 @@+<!DOCTYPE html>+<html lang="en">++<head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <meta http-equiv="X-UA-Compatible" content="ie=edge" />+ <title>Access Removed - {entity_name}</title>+</head>++<body style="+ background-color: #f8f9fb;+ height: 100%;+ font-family: Arial, Helvetica, sans-serif;+ ">+ <div style="+ width: 100%;+ margin: auto;+ text-align: center;+ background-color: #f8f9fb;+ ">+ <table style="text-align: center; width: 100%">+ <tr>+ <td style="height: 6px"></td>+ </tr>+ <tr>+ <td style="text-align: center">+ <table style="+ background-color: {background_color};+ text-align: center;+ max-width: 55%;+ margin: auto;+ ">+ <tr>+ <td style="height: 20px"></td>+ </tr>+ <tr>+ <td>+ <table style="width: 100%">+ <tr>+ <td style="text-align: center">+ <img src={entity_logo_url} alt={entity_name} style="+ text-align: center;+ height: auto;+ width: 4rem;+ " />+ </td>+ </tr>+ </table>+ </td>+ </tr>+ <tr>+ <td style="height: 40px"></td>+ </tr>+ <tr>+ <td style="+ font-size: 2.02rem;+ font-weight: 600;+ line-height: 2.5rem;+ color: {foreground_color};+ min-width: 550px;+ ">+ Access Removed+ </td>+ </tr>+ <tr>+ <td style="height: 20px"></td>+ </tr>+ <tr>+ <td style="+ color: {foreground_color};+ opacity: 0.8;+ width: 50%;+ font-size: 1.02rem;+ font-weight: 400;+ line-height: 1.4rem;+ min-width: 300px;+ ">+ <table style="+ width: 70%;+ min-width: 400px;+ text-align: start;+ margin: auto;+ ">+ <tr>+ <td style="padding: 0 15px text-align: center">+ <p>Dear {username},</p>+ <p>+ This is to inform you that your access has been revoked for the following role:+ </p>+ <table style="+ width: 100%;+ margin: 15px 0;+ border: 1px solid {foreground_color};+ border-opacity: 0.2;+ border-radius: 8px;+ padding: 15px;+ ">+ <tr>+ <td style="padding: 8px 15px">+ <strong>Role:</strong> {role_name}+ </td>+ </tr>+ <tr>+ <td style="padding: 8px 15px">+ <strong>Entity Type:</strong> {entity_type}+ </td>+ </tr>+ <tr>+ <td style="padding: 8px 15px">+ <strong>Access Level:</strong>+ <ul+ style="+ list-style-type: none;+ padding-left: 0;+ margin: 8px 0 0 0;+ text-align: left;+ gap: 8px;+ "+ >+ {lineage_info}+ </ul>+ </td>+ </tr>+ </table>+ <p>+ You no longer have access to the resources and permissions associated with this role.+ If you believe this is an error or have any questions, please contact your administrator.+ </p>+ <p>+ If you need assistance, please reach out to the support team.+ </p>+ </td>+ </tr>+ <tr>+ <td style="height: 15px"></td>+ </tr>+ <tr>+ <td>+ Best regards,<br />+ {entity_name} Team+ </td>+ </tr>+ </table>+ </td>+ </tr>+ <tr>+ <td style="height: 50px"></td>+ </tr>+ </table>+ </td>+ </tr>+ <tr>+ <td style="height: 6px"></td>+ </tr>+ </table>+ </div>+</body>++</html>diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rsindex 99a28305f2..eb73347911 100644--- a/crates/router/src/services/email/types.rs+++ b/crates/router/src/services/email/types.rs@@ -1,6 +1,7 @@use api_models::user::dashboard_metadata::ProdIntent;use common_enums::{EntityType, MerchantProductType};use common_utils::{errors::CustomResult, pii, types::user::EmailThemeConfig};+use diesel_models::organization::OrganizationBridge;use error_stack::ResultExt;use external_services::email::{EmailContents, EmailData, EmailError};use masking::{ExposeInterface, PeekInterface, Secret};@@ -81,6 +82,16 @@ pub enum EmailBody {prefix: String,},WelcomeToCommunity,+ RoleDeleted {+ user_name: String,+ role_name: String,+ entity_type: String,+ lineage_info: String,+ entity_name: String,+ entity_logo_url: String,+ background_color: String,+ foreground_color: String,+ },}pub mod html {@@ -242,6 +253,28 @@ Email : {user_email}EmailBody::WelcomeToCommunity => {include_str!("assets/welcome_to_community.html").to_string()}+ EmailBody::RoleDeleted {+ user_name,+ role_name,+ entity_type,+ lineage_info,+ entity_name,+ entity_logo_url,+ background_color,+ foreground_color,+ } => {+ format!(+ include_str!("assets/role_deleted.html"),+ username = user_name,+ role_name = role_name,+ entity_type = entity_type,+ lineage_info = lineage_info,+ entity_name = entity_name,+ entity_logo_url = entity_logo_url,+ background_color = background_color,+ foreground_color = foreground_color+ )+ }}}}@@ -690,3 +723,61 @@ impl EmailData for WelcomeToCommunity {})}}++pub struct RoleDeleted {+ pub recipient_email: domain::UserEmail,+ pub user_name: domain::UserName,+ pub role_name: String,+ pub entity_type: EntityType,+ pub org: diesel_models::organization::Organization,+ pub merchant: domain::MerchantAccount,+ pub profile: domain::Profile,+ pub theme_config: EmailThemeConfig,+}++#[async_trait::async_trait]+impl EmailData for RoleDeleted {+ async fn get_email_data(&self, _base_url: &str) -> CustomResult<EmailContents, EmailError> {+ let org_info = match self.org.get_organization_name() {+ Some(name) => format!("Organization: {}", name),+ None => format!(+ "Organization Id: {}",+ self.org.get_organization_id().get_string_repr()+ ),+ };++ let merchant_info = match &self.merchant.merchant_name {+ Some(name) => format!("Merchant: {}", name.get_inner().peek().clone()),+ None => format!("Merchant Id: {}", self.merchant.get_id().get_string_repr()),+ };++ let profile_info = format!("Profile: {}", self.profile.profile_name);++ let lineage_info = match self.entity_type {+ EntityType::Tenant => vec!["Tenant Level".to_string()],+ EntityType::Organization => vec![org_info],+ EntityType::Merchant => vec![org_info, merchant_info],+ EntityType::Profile => vec![org_info, merchant_info, profile_info],+ }+ .into_iter()+ .map(|item| format!("<li>{}</li>", item))+ .collect::<String>();++ let body = html::get_html_body(EmailBody::RoleDeleted {+ user_name: self.user_name.clone().get_secret().expose(),+ role_name: self.role_name.clone(),+ entity_type: format!("{:?}", self.entity_type),+ lineage_info,+ entity_name: self.theme_config.entity_name.clone(),+ entity_logo_url: self.theme_config.entity_logo_url.clone(),+ background_color: self.theme_config.background_color.clone(),+ foreground_color: self.theme_config.foreground_color.clone(),+ });++ Ok(EmailContents {+ subject: format!("Access Removed - {} Role Revoked", self.role_name),+ body: external_services::email::IntermediateString::new(body),+ recipient: self.recipient_email.clone().into_inner(),+ })+ }+}diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rsindex 2033611aa0..996ee2b71e 100644--- a/crates/router/src/utils/user_role.rs+++ b/crates/router/src/utils/user_role.rs@@ -31,6 +31,11 @@ use crate::{},types::domain,};+#[cfg(feature = "email")]+use crate::{+ services::{authentication as auth, email::types as email_types},+ utils::user::{self as user_utils, theme as theme_utils},+};pub fn validate_role_groups(groups: &[PermissionGroup]) -> UserResult<()> {if groups.is_empty() {@@ -597,3 +602,73 @@ pub fn resources_to_description(Some(description)}++#[cfg(feature = "email")]+pub async fn send_role_deletion_email_using_db(+ state: &SessionState,+ user_from_db: &domain::UserFromStorage,+ role_info: &roles::RoleInfo,+ user_from_token: &auth::UserFromToken,+) -> UserResult<()> {+ let theme = theme_utils::get_most_specific_theme_using_token_and_min_entity(+ state,+ user_from_token,+ role_info.get_entity_type(),+ )+ .await?;++ let theme_config = theme+ .as_ref()+ .map(|theme| theme.email_config())+ .unwrap_or(state.conf.theme.email_config.clone());++ let org = state+ .accounts_store+ .find_organization_by_org_id(&user_from_token.org_id)+ .await+ .change_context(UserErrors::InternalServerError)?;++ let merchant_key_store = state+ .store+ .get_merchant_key_store_by_merchant_id(+ &user_from_token.merchant_id,+ &state.store.get_master_key().to_vec().into(),+ )+ .await+ .change_context(UserErrors::InternalServerError)?;++ let merchant = state+ .store+ .find_merchant_account_by_merchant_id(&user_from_token.merchant_id, &merchant_key_store)+ .await+ .change_context(UserErrors::InternalServerError)?;++ let profile = state+ .store+ .find_business_profile_by_profile_id(&merchant_key_store, &user_from_token.profile_id)+ .await+ .change_context(UserErrors::InternalServerError)?;++ let email_contents = email_types::RoleDeleted {+ recipient_email: domain::UserEmail::from_pii_email(user_from_db.get_email())?,+ user_name: domain::UserName::new(user_from_db.get_name())?,+ role_name: role_info.get_role_name().to_string(),+ entity_type: role_info.get_entity_type(),+ org,+ merchant,+ profile,+ theme_config,+ };++ state+ .email_client+ .compose_and_send_email(+ user_utils::get_base_url(state),+ Box::new(email_contents),+ state.conf.proxy.https_url.as_ref(),+ )+ .await+ .change_context(UserErrors::InternalServerError)?;++ Ok(())+}