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): Add resend verification email API (#3093)
Mani Chandra6d5c25e33691
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rsindex 92b6757239..1f4cb7359c 100644--- a/crates/api_models/src/events/user.rs+++ b/crates/api_models/src/events/user.rs@@ -8,8 +8,8 @@ use crate::user::{},AuthorizeResponse, ChangePasswordRequest, ConnectAccountRequest, CreateInternalUserRequest,DashboardEntryResponse, ForgotPasswordRequest, GetUsersResponse, InviteUserRequest,- InviteUserResponse, ResetPasswordRequest, SignUpRequest, SignUpWithMerchantIdRequest,- SwitchMerchantIdRequest, UserMerchantCreate, VerifyEmailRequest,+ InviteUserResponse, ResetPasswordRequest, SendVerifyEmailRequest, SignUpRequest,+ SignUpWithMerchantIdRequest, SwitchMerchantIdRequest, UserMerchantCreate, VerifyEmailRequest,};impl ApiEventMetric for DashboardEntryResponse {@@ -39,7 +39,8 @@ common_utils::impl_misc_api_event_type!(ResetPasswordRequest,InviteUserRequest,InviteUserResponse,- VerifyEmailRequest+ VerifyEmailRequest,+ SendVerifyEmailRequest);#[cfg(feature = "dummy_connector")]diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rsindex 10d8411f8e..d666dfc3bf 100644--- a/crates/api_models/src/user.rs+++ b/crates/api_models/src/user.rs@@ -128,3 +128,8 @@ pub struct VerifyEmailRequest {}pub type VerifyEmailResponse = DashboardEntryResponse;++#[derive(serde::Deserialize, Debug, serde::Serialize)]+pub struct SendVerifyEmailRequest {+ pub email: pii::Email,+}diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rsindex 03ca880561..330e02cd54 100644--- a/crates/router/src/core/errors/user.rs+++ b/crates/router/src/core/errors/user.rs@@ -28,6 +28,8 @@ pub enum UserErrors {NameParsingError,#[error("PasswordParsingError")]PasswordParsingError,+ #[error("UserAlreadyVerified")]+ UserAlreadyVerified,#[error("CompanyNameParsingError")]CompanyNameParsingError,#[error("MerchantAccountCreationError: {0}")]@@ -104,6 +106,9 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponSelf::PasswordParsingError => {AER::BadRequest(ApiError::new(sub_code, 9, "Invalid Password", None))}+ Self::UserAlreadyVerified => {+ AER::Unauthorized(ApiError::new(sub_code, 11, "User already verified", None))+ }Self::CompanyNameParsingError => {AER::BadRequest(ApiError::new(sub_code, 14, "Invalid Company Name", None))}diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rsindex e2c538ca80..a9f46a3885 100644--- a/crates/router/src/core/user.rs+++ b/crates/router/src/core/user.rs@@ -14,7 +14,6 @@ use super::errors::{UserErrors, UserResponse};use crate::services::email::types as email_types;use crate::{consts,- db::user::UserInterface,routes::AppState,services::{authentication as auth, ApplicationResponse},types::domain,@@ -228,11 +227,12 @@ pub async fn change_password(request: user_api::ChangePasswordRequest,user_from_token: auth::UserFromToken,) -> UserResponse<()> {- let user: domain::UserFromStorage =- UserInterface::find_user_by_id(&*state.store, &user_from_token.user_id)- .await- .change_context(UserErrors::InternalServerError)?- .into();+ let user: domain::UserFromStorage = state+ .store+ .find_user_by_id(&user_from_token.user_id)+ .await+ .change_context(UserErrors::InternalServerError)?+ .into();user.compare_password(request.old_password.to_owned()).change_context(UserErrors::InvalidOldPassword)?;@@ -245,17 +245,18 @@ pub async fn change_password(let new_password_hash =utils::user::password::generate_password_hash(new_password.get_secret())?;- let _ = UserInterface::update_user_by_user_id(- &*state.store,- user.get_user_id(),- diesel_models::user::UserUpdate::AccountUpdate {- name: None,- password: Some(new_password_hash),- is_verified: None,- },- )- .await- .change_context(UserErrors::InternalServerError)?;+ let _ = state+ .store+ .update_user_by_user_id(+ user.get_user_id(),+ diesel_models::user::UserUpdate::AccountUpdate {+ name: None,+ password: Some(new_password_hash),+ is_verified: None,+ },+ )+ .await+ .change_context(UserErrors::InternalServerError)?;Ok(ApplicationResponse::StatusOk)}@@ -670,3 +671,43 @@ pub async fn verify_email(utils::user::get_dashboard_entry_response(state, user_from_db, user_role, token)?,))}++#[cfg(feature = "email")]+pub async fn send_verification_mail(+ state: AppState,+ req: user_api::SendVerifyEmailRequest,+) -> UserResponse<()> {+ let user_email = domain::UserEmail::try_from(req.email)?;+ let user = state+ .store+ .find_user_by_email(user_email.clone().get_secret().expose().as_str())+ .await+ .map_err(|e| {+ if e.current_context().is_db_not_found() {+ e.change_context(UserErrors::UserNotFound)+ } else {+ e.change_context(UserErrors::InternalServerError)+ }+ })?;++ if user.is_verified {+ return Err(UserErrors::UserAlreadyVerified.into());+ }++ let email_contents = email_types::VerifyEmail {+ recipient_email: domain::UserEmail::from_pii_email(user.email)?,+ settings: state.conf.clone(),+ subject: "Welcome to the Hyperswitch community!",+ };++ state+ .email_client+ .compose_and_send_email(+ Box::new(email_contents),+ state.conf.proxy.https_url.as_ref(),+ )+ .await+ .change_context(UserErrors::InternalServerError)?;++ Ok(ApplicationResponse::StatusOk)+}diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex 34ae6fa3ec..eec8a36ce9 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -903,6 +903,10 @@ impl User {.route(web::post().to(user_signup_with_merchant_id)),).service(web::resource("/verify_email").route(web::post().to(verify_email)))+ .service(+ web::resource("/verify_email_request")+ .route(web::post().to(verify_email_request)),+ );}#[cfg(not(feature = "email"))]{diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rsindex f5519b9603..10f408f3d4 100644--- a/crates/router/src/routes/lock_utils.rs+++ b/crates/router/src/routes/lock_utils.rs@@ -171,7 +171,8 @@ impl From<Flow> for ApiIdentifier {| Flow::ResetPassword| Flow::InviteUser| Flow::UserSignUpWithMerchantId- | Flow::VerifyEmail => Self::User,+ | Flow::VerifyEmail+ | Flow::VerifyEmailRequest => Self::User,Flow::ListRoles | Flow::GetRole | Flow::UpdateUserRole | Flow::GetAuthorizationInfo => {Self::UserRolediff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rsindex 594da67aa0..7f0f0db3b6 100644--- a/crates/router/src/routes/user.rs+++ b/crates/router/src/routes/user.rs@@ -33,7 +33,7 @@ pub async fn user_signup_with_merchant_id(&http_req,req_payload.clone(),|state, _, req_body| user_core::signup_with_merchant_id(state, req_body),- &auth::NoAuth,+ &auth::AdminApiAuth,api_locking::LockAction::NotApplicable,)).await@@ -370,3 +370,22 @@ pub async fn verify_email()).await}++#[cfg(feature = "email")]+pub async fn verify_email_request(+ state: web::Data<AppState>,+ http_req: HttpRequest,+ json_payload: web::Json<user_api::SendVerifyEmailRequest>,+) -> HttpResponse {+ let flow = Flow::VerifyEmailRequest;+ Box::pin(api::server_wrap(+ flow,+ state.clone(),+ &http_req,+ json_payload.into_inner(),+ |state, _, req_body| user_core::send_verification_mail(state, req_body),+ &auth::NoAuth,+ api_locking::LockAction::NotApplicable,+ ))+ .await+}diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rsindex 6344c21f5f..e37e15443b 100644--- a/crates/router_env/src/logger/types.rs+++ b/crates/router_env/src/logger/types.rs@@ -313,6 +313,8 @@ pub enum Flow {SyncOnboardingStatus,/// Verify email TokenVerifyEmail,+ /// Send verify email+ VerifyEmailRequest,}///