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(user): add internal apis to get user details and list users (#11433)
Grovy-3170d1997225804d
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rsindex d8aba26e8b..3948365911 100644--- a/crates/api_models/src/events/user.rs+++ b/crates/api_models/src/events/user.rs@@ -16,8 +16,9 @@ use crate::user::{CreateInternalUserRequest, CreateTenantUserRequest, CreateUserAuthenticationMethodRequest,CreateUserAuthenticationMethodResponse, EmbeddedTokenInfoResponse, ForgotPasswordRequest,GetSsoAuthUrlRequest, GetUserAuthenticationMethodsRequest, GetUserDetailsResponse,- GetUserRoleDetailsRequest, GetUserRoleDetailsResponseV2, InviteUserRequest,- IssueEmbeddedTokenResponse, PlatformAccountCreateRequest, PlatformAccountCreateResponse,+ GetUserInternalDetailsResponse, GetUserRoleDetailsRequest, GetUserRoleDetailsResponseV2,+ InviteUserRequest, IssueEmbeddedTokenResponse, ListUsersInternalRequest,+ ListUsersInternalResponse, PlatformAccountCreateRequest, PlatformAccountCreateResponse,ReInviteUserRequest, RecoveryCodes, ResetPasswordRequest, RotatePasswordRequest,SendVerifyEmailRequest, SignUpRequest, SignUpWithMerchantIdRequest, SsoSignInRequest,SwitchMerchantRequest, SwitchOrganizationRequest, SwitchProfileRequest, TokenResponse,@@ -79,7 +80,10 @@ common_utils::impl_api_event_type!(AuthSelectRequest,CloneConnectorRequest,IssueEmbeddedTokenResponse,- EmbeddedTokenInfoResponse+ EmbeddedTokenInfoResponse,+ GetUserInternalDetailsResponse,+ ListUsersInternalRequest,+ ListUsersInternalResponse));diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rsindex 0aa40fa16a..41d51362b1 100644--- a/crates/api_models/src/user.rs+++ b/crates/api_models/src/user.rs@@ -445,6 +445,11 @@ pub struct UserKeyTransferRequest {pub limit: u32,}+#[derive(Debug, serde::Deserialize, serde::Serialize)]+pub struct ListUsersInternalRequest {+ pub user_ids: Vec<String>,+}+#[derive(Debug, serde::Deserialize, serde::Serialize)]pub struct UserTransferKeyResponse {pub total_transferred: usize,@@ -484,3 +489,16 @@ pub struct EmbeddedTokenInfoResponse {pub merchant_account_version: common_enums::ApiVersion,pub profile_id: id_type::ProfileId,}++#[derive(Debug, serde::Serialize)]+pub struct GetUserInternalDetailsResponse {+ pub user_id: String,+ pub name: Secret<String>,+ pub email: pii::Email,+ pub is_active: bool,+}++#[derive(Debug, serde::Serialize)]+pub struct ListUsersInternalResponse {+ pub users: Vec<GetUserInternalDetailsResponse>,+}diff --git a/crates/diesel_models/src/query/user.rs b/crates/diesel_models/src/query/user.rsindex 0d96f02420..5d35a02f15 100644--- a/crates/diesel_models/src/query/user.rs+++ b/crates/diesel_models/src/query/user.rs@@ -53,6 +53,14 @@ impl User {.await}+ pub async fn find_by_user_id(conn: &PgPooledConn, user_id: &str) -> StorageResult<Self> {+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(+ conn,+ users_dsl::user_id.eq(user_id.to_owned()),+ )+ .await+ }+pub async fn update_active_by_user_id(conn: &PgPooledConn,user_id: &str,@@ -120,6 +128,19 @@ impl User {.await}+ pub async fn list_users_by_user_ids(+ conn: &PgPooledConn,+ user_ids: Vec<String>,+ ) -> StorageResult<Vec<Self>> {+ generics::generic_filter::<+ <Self as HasTable>::Table,+ _,+ <<Self as HasTable>::Table as diesel::Table>::PrimaryKey,+ _,+ >(conn, users_dsl::user_id.eq_any(user_ids), None, None, None)+ .await+ }+pub async fn reactivate_by_user_id(conn: &PgPooledConn,user_id: &str,diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rsindex a36fdc5120..40ddfa4e81 100644--- a/crates/router/src/core/user.rs+++ b/crates/router/src/core/user.rs@@ -3986,3 +3986,54 @@ pub async fn embedded_token_info(},))}++pub async fn get_user_details_internal(+ state: SessionState,+ user_id: String,+) -> UserResponse<user_api::GetUserInternalDetailsResponse> {+ let user: domain::UserFromStorage = state+ .global_store+ .find_user_by_user_id(&user_id)+ .await+ .change_context(UserErrors::InternalServerError)+ .attach_printable("Failed to fetch user from database")?+ .into();++ Ok(ApplicationResponse::Json(+ user_api::GetUserInternalDetailsResponse {+ user_id: user.get_user_id().to_string(),+ name: user.get_name(),+ email: user.get_email(),+ is_active: user.is_active(),+ },+ ))+}++pub async fn list_users_internal(+ state: SessionState,+ req: user_api::ListUsersInternalRequest,+) -> UserResponse<user_api::ListUsersInternalResponse> {+ let users = state+ .global_store+ .list_users_by_user_ids(req.user_ids)+ .await+ .change_context(UserErrors::InternalServerError)+ .attach_printable("Failed to fetch users from database")?;++ let users_minimal_details = users+ .into_iter()+ .map(domain::UserFromStorage::from)+ .map(|user| user_api::GetUserInternalDetailsResponse {+ user_id: user.get_user_id().to_string(),+ name: user.get_name(),+ email: user.get_email(),+ is_active: user.is_active(),+ })+ .collect();++ Ok(ApplicationResponse::Json(+ user_api::ListUsersInternalResponse {+ users: users_minimal_details,+ },+ ))+}diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rsindex c378eecd37..0047bac81f 100644--- a/crates/router/src/db/kafka_store.rs+++ b/crates/router/src/db/kafka_store.rs@@ -3379,6 +3379,13 @@ impl UserInterface for KafkaStore {self.diesel_store.find_active_user_by_user_id(user_id).await}+ async fn find_user_by_user_id(+ &self,+ user_id: &str,+ ) -> CustomResult<storage::User, errors::StorageError> {+ self.diesel_store.find_user_by_user_id(user_id).await+ }+async fn update_active_user_by_user_id(&self,user_id: &str,@@ -3408,6 +3415,13 @@ impl UserInterface for KafkaStore {.await}+ async fn list_users_by_user_ids(+ &self,+ user_ids: Vec<String>,+ ) -> CustomResult<Vec<storage::User>, errors::StorageError> {+ self.diesel_store.list_users_by_user_ids(user_ids).await+ }+async fn reactivate_user_by_user_id(&self,user_id: &str,diff --git a/crates/router/src/db/user.rs b/crates/router/src/db/user.rsindex c2b1cb40be..032c389b51 100644--- a/crates/router/src/db/user.rs+++ b/crates/router/src/db/user.rs@@ -34,6 +34,11 @@ pub trait UserInterface {user_id: &str,) -> CustomResult<storage::User, errors::StorageError>;+ async fn find_user_by_user_id(+ &self,+ user_id: &str,+ ) -> CustomResult<storage::User, errors::StorageError>;+async fn update_active_user_by_user_id(&self,user_id: &str,@@ -51,6 +56,11 @@ pub trait UserInterface {user_ids: Vec<String>,) -> CustomResult<Vec<storage::User>, errors::StorageError>;+ async fn list_users_by_user_ids(+ &self,+ user_ids: Vec<String>,+ ) -> CustomResult<Vec<storage::User>, errors::StorageError>;+async fn reactivate_user_by_user_id(&self,user_id: &str,@@ -105,6 +115,17 @@ impl UserInterface for Store {.map_err(|error| report!(errors::StorageError::from(error)))}+ #[instrument(skip_all)]+ async fn find_user_by_user_id(+ &self,+ user_id: &str,+ ) -> CustomResult<storage::User, errors::StorageError> {+ let conn = connection::pg_connection_read(self).await?;+ storage::User::find_by_user_id(&conn, user_id)+ .await+ .map_err(|error| report!(errors::StorageError::from(error)))+ }+#[instrument(skip_all)]async fn update_active_user_by_user_id(&self,@@ -141,6 +162,16 @@ impl UserInterface for Store {.map_err(|error| report!(errors::StorageError::from(error)))}+ async fn list_users_by_user_ids(+ &self,+ user_ids: Vec<String>,+ ) -> CustomResult<Vec<storage::User>, errors::StorageError> {+ let conn = connection::pg_connection_read(self).await?;+ storage::User::list_users_by_user_ids(&conn, user_ids)+ .await+ .map_err(|error| report!(errors::StorageError::from(error)))+ }+#[instrument(skip_all)]async fn reactivate_user_by_user_id(&self,@@ -242,6 +273,23 @@ impl UserInterface for MockDb {)}+ async fn find_user_by_user_id(+ &self,+ user_id: &str,+ ) -> CustomResult<storage::User, errors::StorageError> {+ let users = self.users.lock().await;+ users+ .iter()+ .find(|user| user.user_id == user_id)+ .cloned()+ .ok_or(+ errors::StorageError::ValueNotFound(format!(+ "No user available for user_id = {user_id}"+ ))+ .into(),+ )+ }+async fn update_active_user_by_user_id(&self,user_id: &str,@@ -396,6 +444,13 @@ impl UserInterface for MockDb {Err(errors::StorageError::MockDbError)?}+ async fn list_users_by_user_ids(+ &self,+ _user_ids: Vec<String>,+ ) -> CustomResult<Vec<storage::User>, errors::StorageError> {+ Err(errors::StorageError::MockDbError)?+ }+async fn reactivate_user_by_user_id(&self,user_id: &str,diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex 5b89e4f7db..f501c4258c 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -3113,6 +3113,19 @@ impl User {),),);++ // Internal API endpoints (authenticated via X-Internal-API-Key header)+ route = route.service(+ web::scope("/internal")+ .service(+ web::resource("/user/list").route(web::post().to(user::list_users_internal)),+ )+ .service(+ web::resource("/user/{user_id}")+ .route(web::get().to(user::get_user_details_internal)),+ ),+ );+route}}diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rsindex a0816feb07..be16f29b77 100644--- a/crates/router/src/routes/lock_utils.rs+++ b/crates/router/src/routes/lock_utils.rs@@ -318,7 +318,9 @@ impl From<Flow> for ApiIdentifier {| Flow::ListAllThemesInLineage| Flow::CloneConnector| Flow::EmbeddedTokenInfo- | Flow::GetEmbeddedToken => Self::User,+ | Flow::GetEmbeddedToken+ | Flow::GetUserDetailsInternal+ | Flow::ListUsersInternal => Self::User,Flow::GetDataFromHyperswitchAiFlow | Flow::ListAllChatInteractions => Self::AiWorkflow,diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rsindex 7c85cdf692..13c4e1f121 100644--- a/crates/router/src/routes/user.rs+++ b/crates/router/src/routes/user.rs@@ -1175,3 +1175,42 @@ pub async fn embedded_token_info()).await}++pub async fn get_user_details_internal(+ state: web::Data<AppState>,+ req: HttpRequest,+ path: web::Path<String>,+) -> HttpResponse {+ let flow = Flow::GetUserDetailsInternal;+ let user_id = path.into_inner();++ Box::pin(api::server_wrap(+ flow,+ state,+ &req,+ user_id.clone(),+ |state, _auth: (), user_id, _| user_core::get_user_details_internal(state, user_id),+ &auth::InternalMerchantIdProfileIdAuth(auth::AdminApiAuth),+ api_locking::LockAction::NotApplicable,+ ))+ .await+}++pub async fn list_users_internal(+ state: web::Data<AppState>,+ req: HttpRequest,+ json_payload: web::Json<user_api::ListUsersInternalRequest>,+) -> HttpResponse {+ let flow = Flow::ListUsersInternal;++ Box::pin(api::server_wrap(+ flow,+ state,+ &req,+ json_payload.into_inner(),+ |state, _auth: (), req, _| user_core::list_users_internal(state, req),+ &auth::InternalMerchantIdProfileIdAuth(auth::AdminApiAuth),+ api_locking::LockAction::NotApplicable,+ ))+ .await+}diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rsindex da82e91eaa..bc7bbd17cf 100644--- a/crates/router/src/services/authentication.rs+++ b/crates/router/src/services/authentication.rs@@ -2572,40 +2572,25 @@ where/// it falls back to the provided authentication mechanism.pub struct InternalMerchantIdProfileIdAuth<F>(pub F);-pub fn is_internal_merchant_id_profile_id_auth(- request_headers: &HeaderMap,-) -> common_enums::ApiKeyType {- let merchant_id = HeaderMapStruct::new(request_headers)- .get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)- .ok();- let internal_api_key = HeaderMapStruct::new(request_headers)- .get_header_value_by_key(headers::X_INTERNAL_API_KEY)- .map(|internal_api_key| internal_api_key.to_string());- let profile_id = HeaderMapStruct::new(request_headers)- .get_id_type_from_header::<id_type::ProfileId>(headers::X_PROFILE_ID)- .ok();-- if merchant_id.is_some() && profile_id.is_some() && internal_api_key.is_some() {- common_enums::ApiKeyType::Internal- } else {- common_enums::ApiKeyType::External- }+/// Validated data returned from successful internal merchant/profile authentication+struct InternalAuthValidatedData {+ key_store: domain::MerchantKeyStore,+ profile: domain::Profile,+ initiator_merchant: domain::MerchantAccount,}-#[async_trait]-impl<A, F> AuthenticateAndFetch<AuthenticationData, A> for InternalMerchantIdProfileIdAuth<F>-where- A: SessionStateInfo + Sync + Send,- F: AuthenticateAndFetch<AuthenticationData, A> + Sync + Send,-{- async fn authenticate_and_fetch(- &self,+impl<F> InternalMerchantIdProfileIdAuth<F> {+ /// Common authentication logic for internal merchant/profile ID auth.+ /// Returns Ok(Some(data)) if authentication succeeds via internal API key,+ /// Ok(None) if headers are missing (should fallback to wrapped auth),+ /// Err if authentication fails.+ async fn validate_internal_auth<A>(request_headers: &HeaderMap,state: &A,- ) -> RouterResult<(AuthenticationData, AuthenticationType)> {- if !state.conf().internal_merchant_id_profile_id_auth.enabled {- return self.0.authenticate_and_fetch(request_headers, state).await;- }+ ) -> RouterResult<Option<InternalAuthValidatedData>>+ where+ A: SessionStateInfo + Sync + Send,+ {let merchant_id = HeaderMapStruct::new(request_headers).get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID).ok();@@ -2615,6 +2600,7 @@ wherelet profile_id = HeaderMapStruct::new(request_headers).get_id_type_from_header::<id_type::ProfileId>(headers::X_PROFILE_ID).ok();+if let (Some(internal_api_key), Some(merchant_id), Some(profile_id)) =(internal_api_key, merchant_id, profile_id){@@ -2628,6 +2614,7 @@ wherereturn Err(errors::ApiErrorResponse::Unauthorized).attach_printable("Internal API key authentication failed");}+let key_store = state.store().get_merchant_key_store_by_merchant_id(@@ -2653,35 +2640,91 @@ where.await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;- let initiator = Some(domain::Initiator::Api {- merchant_id: initiator_merchant.get_id().clone(),- merchant_account_type: initiator_merchant.merchant_account_type,- publishable_key: initiator_merchant.publishable_key.clone(),- });-- let platform = resolve_platform(- state,- request_headers,- initiator_merchant.clone(),+ Ok(Some(InternalAuthValidatedData {key_store,- initiator,- )- .await?;+ profile,+ initiator_merchant,+ }))+ } else {+ Ok(None)+ }+ }+}++#[async_trait]+impl<A, F> AuthenticateAndFetch<AuthenticationData, A> for InternalMerchantIdProfileIdAuth<F>+where+ A: SessionStateInfo + Sync + Send,+ F: AuthenticateAndFetch<AuthenticationData, A> + Sync + Send,+{+ async fn authenticate_and_fetch(+ &self,+ request_headers: &HeaderMap,+ state: &A,+ ) -> RouterResult<(AuthenticationData, AuthenticationType)> {+ if !state.conf().internal_merchant_id_profile_id_auth.enabled {+ return self.0.authenticate_and_fetch(request_headers, state).await;+ }- let auth = AuthenticationData::construct_authentication_data_for_internal_merchant_id_profile_id_auth(platform, profile);+ match Box::pin(Self::validate_internal_auth(request_headers, state)).await? {+ Some(validated_data) => {+ let initiator = Some(domain::Initiator::Api {+ merchant_id: validated_data.initiator_merchant.get_id().clone(),+ merchant_account_type: validated_data.initiator_merchant.merchant_account_type,+ publishable_key: validated_data.initiator_merchant.publishable_key.clone(),+ });- Ok((- auth.clone(),+ let platform = resolve_platform(+ state,+ request_headers,+ validated_data.initiator_merchant.clone(),+ validated_data.key_store,+ initiator,+ )+ .await?;++ let auth = AuthenticationData::construct_authentication_data_for_internal_merchant_id_profile_id_auth(+ platform,+ validated_data.profile.clone(),+ );++ Ok((+ auth,+ AuthenticationType::InternalMerchantIdProfileId {+ merchant_id: validated_data.initiator_merchant.get_id().clone(),+ profile_id: Some(validated_data.profile.get_id().clone()),+ },+ ))+ }+ None => self.0.authenticate_and_fetch(request_headers, state).await,+ }+ }+}++#[async_trait]+impl<A, F> AuthenticateAndFetch<(), A> for InternalMerchantIdProfileIdAuth<F>+where+ A: SessionStateInfo + Sync + Send,+ F: AuthenticateAndFetch<(), A> + Sync + Send,+{+ async fn authenticate_and_fetch(+ &self,+ request_headers: &HeaderMap,+ state: &A,+ ) -> RouterResult<((), AuthenticationType)> {+ if !state.conf().internal_merchant_id_profile_id_auth.enabled {+ return self.0.authenticate_and_fetch(request_headers, state).await;+ }++ match Box::pin(Self::validate_internal_auth(request_headers, state)).await? {+ Some(validated_data) => Ok((+ (),AuthenticationType::InternalMerchantIdProfileId {- merchant_id: merchant_id.clone(),- profile_id: Some(profile_id),+ merchant_id: validated_data.initiator_merchant.get_id().clone(),+ profile_id: Some(validated_data.profile.get_id().clone()),},- ))- } else {- Ok(self- .0- .authenticate_and_fetch(request_headers, state)- .await?)+ )),+ None => self.0.authenticate_and_fetch(request_headers, state).await,}}}diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rsindex b4cf6d3b55..8492e98ad8 100644--- a/crates/router_env/src/logger/types.rs+++ b/crates/router_env/src/logger/types.rs@@ -727,6 +727,10 @@ pub enum Flow {GetEmbeddedToken,// Get embedded token info flowEmbeddedTokenInfo,+ // Get user details internal+ GetUserDetailsInternal,+ // List users internal+ ListUsersInternal,}/// Trait for providing generic behaviour to flow metric