text
stringlengths
81
477k
file_path
stringlengths
22
92
module
stringlengths
13
87
token_count
int64
24
94.8k
has_source_code
bool
1 class
// File: crates/router/src/routes/user.rs // Module: router::src::routes::user pub mod theme; use actix_web::{web, HttpRequest, HttpResponse}; #[cfg(feature = "dummy_connector")] use api_models::user::sample_data::SampleDataRequest; use api_models::{ errors::types::ApiErrorResponse, user::{self as user_api}, }; use common_enums::TokenPurpose; use common_utils::errors::ReportSwitchExt; use router_env::Flow; use super::AppState; use crate::{ core::{api_locking, user as user_core}, services::{ api, authentication::{self as auth}, authorization::permissions::Permission, }, utils::user::dashboard_metadata::{parse_string_to_enums, set_ip_address_if_required}, }; pub async fn get_user_details(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { let flow = Flow::GetUserDetails; Box::pin(api::server_wrap( flow, state, &req, (), |state, user, _, _| user_core::get_user_details(state, user), &auth::DashboardNoPermissionAuth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "email")] pub async fn user_signup_with_merchant_id( state: web::Data<AppState>, http_req: HttpRequest, json_payload: web::Json<user_api::SignUpWithMerchantIdRequest>, query: web::Query<user_api::AuthIdAndThemeIdQueryParam>, ) -> HttpResponse { let flow = Flow::UserSignUpWithMerchantId; let req_payload = json_payload.into_inner(); let query_params = query.into_inner(); Box::pin(api::server_wrap( flow.clone(), state, &http_req, req_payload.clone(), |state, _, req_body, _| { user_core::signup_with_merchant_id( state, req_body, query_params.auth_id.clone(), query_params.theme_id.clone(), ) }, &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } pub async fn user_signup( state: web::Data<AppState>, http_req: HttpRequest, json_payload: web::Json<user_api::SignUpRequest>, ) -> HttpResponse { let flow = Flow::UserSignUp; let req_payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow.clone(), state, &http_req, req_payload.clone(), |state, _: (), req_body, _| async move { user_core::signup_token_only_flow(state, req_body).await }, &auth::NoAuth, api_locking::LockAction::NotApplicable, )) .await } pub async fn user_signin( state: web::Data<AppState>, http_req: HttpRequest, json_payload: web::Json<user_api::SignInRequest>, ) -> HttpResponse { let flow = Flow::UserSignIn; let req_payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow.clone(), state, &http_req, req_payload.clone(), |state, _: (), req_body, _| async move { user_core::signin_token_only_flow(state, req_body).await }, &auth::NoAuth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "email")] pub async fn user_connect_account( state: web::Data<AppState>, http_req: HttpRequest, json_payload: web::Json<user_api::ConnectAccountRequest>, query: web::Query<user_api::AuthIdAndThemeIdQueryParam>, ) -> HttpResponse { let flow = Flow::UserConnectAccount; let req_payload = json_payload.into_inner(); let query_params = query.into_inner(); Box::pin(api::server_wrap( flow.clone(), state, &http_req, req_payload.clone(), |state, _: (), req_body, _| { user_core::connect_account( state, req_body, query_params.auth_id.clone(), query_params.theme_id.clone(), ) }, &auth::NoAuth, api_locking::LockAction::NotApplicable, )) .await } pub async fn signout(state: web::Data<AppState>, http_req: HttpRequest) -> HttpResponse { let flow = Flow::Signout; Box::pin(api::server_wrap( flow, state.clone(), &http_req, (), |state, user, _, _| user_core::signout(state, user), &auth::AnyPurposeOrLoginTokenAuth, api_locking::LockAction::NotApplicable, )) .await } pub async fn change_password( state: web::Data<AppState>, http_req: HttpRequest, json_payload: web::Json<user_api::ChangePasswordRequest>, ) -> HttpResponse { let flow = Flow::ChangePassword; Box::pin(api::server_wrap( flow, state.clone(), &http_req, json_payload.into_inner(), |state, user, req, _| user_core::change_password(state, req, user), &auth::DashboardNoPermissionAuth, api_locking::LockAction::NotApplicable, )) .await } pub async fn set_dashboard_metadata( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<user_api::dashboard_metadata::SetMetaDataRequest>, ) -> HttpResponse { let flow = Flow::SetDashboardMetadata; let mut payload = json_payload.into_inner(); if let Err(e) = ReportSwitchExt::<(), ApiErrorResponse>::switch(set_ip_address_if_required( &mut payload, req.headers(), )) { return api::log_and_return_error_response(e); } Box::pin(api::server_wrap( flow, state, &req, payload, user_core::dashboard_metadata::set_metadata, &auth::JWTAuth { permission: Permission::ProfileAccountWrite, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn get_multiple_dashboard_metadata( state: web::Data<AppState>, req: HttpRequest, query: web::Query<user_api::dashboard_metadata::GetMultipleMetaDataRequest>, ) -> HttpResponse { let flow = Flow::GetMultipleDashboardMetadata; let payload = match ReportSwitchExt::<_, ApiErrorResponse>::switch(parse_string_to_enums( query.into_inner().keys, )) { Ok(payload) => payload, Err(e) => { return api::log_and_return_error_response(e); } }; Box::pin(api::server_wrap( flow, state, &req, payload, user_core::dashboard_metadata::get_multiple_metadata, &auth::DashboardNoPermissionAuth, api_locking::LockAction::NotApplicable, )) .await } pub async fn internal_user_signup( state: web::Data<AppState>, http_req: HttpRequest, json_payload: web::Json<user_api::CreateInternalUserRequest>, ) -> HttpResponse { let flow = Flow::InternalUserSignup; Box::pin(api::server_wrap( flow, state.clone(), &http_req, json_payload.into_inner(), |state, _, req, _| user_core::create_internal_user(state, req), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } pub async fn create_tenant_user( state: web::Data<AppState>, http_req: HttpRequest, json_payload: web::Json<user_api::CreateTenantUserRequest>, ) -> HttpResponse { let flow = Flow::TenantUserCreate; Box::pin(api::server_wrap( flow, state.clone(), &http_req, json_payload.into_inner(), |state, _, req, _| user_core::create_tenant_user(state, req), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] pub async fn create_platform( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<user_api::PlatformAccountCreateRequest>, ) -> HttpResponse { let flow = Flow::CreatePlatformAccount; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, user: auth::UserFromToken, json_payload, _| { user_core::create_platform_account(state, user, json_payload) }, &auth::JWTAuth { permission: Permission::OrganizationAccountWrite, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] pub async fn user_org_create( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<user_api::UserOrgMerchantCreateRequest>, ) -> HttpResponse { let flow = Flow::UserOrgMerchantCreate; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, _auth: auth::UserFromToken, json_payload, _| { user_core::create_org_merchant_for_user(state, json_payload) }, &auth::JWTAuth { permission: Permission::TenantAccountWrite, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn user_merchant_account_create( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<user_api::UserMerchantCreate>, ) -> HttpResponse { let flow = Flow::UserMerchantAccountCreate; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: auth::UserFromToken, json_payload, _| { user_core::create_merchant_account(state, auth, json_payload) }, &auth::JWTAuth { permission: Permission::OrganizationAccountWrite, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "dummy_connector", feature = "v1"))] pub async fn generate_sample_data( state: web::Data<AppState>, http_req: HttpRequest, payload: web::Json<SampleDataRequest>, ) -> impl actix_web::Responder { use crate::core::user::sample_data; let flow = Flow::GenerateSampleData; Box::pin(api::server_wrap( flow, state, &http_req, payload.into_inner(), sample_data::generate_sample_data_for_user, &auth::JWTAuth { permission: Permission::MerchantPaymentWrite, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "dummy_connector", feature = "v1"))] pub async fn delete_sample_data( state: web::Data<AppState>, http_req: HttpRequest, payload: web::Json<SampleDataRequest>, ) -> impl actix_web::Responder { use crate::core::user::sample_data; let flow = Flow::DeleteSampleData; Box::pin(api::server_wrap( flow, state, &http_req, payload.into_inner(), sample_data::delete_sample_data_for_user, &auth::JWTAuth { permission: Permission::MerchantAccountWrite, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn list_user_roles_details( state: web::Data<AppState>, req: HttpRequest, payload: web::Json<user_api::GetUserRoleDetailsRequest>, ) -> HttpResponse { let flow = Flow::GetUserRoleDetails; Box::pin(api::server_wrap( flow, state.clone(), &req, payload.into_inner(), user_core::list_user_roles_details, &auth::JWTAuth { permission: Permission::ProfileUserRead, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn rotate_password( state: web::Data<AppState>, req: HttpRequest, payload: web::Json<user_api::RotatePasswordRequest>, ) -> HttpResponse { let flow = Flow::RotatePassword; Box::pin(api::server_wrap( flow, state.clone(), &req, payload.into_inner(), user_core::rotate_password, &auth::SinglePurposeJWTAuth(TokenPurpose::ForceSetPassword), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "email")] pub async fn forgot_password( state: web::Data<AppState>, req: HttpRequest, payload: web::Json<user_api::ForgotPasswordRequest>, query: web::Query<user_api::AuthIdAndThemeIdQueryParam>, ) -> HttpResponse { let flow = Flow::ForgotPassword; let query_params = query.into_inner(); Box::pin(api::server_wrap( flow, state.clone(), &req, payload.into_inner(), |state, _: (), payload, _| { user_core::forgot_password( state, payload, query_params.auth_id.clone(), query_params.theme_id.clone(), ) }, &auth::NoAuth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "email")] pub async fn reset_password( state: web::Data<AppState>, req: HttpRequest, payload: web::Json<user_api::ResetPasswordRequest>, ) -> HttpResponse { let flow = Flow::ResetPassword; Box::pin(api::server_wrap( flow, state.clone(), &req, payload.into_inner(), |state, user, payload, _| user_core::reset_password_token_only_flow(state, user, payload), &auth::SinglePurposeJWTAuth(TokenPurpose::ResetPassword), api_locking::LockAction::NotApplicable, )) .await } pub async fn invite_multiple_user( state: web::Data<AppState>, req: HttpRequest, payload: web::Json<Vec<user_api::InviteUserRequest>>, auth_id_query_param: web::Query<user_api::AuthIdAndThemeIdQueryParam>, ) -> HttpResponse { let flow = Flow::InviteMultipleUser; let auth_id = auth_id_query_param.into_inner().auth_id; Box::pin(api::server_wrap( flow, state.clone(), &req, payload.into_inner(), |state, user, payload, req_state| { user_core::invite_multiple_user(state, user, payload, req_state, auth_id.clone()) }, &auth::JWTAuth { permission: Permission::ProfileUserWrite, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "email")] pub async fn resend_invite( state: web::Data<AppState>, req: HttpRequest, payload: web::Json<user_api::ReInviteUserRequest>, query: web::Query<user_api::AuthIdAndThemeIdQueryParam>, ) -> HttpResponse { let flow = Flow::ReInviteUser; let auth_id = query.into_inner().auth_id; Box::pin(api::server_wrap( flow, state.clone(), &req, payload.into_inner(), |state, user, req_payload, _| { user_core::resend_invite(state, user, req_payload, auth_id.clone()) }, &auth::JWTAuth { permission: Permission::ProfileUserWrite, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "email")] pub async fn accept_invite_from_email( state: web::Data<AppState>, req: HttpRequest, payload: web::Json<user_api::AcceptInviteFromEmailRequest>, ) -> HttpResponse { let flow = Flow::AcceptInviteFromEmail; Box::pin(api::server_wrap( flow.clone(), state, &req, payload.into_inner(), |state, user, req_payload, _| { user_core::accept_invite_from_email_token_only_flow(state, user, req_payload) }, &auth::SinglePurposeJWTAuth(TokenPurpose::AcceptInvitationFromEmail), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "email")] pub async fn verify_email( state: web::Data<AppState>, http_req: HttpRequest, json_payload: web::Json<user_api::VerifyEmailRequest>, ) -> HttpResponse { let flow = Flow::VerifyEmail; Box::pin(api::server_wrap( flow.clone(), state, &http_req, json_payload.into_inner(), |state, user, req_payload, _| { user_core::verify_email_token_only_flow(state, user, req_payload) }, &auth::SinglePurposeJWTAuth(TokenPurpose::VerifyEmail), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "email")] pub async fn verify_email_request( state: web::Data<AppState>, http_req: HttpRequest, json_payload: web::Json<user_api::SendVerifyEmailRequest>, query: web::Query<user_api::AuthIdAndThemeIdQueryParam>, ) -> HttpResponse { let flow = Flow::VerifyEmailRequest; let query_params = query.into_inner(); 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, query_params.auth_id.clone(), query_params.theme_id.clone(), ) }, &auth::NoAuth, api_locking::LockAction::NotApplicable, )) .await } pub async fn update_user_account_details( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<user_api::UpdateUserAccountDetailsRequest>, ) -> HttpResponse { let flow = Flow::UpdateUserAccountDetails; Box::pin(api::server_wrap( flow, state.clone(), &req, json_payload.into_inner(), user_core::update_user_details, &auth::DashboardNoPermissionAuth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "email")] pub async fn user_from_email( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<user_api::UserFromEmailRequest>, ) -> HttpResponse { let flow = Flow::UserFromEmail; Box::pin(api::server_wrap( flow, state.clone(), &req, json_payload.into_inner(), |state, _: (), req_body, _| user_core::user_from_email(state, req_body), &auth::NoAuth, api_locking::LockAction::NotApplicable, )) .await } pub async fn totp_begin(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { let flow = Flow::TotpBegin; Box::pin(api::server_wrap( flow, state.clone(), &req, (), |state, user, _, _| user_core::begin_totp(state, user), &auth::SinglePurposeJWTAuth(TokenPurpose::TOTP), api_locking::LockAction::NotApplicable, )) .await } pub async fn totp_reset(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { let flow = Flow::TotpReset; Box::pin(api::server_wrap( flow, state.clone(), &req, (), |state, user, _, _| user_core::reset_totp(state, user), &auth::DashboardNoPermissionAuth, api_locking::LockAction::NotApplicable, )) .await } pub async fn totp_verify( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<user_api::VerifyTotpRequest>, ) -> HttpResponse { let flow = Flow::TotpVerify; Box::pin(api::server_wrap( flow, state.clone(), &req, json_payload.into_inner(), |state, user, req_body, _| user_core::verify_totp(state, user, req_body), &auth::SinglePurposeOrLoginTokenAuth(TokenPurpose::TOTP), api_locking::LockAction::NotApplicable, )) .await } pub async fn verify_recovery_code( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<user_api::VerifyRecoveryCodeRequest>, ) -> HttpResponse { let flow = Flow::RecoveryCodeVerify; Box::pin(api::server_wrap( flow, state.clone(), &req, json_payload.into_inner(), |state, user, req_body, _| user_core::verify_recovery_code(state, user, req_body), &auth::SinglePurposeOrLoginTokenAuth(TokenPurpose::TOTP), api_locking::LockAction::NotApplicable, )) .await } pub async fn totp_update( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<user_api::VerifyTotpRequest>, ) -> HttpResponse { let flow = Flow::TotpUpdate; Box::pin(api::server_wrap( flow, state.clone(), &req, json_payload.into_inner(), |state, user, req_body, _| user_core::update_totp(state, user, req_body), &auth::SinglePurposeOrLoginTokenAuth(TokenPurpose::TOTP), api_locking::LockAction::NotApplicable, )) .await } pub async fn generate_recovery_codes(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { let flow = Flow::RecoveryCodesGenerate; Box::pin(api::server_wrap( flow, state.clone(), &req, (), |state, user, _, _| user_core::generate_recovery_codes(state, user), &auth::SinglePurposeOrLoginTokenAuth(TokenPurpose::TOTP), api_locking::LockAction::NotApplicable, )) .await } pub async fn terminate_two_factor_auth( state: web::Data<AppState>, req: HttpRequest, query: web::Query<user_api::SkipTwoFactorAuthQueryParam>, ) -> HttpResponse { let flow = Flow::TerminateTwoFactorAuth; let skip_two_factor_auth = query.into_inner().skip_two_factor_auth.unwrap_or(false); Box::pin(api::server_wrap( flow, state.clone(), &req, (), |state, user, _, _| user_core::terminate_two_factor_auth(state, user, skip_two_factor_auth), &auth::SinglePurposeJWTAuth(TokenPurpose::TOTP), api_locking::LockAction::NotApplicable, )) .await } pub async fn check_two_factor_auth_status( state: web::Data<AppState>, req: HttpRequest, ) -> HttpResponse { let flow = Flow::TwoFactorAuthStatus; Box::pin(api::server_wrap( flow, state.clone(), &req, (), |state, user, _, _| user_core::check_two_factor_auth_status(state, user), &auth::DashboardNoPermissionAuth, api_locking::LockAction::NotApplicable, )) .await } pub async fn check_two_factor_auth_status_with_attempts( state: web::Data<AppState>, req: HttpRequest, ) -> HttpResponse { let flow = Flow::TwoFactorAuthStatus; Box::pin(api::server_wrap( flow, state.clone(), &req, (), |state, user, _, _| user_core::check_two_factor_auth_status_with_attempts(state, user), &auth::SinglePurposeOrLoginTokenAuth(TokenPurpose::TOTP), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] pub async fn get_sso_auth_url( state: web::Data<AppState>, req: HttpRequest, query: web::Query<user_api::GetSsoAuthUrlRequest>, ) -> HttpResponse { let flow = Flow::GetSsoAuthUrl; let payload = query.into_inner(); Box::pin(api::server_wrap( flow, state.clone(), &req, payload, |state, _: (), req, _| user_core::get_sso_auth_url(state, req), &auth::NoAuth, api_locking::LockAction::NotApplicable, )) .await } pub async fn sso_sign( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<user_api::SsoSignInRequest>, ) -> HttpResponse { let flow = Flow::SignInWithSso; let payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow, state.clone(), &req, payload, |state, user: Option<auth::UserFromSinglePurposeToken>, payload, _| { user_core::sso_sign(state, payload, user) }, auth::auth_type( &auth::NoAuth, &auth::SinglePurposeJWTAuth(TokenPurpose::SSO), req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } pub async fn create_user_authentication_method( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<user_api::CreateUserAuthenticationMethodRequest>, ) -> HttpResponse { let flow = Flow::CreateUserAuthenticationMethod; Box::pin(api::server_wrap( flow, state.clone(), &req, json_payload.into_inner(), |state, _, req_body, _| user_core::create_user_authentication_method(state, req_body), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } pub async fn update_user_authentication_method( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<user_api::UpdateUserAuthenticationMethodRequest>, ) -> HttpResponse { let flow = Flow::UpdateUserAuthenticationMethod; Box::pin(api::server_wrap( flow, state.clone(), &req, json_payload.into_inner(), |state, _, req_body, _| user_core::update_user_authentication_method(state, req_body), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } pub async fn list_user_authentication_methods( state: web::Data<AppState>, req: HttpRequest, query: web::Query<user_api::GetUserAuthenticationMethodsRequest>, ) -> HttpResponse { let flow = Flow::ListUserAuthenticationMethods; Box::pin(api::server_wrap( flow, state.clone(), &req, query.into_inner(), |state, _: (), req, _| user_core::list_user_authentication_methods(state, req), &auth::NoAuth, api_locking::LockAction::NotApplicable, )) .await } pub async fn terminate_auth_select( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<user_api::AuthSelectRequest>, ) -> HttpResponse { let flow = Flow::AuthSelect; Box::pin(api::server_wrap( flow, state.clone(), &req, json_payload.into_inner(), |state, user, req, _| user_core::terminate_auth_select(state, user, req), &auth::SinglePurposeJWTAuth(TokenPurpose::AuthSelect), api_locking::LockAction::NotApplicable, )) .await } pub async fn transfer_user_key( state: web::Data<AppState>, req: HttpRequest, payload: web::Json<user_api::UserKeyTransferRequest>, ) -> HttpResponse { let flow = Flow::UserTransferKey; Box::pin(api::server_wrap( flow, state.clone(), &req, payload.into_inner(), |state, _, req, _| user_core::transfer_user_key_store_keymanager(state, req), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } pub async fn list_orgs_for_user(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { let flow = Flow::ListOrgForUser; Box::pin(api::server_wrap( flow, state.clone(), &req, (), |state, user_from_token, _, _| user_core::list_orgs_for_user(state, user_from_token), &auth::DashboardNoPermissionAuth, api_locking::LockAction::NotApplicable, )) .await } pub async fn list_merchants_for_user_in_org( state: web::Data<AppState>, req: HttpRequest, ) -> HttpResponse { let flow = Flow::ListMerchantsForUserInOrg; Box::pin(api::server_wrap( flow, state.clone(), &req, (), |state, user_from_token, _, _| { user_core::list_merchants_for_user_in_org(state, user_from_token) }, &auth::DashboardNoPermissionAuth, api_locking::LockAction::NotApplicable, )) .await } pub async fn list_profiles_for_user_in_org_and_merchant( state: web::Data<AppState>, req: HttpRequest, ) -> HttpResponse { let flow = Flow::ListProfileForUserInOrgAndMerchant; Box::pin(api::server_wrap( flow, state.clone(), &req, (), |state, user_from_token, _, _| { user_core::list_profiles_for_user_in_org_and_merchant_account(state, user_from_token) }, &auth::DashboardNoPermissionAuth, api_locking::LockAction::NotApplicable, )) .await } pub async fn switch_org_for_user( state: web::Data<AppState>, http_req: HttpRequest, json_payload: web::Json<user_api::SwitchOrganizationRequest>, ) -> HttpResponse { let flow = Flow::SwitchOrg; Box::pin(api::server_wrap( flow, state.clone(), &http_req, json_payload.into_inner(), |state, user, req, _| user_core::switch_org_for_user(state, req, user), &auth::DashboardNoPermissionAuth, api_locking::LockAction::NotApplicable, )) .await } pub async fn switch_merchant_for_user_in_org( state: web::Data<AppState>, http_req: HttpRequest, json_payload: web::Json<user_api::SwitchMerchantRequest>, ) -> HttpResponse { let flow = Flow::SwitchMerchantV2; Box::pin(api::server_wrap( flow, state.clone(), &http_req, json_payload.into_inner(), |state, user, req, _| user_core::switch_merchant_for_user_in_org(state, req, user), &auth::DashboardNoPermissionAuth, api_locking::LockAction::NotApplicable, )) .await } pub async fn switch_profile_for_user_in_org_and_merchant( state: web::Data<AppState>, http_req: HttpRequest, json_payload: web::Json<user_api::SwitchProfileRequest>, ) -> HttpResponse { let flow = Flow::SwitchProfile; Box::pin(api::server_wrap( flow, state.clone(), &http_req, json_payload.into_inner(), |state, user, req, _| { user_core::switch_profile_for_user_in_org_and_merchant(state, req, user) }, &auth::DashboardNoPermissionAuth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] pub async fn clone_connector( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<user_api::CloneConnectorRequest>, ) -> HttpResponse { let flow = Flow::CloneConnector; Box::pin(api::server_wrap( flow, state.clone(), &req, json_payload.into_inner(), |state, _: auth::UserFromToken, req, _| user_core::clone_connector(state, req), &auth::JWTAuth { permission: Permission::MerchantInternalConnectorWrite, }, api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/user.rs
router::src::routes::user
7,099
true
// File: crates/router/src/routes/user_role.rs // Module: router::src::routes::user_role use actix_web::{web, HttpRequest, HttpResponse}; use api_models::user_role::{self as user_role_api, role as role_api}; use common_enums::TokenPurpose; use router_env::Flow; use super::AppState; use crate::{ core::{ api_locking, user_role::{self as user_role_core, role as role_core}, }, services::{ api, authentication::{self as auth}, authorization::permissions::Permission, }, }; // TODO: To be deprecated pub async fn get_authorization_info( state: web::Data<AppState>, http_req: HttpRequest, ) -> HttpResponse { let flow = Flow::GetAuthorizationInfo; Box::pin(api::server_wrap( flow, state.clone(), &http_req, (), |state, _: (), _, _| async move { user_role_core::get_authorization_info_with_groups(state).await }, &auth::JWTAuth { permission: Permission::MerchantUserRead, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn get_role_from_token(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { let flow = Flow::GetRoleFromToken; Box::pin(api::server_wrap( flow, state.clone(), &req, (), |state, user, _, _| async move { role_core::get_role_from_token_with_groups(state, user).await }, &auth::DashboardNoPermissionAuth, api_locking::LockAction::NotApplicable, )) .await } pub async fn get_groups_and_resources_for_role_from_token( state: web::Data<AppState>, req: HttpRequest, ) -> HttpResponse { let flow = Flow::GetRoleFromTokenV2; Box::pin(api::server_wrap( flow, state.clone(), &req, (), |state, user, _, _| async move { role_core::get_groups_and_resources_for_role_from_token(state, user).await }, &auth::DashboardNoPermissionAuth, api_locking::LockAction::NotApplicable, )) .await } pub async fn get_parent_groups_info_for_role_from_token( state: web::Data<AppState>, req: HttpRequest, ) -> HttpResponse { let flow = Flow::GetParentGroupsInfoForRoleFromToken; Box::pin(api::server_wrap( flow, state.clone(), &req, (), |state, user, _, _| async move { role_core::get_parent_groups_info_for_role_from_token(state, user).await }, &auth::DashboardNoPermissionAuth, api_locking::LockAction::NotApplicable, )) .await } // TODO: To be deprecated pub async fn create_role( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<role_api::CreateRoleRequest>, ) -> HttpResponse { let flow = Flow::CreateRole; Box::pin(api::server_wrap( flow, state.clone(), &req, json_payload.into_inner(), role_core::create_role, &auth::JWTAuth { permission: Permission::MerchantUserWrite, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn create_role_v2( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<role_api::CreateRoleV2Request>, ) -> HttpResponse { let flow = Flow::CreateRoleV2; Box::pin(api::server_wrap( flow, state.clone(), &req, json_payload.into_inner(), role_core::create_role_v2, &auth::JWTAuth { permission: Permission::MerchantUserWrite, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn get_role( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, ) -> HttpResponse { let flow = Flow::GetRole; let request_payload = user_role_api::role::GetRoleRequest { role_id: path.into_inner(), }; Box::pin(api::server_wrap( flow, state.clone(), &req, request_payload, |state, user, payload, _| async move { role_core::get_role_with_groups(state, user, payload).await }, &auth::JWTAuth { permission: Permission::ProfileUserRead, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn get_parent_info_for_role( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, ) -> HttpResponse { let flow = Flow::GetRoleV2; let request_payload = user_role_api::role::GetRoleRequest { role_id: path.into_inner(), }; Box::pin(api::server_wrap( flow, state.clone(), &req, request_payload, |state, user, payload, _| async move { role_core::get_parent_info_for_role(state, user, payload).await }, &auth::JWTAuth { permission: Permission::ProfileUserRead, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn update_role( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<role_api::UpdateRoleRequest>, path: web::Path<String>, ) -> HttpResponse { let flow = Flow::UpdateRole; let role_id = path.into_inner(); Box::pin(api::server_wrap( flow, state.clone(), &req, json_payload.into_inner(), |state, user, req, _| role_core::update_role(state, user, req, &role_id), &auth::JWTAuth { permission: Permission::MerchantUserWrite, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn update_user_role( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<user_role_api::UpdateUserRoleRequest>, ) -> HttpResponse { let flow = Flow::UpdateUserRole; let payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow, state.clone(), &req, payload, user_role_core::update_user_role, &auth::JWTAuth { permission: Permission::ProfileUserWrite, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn accept_invitations_v2( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<user_role_api::AcceptInvitationsV2Request>, ) -> HttpResponse { let flow = Flow::AcceptInvitationsV2; let payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow, state.clone(), &req, payload, |state, user, req_body, _| user_role_core::accept_invitations_v2(state, user, req_body), &auth::DashboardNoPermissionAuth, api_locking::LockAction::NotApplicable, )) .await } pub async fn accept_invitations_pre_auth( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<user_role_api::AcceptInvitationsPreAuthRequest>, ) -> HttpResponse { let flow = Flow::AcceptInvitationsPreAuth; let payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow, state.clone(), &req, payload, |state, user, req_body, _| async move { user_role_core::accept_invitations_pre_auth(state, user, req_body).await }, &auth::SinglePurposeJWTAuth(TokenPurpose::AcceptInvite), api_locking::LockAction::NotApplicable, )) .await } pub async fn delete_user_role( state: web::Data<AppState>, req: HttpRequest, payload: web::Json<user_role_api::DeleteUserRoleRequest>, ) -> HttpResponse { let flow = Flow::DeleteUserRole; Box::pin(api::server_wrap( flow, state.clone(), &req, payload.into_inner(), user_role_core::delete_user_role, &auth::JWTAuth { permission: Permission::ProfileUserWrite, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn get_role_information( state: web::Data<AppState>, http_req: HttpRequest, ) -> HttpResponse { let flow = Flow::GetRolesInfo; Box::pin(api::server_wrap( flow, state.clone(), &http_req, (), |_, _: (), _, _| async move { user_role_core::get_authorization_info_with_group_tag().await }, &auth::JWTAuth { permission: Permission::ProfileUserRead, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn get_parent_group_info( state: web::Data<AppState>, http_req: HttpRequest, query: web::Query<role_api::GetParentGroupsInfoQueryParams>, ) -> HttpResponse { let flow = Flow::GetParentGroupInfo; Box::pin(api::server_wrap( flow, state.clone(), &http_req, query.into_inner(), |state, user_from_token, request, _| async move { user_role_core::get_parent_group_info(state, user_from_token, request).await }, &auth::JWTAuth { permission: Permission::ProfileUserRead, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn list_users_in_lineage( state: web::Data<AppState>, req: HttpRequest, query: web::Query<user_role_api::ListUsersInEntityRequest>, ) -> HttpResponse { let flow = Flow::ListUsersInLineage; Box::pin(api::server_wrap( flow, state.clone(), &req, query.into_inner(), |state, user_from_token, request, _| { user_role_core::list_users_in_lineage(state, user_from_token, request) }, &auth::DashboardNoPermissionAuth, api_locking::LockAction::NotApplicable, )) .await } pub async fn list_roles_with_info( state: web::Data<AppState>, req: HttpRequest, query: web::Query<role_api::ListRolesQueryParams>, ) -> HttpResponse { let flow = Flow::ListRolesV2; Box::pin(api::server_wrap( flow, state.clone(), &req, query.into_inner(), |state, user_from_token, request, _| { role_core::list_roles_with_info(state, user_from_token, request) }, &auth::JWTAuth { permission: Permission::ProfileUserRead, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn list_invitable_roles_at_entity_level( state: web::Data<AppState>, req: HttpRequest, query: web::Query<role_api::ListRolesAtEntityLevelRequest>, ) -> HttpResponse { let flow = Flow::ListInvitableRolesAtEntityLevel; Box::pin(api::server_wrap( flow, state.clone(), &req, query.into_inner(), |state, user_from_token, req, _| { role_core::list_roles_at_entity_level( state, user_from_token, req, role_api::RoleCheckType::Invite, ) }, &auth::JWTAuth { permission: Permission::ProfileUserRead, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn list_updatable_roles_at_entity_level( state: web::Data<AppState>, req: HttpRequest, query: web::Query<role_api::ListRolesAtEntityLevelRequest>, ) -> HttpResponse { let flow = Flow::ListUpdatableRolesAtEntityLevel; Box::pin(api::server_wrap( flow, state.clone(), &req, query.into_inner(), |state, user_from_token, req, _| { role_core::list_roles_at_entity_level( state, user_from_token, req, role_api::RoleCheckType::Update, ) }, &auth::JWTAuth { permission: Permission::ProfileUserRead, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn list_invitations_for_user( state: web::Data<AppState>, req: HttpRequest, ) -> HttpResponse { let flow = Flow::ListInvitationsForUser; Box::pin(api::server_wrap( flow, state.clone(), &req, (), |state, user_id_from_token, _, _| { user_role_core::list_invitations_for_user(state, user_id_from_token) }, &auth::SinglePurposeOrLoginTokenAuth(TokenPurpose::AcceptInvite), api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/user_role.rs
router::src::routes::user_role
2,914
true
// File: crates/router/src/routes/files.rs // Module: router::src::routes::files use actix_multipart::Multipart; use actix_web::{web, HttpRequest, HttpResponse}; use api_models::files as file_types; use router_env::{instrument, tracing, Flow}; use crate::core::api_locking; pub mod transformers; use super::app::AppState; use crate::{ core::files::*, services::{api, authentication as auth}, types::{api::files, domain}, }; #[cfg(feature = "v1")] /// Files - Create /// /// To create a file #[utoipa::path( post, path = "/files", request_body=MultipartRequestWithFile, responses( (status = 200, description = "File created", body = CreateFileResponse), (status = 400, description = "Bad Request") ), tag = "Files", operation_id = "Create a File", security(("api_key" = [])) )] #[instrument(skip_all, fields(flow = ?Flow::CreateFile))] pub async fn files_create( state: web::Data<AppState>, req: HttpRequest, payload: Multipart, ) -> HttpResponse { let flow = Flow::CreateFile; let create_file_request_result = transformers::get_create_file_request(payload).await; let create_file_request = match create_file_request_result { Ok(valid_request) => valid_request, Err(err) => return api::log_and_return_error_response(err), }; Box::pin(api::server_wrap( flow, state, &req, create_file_request, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); files_create_core(state, merchant_context, req) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::DashboardNoPermissionAuth, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] /// Files - Delete /// /// To delete a file #[utoipa::path( delete, path = "/files/{file_id}", params( ("file_id" = String, Path, description = "The identifier for file") ), responses( (status = 200, description = "File deleted"), (status = 404, description = "File not found") ), tag = "Files", operation_id = "Delete a File", security(("api_key" = [])) )] #[instrument(skip_all, fields(flow = ?Flow::DeleteFile))] pub async fn files_delete( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, ) -> HttpResponse { let flow = Flow::DeleteFile; let file_id = files::FileId { file_id: path.into_inner(), }; Box::pin(api::server_wrap( flow, state, &req, file_id, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); files_delete_core(state, merchant_context, req) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::DashboardNoPermissionAuth, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] /// Files - Retrieve /// /// To retrieve a file #[utoipa::path( get, path = "/files/{file_id}", params( ("file_id" = String, Path, description = "The identifier for file") ), responses( (status = 200, description = "File body"), (status = 400, description = "Bad Request") ), tag = "Files", operation_id = "Retrieve a File", security(("api_key" = [])) )] #[instrument(skip_all, fields(flow = ?Flow::RetrieveFile))] pub async fn files_retrieve( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, json_payload: web::Query<file_types::FileRetrieveQuery>, ) -> HttpResponse { let flow = Flow::RetrieveFile; let file_id = files::FileRetrieveRequest { file_id: path.into_inner(), dispute_id: json_payload.dispute_id.clone(), }; Box::pin(api::server_wrap( flow, state, &req, file_id, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); files_retrieve_core(state, merchant_context, req) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::DashboardNoPermissionAuth, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/files.rs
router::src::routes::files
1,196
true
// File: crates/router/src/routes/metrics.rs // Module: router::src::routes::metrics pub mod bg_metrics_collector; pub mod request; use router_env::{counter_metric, global_meter, histogram_metric_f64}; global_meter!(GLOBAL_METER, "ROUTER_API"); counter_metric!(HEALTH_METRIC, GLOBAL_METER); // No. of health API hits counter_metric!(KV_MISS, GLOBAL_METER); // No. of KV misses // API Level Metrics counter_metric!(REQUESTS_RECEIVED, GLOBAL_METER); histogram_metric_f64!(REQUEST_TIME, GLOBAL_METER); // Operation Level Metrics counter_metric!(PAYMENT_OPS_COUNT, GLOBAL_METER); counter_metric!(PAYMENT_COUNT, GLOBAL_METER); counter_metric!(SUCCESSFUL_PAYMENT, GLOBAL_METER); //TODO: This can be removed, added for payment list debugging histogram_metric_f64!(PAYMENT_LIST_LATENCY, GLOBAL_METER); counter_metric!(REFUND_COUNT, GLOBAL_METER); counter_metric!(SUCCESSFUL_REFUND, GLOBAL_METER); counter_metric!(PAYMENT_CANCEL_COUNT, GLOBAL_METER); counter_metric!(SUCCESSFUL_CANCEL, GLOBAL_METER); counter_metric!(PAYMENT_EXTEND_AUTHORIZATION_COUNT, GLOBAL_METER); counter_metric!(SUCCESSFUL_EXTEND_AUTHORIZATION_COUNT, GLOBAL_METER); counter_metric!(MANDATE_COUNT, GLOBAL_METER); counter_metric!(SUBSEQUENT_MANDATE_PAYMENT, GLOBAL_METER); // Manual retry metrics counter_metric!(MANUAL_RETRY_REQUEST_COUNT, GLOBAL_METER); counter_metric!(MANUAL_RETRY_COUNT, GLOBAL_METER); counter_metric!(MANUAL_RETRY_VALIDATION_FAILED, GLOBAL_METER); counter_metric!(STORED_TO_LOCKER, GLOBAL_METER); counter_metric!(GET_FROM_LOCKER, GLOBAL_METER); counter_metric!(DELETE_FROM_LOCKER, GLOBAL_METER); counter_metric!(CREATED_TOKENIZED_CARD, GLOBAL_METER); counter_metric!(DELETED_TOKENIZED_CARD, GLOBAL_METER); counter_metric!(GET_TOKENIZED_CARD, GLOBAL_METER); counter_metric!(TOKENIZED_DATA_COUNT, GLOBAL_METER); // Tokenized data added counter_metric!(RETRIED_DELETE_DATA_COUNT, GLOBAL_METER); // Tokenized data retried counter_metric!(CUSTOMER_CREATED, GLOBAL_METER); counter_metric!(CUSTOMER_REDACTED, GLOBAL_METER); counter_metric!(API_KEY_CREATED, GLOBAL_METER); counter_metric!(API_KEY_REVOKED, GLOBAL_METER); counter_metric!(MCA_CREATE, GLOBAL_METER); // Flow Specific Metrics histogram_metric_f64!(CONNECTOR_REQUEST_TIME, GLOBAL_METER); counter_metric!(SESSION_TOKEN_CREATED, GLOBAL_METER); counter_metric!(CONNECTOR_CALL_COUNT, GLOBAL_METER); // Attributes needed counter_metric!(THREE_DS_PAYMENT_COUNT, GLOBAL_METER); counter_metric!(THREE_DS_DOWNGRADE_COUNT, GLOBAL_METER); counter_metric!(RESPONSE_DESERIALIZATION_FAILURE, GLOBAL_METER); counter_metric!(CONNECTOR_ERROR_RESPONSE_COUNT, GLOBAL_METER); counter_metric!(REQUEST_TIMEOUT_COUNT, GLOBAL_METER); counter_metric!(EXECUTE_PRETASK_COUNT, GLOBAL_METER); counter_metric!(CONNECTOR_PAYMENT_METHOD_TOKENIZATION, GLOBAL_METER); counter_metric!(PREPROCESSING_STEPS_COUNT, GLOBAL_METER); counter_metric!(CONNECTOR_CUSTOMER_CREATE, GLOBAL_METER); counter_metric!(REDIRECTION_TRIGGERED, GLOBAL_METER); // Connector Level Metric counter_metric!(REQUEST_BUILD_FAILURE, GLOBAL_METER); // Connector http status code metrics counter_metric!(CONNECTOR_HTTP_STATUS_CODE_1XX_COUNT, GLOBAL_METER); counter_metric!(CONNECTOR_HTTP_STATUS_CODE_2XX_COUNT, GLOBAL_METER); counter_metric!(CONNECTOR_HTTP_STATUS_CODE_3XX_COUNT, GLOBAL_METER); counter_metric!(CONNECTOR_HTTP_STATUS_CODE_4XX_COUNT, GLOBAL_METER); counter_metric!(CONNECTOR_HTTP_STATUS_CODE_5XX_COUNT, GLOBAL_METER); // Service Level counter_metric!(CARD_LOCKER_FAILURES, GLOBAL_METER); counter_metric!(CARD_LOCKER_SUCCESSFUL_RESPONSE, GLOBAL_METER); counter_metric!(TEMP_LOCKER_FAILURES, GLOBAL_METER); histogram_metric_f64!(CARD_ADD_TIME, GLOBAL_METER); histogram_metric_f64!(CARD_GET_TIME, GLOBAL_METER); histogram_metric_f64!(CARD_DELETE_TIME, GLOBAL_METER); // Apple Pay Flow Metrics counter_metric!(APPLE_PAY_MANUAL_FLOW, GLOBAL_METER); counter_metric!(APPLE_PAY_SIMPLIFIED_FLOW, GLOBAL_METER); counter_metric!(APPLE_PAY_MANUAL_FLOW_SUCCESSFUL_PAYMENT, GLOBAL_METER); counter_metric!(APPLE_PAY_SIMPLIFIED_FLOW_SUCCESSFUL_PAYMENT, GLOBAL_METER); counter_metric!(APPLE_PAY_MANUAL_FLOW_FAILED_PAYMENT, GLOBAL_METER); counter_metric!(APPLE_PAY_SIMPLIFIED_FLOW_FAILED_PAYMENT, GLOBAL_METER); // Metrics for Payment Auto Retries counter_metric!(AUTO_RETRY_ELIGIBLE_REQUEST_COUNT, GLOBAL_METER); counter_metric!(AUTO_RETRY_GSM_MISS_COUNT, GLOBAL_METER); counter_metric!(AUTO_RETRY_GSM_FETCH_FAILURE_COUNT, GLOBAL_METER); counter_metric!(AUTO_RETRY_GSM_MATCH_COUNT, GLOBAL_METER); counter_metric!(AUTO_RETRY_EXHAUSTED_COUNT, GLOBAL_METER); counter_metric!(AUTO_RETRY_PAYMENT_COUNT, GLOBAL_METER); // Metrics for Payout Auto Retries counter_metric!(AUTO_PAYOUT_RETRY_ELIGIBLE_REQUEST_COUNT, GLOBAL_METER); counter_metric!(AUTO_PAYOUT_RETRY_GSM_MISS_COUNT, GLOBAL_METER); counter_metric!(AUTO_PAYOUT_RETRY_GSM_FETCH_FAILURE_COUNT, GLOBAL_METER); counter_metric!(AUTO_PAYOUT_RETRY_GSM_MATCH_COUNT, GLOBAL_METER); counter_metric!(AUTO_PAYOUT_RETRY_EXHAUSTED_COUNT, GLOBAL_METER); counter_metric!(AUTO_RETRY_PAYOUT_COUNT, GLOBAL_METER); // Scheduler / Process Tracker related metrics counter_metric!(TASKS_ADDED_COUNT, GLOBAL_METER); // Tasks added to process tracker counter_metric!(TASK_ADDITION_FAILURES_COUNT, GLOBAL_METER); // Failures in task addition to process tracker counter_metric!(TASKS_RESET_COUNT, GLOBAL_METER); // Tasks reset in process tracker for requeue flow // Access token metrics // // A counter to indicate the number of new access tokens created counter_metric!(ACCESS_TOKEN_CREATION, GLOBAL_METER); // A counter to indicate the access token cache hits counter_metric!(ACCESS_TOKEN_CACHE_HIT, GLOBAL_METER); // A counter to indicate the access token cache miss counter_metric!(ACCESS_TOKEN_CACHE_MISS, GLOBAL_METER); // A counter to indicate the integrity check failures counter_metric!(INTEGRITY_CHECK_FAILED, GLOBAL_METER); // Network Tokenization metrics histogram_metric_f64!(GENERATE_NETWORK_TOKEN_TIME, GLOBAL_METER); histogram_metric_f64!(FETCH_NETWORK_TOKEN_TIME, GLOBAL_METER); histogram_metric_f64!(DELETE_NETWORK_TOKEN_TIME, GLOBAL_METER); histogram_metric_f64!(CHECK_NETWORK_TOKEN_STATUS_TIME, GLOBAL_METER); // A counter to indicate allowed payment method types mismatch counter_metric!(PAYMENT_METHOD_TYPES_MISCONFIGURATION_METRIC, GLOBAL_METER); // AI chat metric to track number of chat request counter_metric!(CHAT_REQUEST_COUNT, GLOBAL_METER);
crates/router/src/routes/metrics.rs
router::src::routes::metrics
1,491
true
// File: crates/router/src/routes/recovery_webhooks.rs // Module: router::src::routes::recovery_webhooks use actix_web::{web, HttpRequest, Responder}; use router_env::{instrument, tracing, Flow}; use super::app::AppState; use crate::{ core::{ api_locking, webhooks::{self, types}, }, services::{api, authentication as auth}, types::domain, }; #[instrument(skip_all, fields(flow = ?Flow::IncomingWebhookReceive))] pub async fn recovery_receive_incoming_webhook<W: types::OutgoingWebhookType>( state: web::Data<AppState>, req: HttpRequest, body: web::Bytes, path: web::Path<( common_utils::id_type::MerchantId, common_utils::id_type::ProfileId, common_utils::id_type::MerchantConnectorAccountId, )>, ) -> impl Responder { let flow = Flow::RecoveryIncomingWebhookReceive; let (merchant_id, profile_id, connector_id) = path.into_inner(); Box::pin(api::server_wrap( flow.clone(), state, &req, (), |state, auth, _, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); webhooks::incoming_webhooks_wrapper::<W>( &flow, state.to_owned(), req_state, &req, merchant_context, auth.profile, &connector_id, body.clone(), false, ) }, &auth::MerchantIdAndProfileIdAuth { merchant_id, profile_id, }, api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/recovery_webhooks.rs
router::src::routes::recovery_webhooks
382
true
// File: crates/router/src/routes/profiles.rs // Module: router::src::routes::profiles use actix_web::{web, HttpRequest, HttpResponse}; use router_env::{instrument, tracing, Flow}; use super::app::AppState; use crate::{ core::{admin::*, api_locking, errors}, services::{api, authentication as auth, authorization::permissions}, types::{api::admin, domain}, }; #[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all, fields(flow = ?Flow::ProfileCreate))] pub async fn profile_create( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<admin::ProfileCreate>, path: web::Path<common_utils::id_type::MerchantId>, ) -> HttpResponse { let flow = Flow::ProfileCreate; let payload = json_payload.into_inner(); let merchant_id = path.into_inner(); if let Err(api_error) = payload .webhook_details .as_ref() .map(|details| { details .validate() .map_err(|message| errors::ApiErrorResponse::InvalidRequestData { message }) }) .transpose() { return api::log_and_return_error_response(api_error.into()); } Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth_data, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth_data.merchant_account, auth_data.key_store), )); create_profile(state, req, merchant_context) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: permissions::Permission::MerchantAccountWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v2"))] #[instrument(skip_all, fields(flow = ?Flow::ProfileCreate))] pub async fn profile_create( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<admin::ProfileCreate>, ) -> HttpResponse { let flow = Flow::ProfileCreate; let payload = json_payload.into_inner(); if let Err(api_error) = payload .webhook_details .as_ref() .map(|details| { details .validate() .map_err(|message| errors::ApiErrorResponse::InvalidRequestData { message }) }) .transpose() { return api::log_and_return_error_response(api_error.into()); } Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth::AuthenticationDataWithoutProfile { merchant_account, key_store, }, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(merchant_account, key_store), )); create_profile(state, req, merchant_context) }, auth::auth_type( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromHeader { required_permission: permissions::Permission::MerchantAccountWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::ProfileRetrieve))] pub async fn profile_retrieve( state: web::Data<AppState>, req: HttpRequest, path: web::Path<( common_utils::id_type::MerchantId, common_utils::id_type::ProfileId, )>, ) -> HttpResponse { let flow = Flow::ProfileRetrieve; let (merchant_id, profile_id) = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, profile_id, |state, auth_data, profile_id, _| retrieve_profile(state, profile_id, auth_data.key_store), auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: permissions::Permission::ProfileAccountRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::ProfileRetrieve))] pub async fn profile_retrieve( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::ProfileId>, ) -> HttpResponse { let flow = Flow::ProfileRetrieve; let profile_id = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, profile_id, |state, auth::AuthenticationDataWithoutProfile { key_store, .. }, profile_id, _| { retrieve_profile(state, profile_id, key_store) }, auth::auth_type( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromHeader { required_permission: permissions::Permission::MerchantAccountRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all, fields(flow = ?Flow::ProfileUpdate))] pub async fn profile_update( state: web::Data<AppState>, req: HttpRequest, path: web::Path<( common_utils::id_type::MerchantId, common_utils::id_type::ProfileId, )>, json_payload: web::Json<api_models::admin::ProfileUpdate>, ) -> HttpResponse { let flow = Flow::ProfileUpdate; let (merchant_id, profile_id) = path.into_inner(); let payload = json_payload.into_inner(); if let Err(api_error) = payload .webhook_details .as_ref() .map(|details| { details .validate() .map_err(|message| errors::ApiErrorResponse::InvalidRequestData { message }) }) .transpose() { return api::log_and_return_error_response(api_error.into()); } Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth_data, req, _| update_profile(state, &profile_id, auth_data.key_store, req), auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantAndProfileFromRoute { merchant_id: merchant_id.clone(), profile_id: profile_id.clone(), required_permission: permissions::Permission::ProfileAccountWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::ProfileUpdate))] pub async fn profile_update( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::ProfileId>, json_payload: web::Json<api_models::admin::ProfileUpdate>, ) -> HttpResponse { let flow = Flow::ProfileUpdate; let profile_id = path.into_inner(); let payload = json_payload.into_inner(); if let Err(api_error) = payload .webhook_details .as_ref() .map(|details| { details .validate() .map_err(|message| errors::ApiErrorResponse::InvalidRequestData { message }) }) .transpose() { return api::log_and_return_error_response(api_error.into()); } Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth::AuthenticationDataWithoutProfile { key_store, .. }, req, _| { update_profile(state, &profile_id, key_store, req) }, auth::auth_type( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromHeader { required_permission: permissions::Permission::MerchantAccountWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::ProfileDelete))] pub async fn profile_delete( state: web::Data<AppState>, req: HttpRequest, path: web::Path<( common_utils::id_type::MerchantId, common_utils::id_type::ProfileId, )>, ) -> HttpResponse { let flow = Flow::ProfileDelete; let (merchant_id, profile_id) = path.into_inner(); api::server_wrap( flow, state, &req, profile_id, |state, _, profile_id, _| delete_profile(state, profile_id, &merchant_id), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, ) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::ProfileList))] pub async fn profiles_list( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::MerchantId>, ) -> HttpResponse { let flow = Flow::ProfileList; let merchant_id = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, merchant_id.clone(), |state, _auth, merchant_id, _| list_profile(state, merchant_id, None), auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: permissions::Permission::MerchantAccountRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::ProfileList))] pub async fn profiles_list( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::MerchantId>, ) -> HttpResponse { let flow = Flow::ProfileList; let merchant_id = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, merchant_id.clone(), |state, auth::AuthenticationDataWithoutProfile { .. }, merchant_id, _| { list_profile(state, merchant_id, None) }, auth::auth_type( &auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: permissions::Permission::MerchantAccountRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all, fields(flow = ?Flow::ProfileList))] pub async fn profiles_list_at_profile_level( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::MerchantId>, ) -> HttpResponse { let flow = Flow::ProfileList; let merchant_id = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, merchant_id.clone(), |state, auth, merchant_id, _| { list_profile( state, merchant_id, auth.profile_id.map(|profile_id| vec![profile_id]), ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: permissions::Permission::ProfileAccountRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::ToggleConnectorAgnosticMit))] pub async fn toggle_connector_agnostic_mit( state: web::Data<AppState>, req: HttpRequest, path: web::Path<( common_utils::id_type::MerchantId, common_utils::id_type::ProfileId, )>, json_payload: web::Json<api_models::admin::ConnectorAgnosticMitChoice>, ) -> HttpResponse { let flow = Flow::ToggleConnectorAgnosticMit; let (merchant_id, profile_id) = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, _: auth::AuthenticationData, req, _| { connector_agnostic_mit_toggle(state, &merchant_id, &profile_id, req) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: permissions::Permission::MerchantRoutingWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::ToggleExtendedCardInfo))] pub async fn toggle_extended_card_info( state: web::Data<AppState>, req: HttpRequest, path: web::Path<( common_utils::id_type::MerchantId, common_utils::id_type::ProfileId, )>, json_payload: web::Json<api_models::admin::ExtendedCardInfoChoice>, ) -> HttpResponse { let flow = Flow::ToggleExtendedCardInfo; let (merchant_id, profile_id) = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, _, req, _| extended_card_info_toggle(state, &merchant_id, &profile_id, req), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::MerchantConnectorsList))] pub async fn payment_connector_list_profile( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::MerchantId>, ) -> HttpResponse { let flow = Flow::MerchantConnectorsList; let merchant_id = path.into_inner(); api::server_wrap( flow, state, &req, merchant_id.to_owned(), |state, auth, merchant_id, _| { list_payment_connectors( state, merchant_id, auth.profile_id.map(|profile_id| vec![profile_id]), ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: permissions::Permission::ProfileConnectorRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, ) .await }
crates/router/src/routes/profiles.rs
router::src::routes::profiles
3,335
true
// File: crates/router/src/routes/process_tracker.rs // Module: router::src::routes::process_tracker #[cfg(feature = "v2")] pub mod revenue_recovery;
crates/router/src/routes/process_tracker.rs
router::src::routes::process_tracker
36
true
// File: crates/router/src/routes/verify_connector.rs // Module: router::src::routes::verify_connector use actix_web::{web, HttpRequest, HttpResponse}; use api_models::verify_connector::VerifyConnectorRequest; use router_env::{instrument, tracing, Flow}; use super::AppState; use crate::{ core::{api_locking, verify_connector}, services::{self, authentication as auth, authorization::permissions::Permission}, }; #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::VerifyPaymentConnector))] pub async fn payment_connector_verify( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<VerifyConnectorRequest>, ) -> HttpResponse { let flow = Flow::VerifyPaymentConnector; Box::pin(services::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, req, _| { verify_connector::verify_connector_credentials(state, req, auth.profile_id) }, &auth::JWTAuth { permission: Permission::MerchantConnectorWrite, }, api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/verify_connector.rs
router::src::routes::verify_connector
255
true
// File: crates/router/src/routes/payment_link.rs // Module: router::src::routes::payment_link use actix_web::{web, Responder}; use router_env::{instrument, tracing, Flow}; use crate::{ core::{api_locking, payment_link::*}, services::{api, authentication as auth}, types::domain, AppState, }; /// Payments Link - Retrieve /// /// To retrieve the properties of a Payment Link. This may be used to get the status of a previously initiated payment or next action for an ongoing payment #[instrument(skip(state, req), fields(flow = ?Flow::PaymentLinkRetrieve))] pub async fn payment_link_retrieve( state: web::Data<AppState>, req: actix_web::HttpRequest, path: web::Path<String>, json_payload: web::Query<api_models::payments::RetrievePaymentLinkRequest>, ) -> impl Responder { let flow = Flow::PaymentLinkRetrieve; let payload = json_payload.into_inner(); let api_auth = auth::ApiKeyAuth::default(); let (auth_type, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(error_stack::report!(err)), }; api::server_wrap( flow, state, &req, payload.clone(), |state, _auth, _, _| retrieve_payment_link(state, path.clone()), &*auth_type, api_locking::LockAction::NotApplicable, ) .await } pub async fn initiate_payment_link( state: web::Data<AppState>, req: actix_web::HttpRequest, path: web::Path<( common_utils::id_type::MerchantId, common_utils::id_type::PaymentId, )>, ) -> impl Responder { let flow = Flow::PaymentLinkInitiate; let (merchant_id, payment_id) = path.into_inner(); let payload = api_models::payments::PaymentLinkInitiateRequest { payment_id, merchant_id: merchant_id.clone(), }; Box::pin(api::server_wrap( flow, state, &req, payload.clone(), |state, auth: auth::AuthenticationData, _, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); initiate_payment_link_flow( state, merchant_context, payload.merchant_id.clone(), payload.payment_id.clone(), ) }, &crate::services::authentication::MerchantIdAuth(merchant_id), api_locking::LockAction::NotApplicable, )) .await } pub async fn initiate_secure_payment_link( state: web::Data<AppState>, req: actix_web::HttpRequest, path: web::Path<( common_utils::id_type::MerchantId, common_utils::id_type::PaymentId, )>, ) -> impl Responder { let flow = Flow::PaymentSecureLinkInitiate; let (merchant_id, payment_id) = path.into_inner(); let payload = api_models::payments::PaymentLinkInitiateRequest { payment_id, merchant_id: merchant_id.clone(), }; let headers = req.headers(); Box::pin(api::server_wrap( flow, state, &req, payload.clone(), |state, auth: auth::AuthenticationData, _, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); initiate_secure_payment_link_flow( state, merchant_context, payload.merchant_id.clone(), payload.payment_id.clone(), headers, ) }, &crate::services::authentication::MerchantIdAuth(merchant_id), api_locking::LockAction::NotApplicable, )) .await } /// Payment Link - List /// /// To list the payment links #[instrument(skip_all, fields(flow = ?Flow::PaymentLinkList))] pub async fn payments_link_list( state: web::Data<AppState>, req: actix_web::HttpRequest, payload: web::Query<api_models::payments::PaymentLinkListConstraints>, ) -> impl Responder { let flow = Flow::PaymentLinkList; let payload = payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, payload, _| { list_payment_link(state, auth.merchant_account, payload) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), api_locking::LockAction::NotApplicable, )) .await } pub async fn payment_link_status( state: web::Data<AppState>, req: actix_web::HttpRequest, path: web::Path<( common_utils::id_type::MerchantId, common_utils::id_type::PaymentId, )>, ) -> impl Responder { let flow = Flow::PaymentLinkStatus; let (merchant_id, payment_id) = path.into_inner(); let payload = api_models::payments::PaymentLinkInitiateRequest { payment_id, merchant_id: merchant_id.clone(), }; Box::pin(api::server_wrap( flow, state, &req, payload.clone(), |state, auth: auth::AuthenticationData, _, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); get_payment_link_status( state, merchant_context, payload.merchant_id.clone(), payload.payment_id.clone(), ) }, &crate::services::authentication::MerchantIdAuth(merchant_id), api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/payment_link.rs
router::src::routes::payment_link
1,287
true
// File: crates/router/src/routes/revenue_recovery_redis.rs // Module: router::src::routes::revenue_recovery_redis use actix_web::{web, HttpRequest, HttpResponse}; use api_models::revenue_recovery_data_backfill::GetRedisDataQuery; use router_env::{instrument, tracing, Flow}; use crate::{ core::{api_locking, revenue_recovery_data_backfill}, routes::AppState, services::{api, authentication as auth}, }; #[instrument(skip_all, fields(flow = ?Flow::RevenueRecoveryRedis))] pub async fn get_revenue_recovery_redis_data( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, query: web::Query<GetRedisDataQuery>, ) -> HttpResponse { let flow = Flow::RevenueRecoveryRedis; let connector_customer_id = path.into_inner(); let key_type = &query.key_type; Box::pin(api::server_wrap( flow, state, &req, (), |state, _: (), _, _| { revenue_recovery_data_backfill::get_redis_data(state, &connector_customer_id, key_type) }, &auth::V2AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/revenue_recovery_redis.rs
router::src::routes::revenue_recovery_redis
271
true
// File: crates/router/src/routes/recon.rs // Module: router::src::routes::recon use actix_web::{web, HttpRequest, HttpResponse}; use api_models::recon as recon_api; use router_env::Flow; use super::AppState; use crate::{ core::{api_locking, recon}, services::{api, authentication, authorization::permissions::Permission}, }; pub async fn update_merchant( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::MerchantId>, json_payload: web::Json<recon_api::ReconUpdateMerchantRequest>, ) -> HttpResponse { let flow = Flow::ReconMerchantUpdate; let merchant_id = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth, req, _| recon::recon_merchant_account_update(state, auth, req), &authentication::AdminApiAuthWithMerchantIdFromRoute(merchant_id), api_locking::LockAction::NotApplicable, )) .await } pub async fn request_for_recon(state: web::Data<AppState>, http_req: HttpRequest) -> HttpResponse { let flow = Flow::ReconServiceRequest; Box::pin(api::server_wrap( flow, state, &http_req, (), |state, user, _, _| recon::send_recon_request(state, user), &authentication::JWTAuth { permission: Permission::MerchantAccountWrite, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn get_recon_token(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { let flow = Flow::ReconTokenRequest; Box::pin(api::server_wrap( flow, state, &req, (), |state, user, _, _| recon::generate_recon_token(state, user), &authentication::JWTAuth { permission: Permission::MerchantReconTokenRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "recon")] pub async fn verify_recon_token(state: web::Data<AppState>, http_req: HttpRequest) -> HttpResponse { let flow = Flow::ReconVerifyToken; Box::pin(api::server_wrap( flow, state.clone(), &http_req, (), |state, user, _req, _| recon::verify_recon_token(state, user), &authentication::JWTAuth { permission: Permission::MerchantReconTokenRead, }, api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/recon.rs
router::src::routes::recon
589
true
// File: crates/router/src/routes/poll.rs // Module: router::src::routes::poll use actix_web::{web, HttpRequest, HttpResponse}; use router_env::{instrument, tracing, Flow}; use super::app::AppState; use crate::{ core::{api_locking, poll}, services::{api, authentication as auth}, types::{api::PollId, domain}, }; #[cfg(feature = "v1")] /// Poll - Retrieve Poll Status #[utoipa::path( get, path = "/poll/status/{poll_id}", params( ("poll_id" = String, Path, description = "The identifier for poll") ), responses( (status = 200, description = "The poll status was retrieved successfully", body = PollResponse), (status = 404, description = "Poll not found") ), tag = "Poll", operation_id = "Retrieve Poll Status", security(("publishable_key" = [])) )] #[instrument(skip_all, fields(flow = ?Flow::RetrievePollStatus))] pub async fn retrieve_poll_status( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, ) -> HttpResponse { let flow = Flow::RetrievePollStatus; let poll_id = PollId { poll_id: path.into_inner(), }; Box::pin(api::server_wrap( flow, state, &req, poll_id, |state, auth, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); poll::retrieve_poll_status(state, req, merchant_context) }, &auth::HeaderAuth(auth::PublishableKeyAuth), api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/poll.rs
router::src::routes::poll
397
true
// File: crates/router/src/routes/webhooks.rs // Module: router::src::routes::webhooks use actix_web::{web, HttpRequest, Responder}; use router_env::{instrument, tracing, Flow}; use super::app::AppState; use crate::{ core::{ api_locking, webhooks::{self, types}, }, services::{api, authentication as auth}, types::domain, }; #[instrument(skip_all, fields(flow = ?Flow::IncomingWebhookReceive))] #[cfg(feature = "v1")] pub async fn receive_incoming_webhook<W: types::OutgoingWebhookType>( state: web::Data<AppState>, req: HttpRequest, body: web::Bytes, path: web::Path<(common_utils::id_type::MerchantId, String)>, ) -> impl Responder { let flow = Flow::IncomingWebhookReceive; let (merchant_id, connector_id_or_name) = path.into_inner(); Box::pin(api::server_wrap( flow.clone(), state, &req, (), |state, auth, _, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); webhooks::incoming_webhooks_wrapper::<W>( &flow, state.to_owned(), req_state, &req, merchant_context, &connector_id_or_name, body.clone(), false, ) }, &auth::MerchantIdAuth(merchant_id), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::IncomingRelayWebhookReceive))] pub async fn receive_incoming_relay_webhook<W: types::OutgoingWebhookType>( state: web::Data<AppState>, req: HttpRequest, body: web::Bytes, path: web::Path<( common_utils::id_type::MerchantId, common_utils::id_type::MerchantConnectorAccountId, )>, ) -> impl Responder { let flow = Flow::IncomingWebhookReceive; let (merchant_id, connector_id) = path.into_inner(); let is_relay_webhook = true; Box::pin(api::server_wrap( flow.clone(), state, &req, (), |state, auth, _, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); webhooks::incoming_webhooks_wrapper::<W>( &flow, state.to_owned(), req_state, &req, merchant_context, connector_id.get_string_repr(), body.clone(), is_relay_webhook, ) }, &auth::MerchantIdAuth(merchant_id), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::IncomingRelayWebhookReceive))] pub async fn receive_incoming_relay_webhook<W: types::OutgoingWebhookType>( state: web::Data<AppState>, req: HttpRequest, body: web::Bytes, path: web::Path<( common_utils::id_type::MerchantId, common_utils::id_type::ProfileId, common_utils::id_type::MerchantConnectorAccountId, )>, ) -> impl Responder { let flow = Flow::IncomingWebhookReceive; let (merchant_id, profile_id, connector_id) = path.into_inner(); let is_relay_webhook = true; Box::pin(api::server_wrap( flow.clone(), state, &req, (), |state, auth, _, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); webhooks::incoming_webhooks_wrapper::<W>( &flow, state.to_owned(), req_state, &req, merchant_context, auth.profile, &connector_id, body.clone(), is_relay_webhook, ) }, &auth::MerchantIdAndProfileIdAuth { merchant_id, profile_id, }, api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::IncomingWebhookReceive))] #[cfg(feature = "v2")] pub async fn receive_incoming_webhook<W: types::OutgoingWebhookType>( state: web::Data<AppState>, req: HttpRequest, body: web::Bytes, path: web::Path<( common_utils::id_type::MerchantId, common_utils::id_type::ProfileId, common_utils::id_type::MerchantConnectorAccountId, )>, ) -> impl Responder { let flow = Flow::IncomingWebhookReceive; let (merchant_id, profile_id, connector_id) = path.into_inner(); Box::pin(api::server_wrap( flow.clone(), state, &req, (), |state, auth, _, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); webhooks::incoming_webhooks_wrapper::<W>( &flow, state.to_owned(), req_state, &req, merchant_context, auth.profile, &connector_id, body.clone(), false, ) }, &auth::MerchantIdAndProfileIdAuth { merchant_id, profile_id, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::IncomingNetworkTokenWebhookReceive))] pub async fn receive_network_token_requestor_incoming_webhook<W: types::OutgoingWebhookType>( state: web::Data<AppState>, req: HttpRequest, body: web::Bytes, _path: web::Path<String>, ) -> impl Responder { let flow = Flow::IncomingNetworkTokenWebhookReceive; Box::pin(api::server_wrap( flow.clone(), state, &req, (), |state, _: (), _, _| { webhooks::network_token_incoming_webhooks_wrapper::<W>( &flow, state.to_owned(), &req, body.clone(), ) }, &auth::NoAuth, api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/webhooks.rs
router::src::routes::webhooks
1,432
true
// File: crates/router/src/routes/api_keys.rs // Module: router::src::routes::api_keys use actix_web::{web, HttpRequest, Responder}; use router_env::{instrument, tracing, Flow}; use super::app::AppState; use crate::{ core::{api_keys, api_locking}, services::{api, authentication as auth, authorization::permissions::Permission}, types::api as api_types, }; #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::ApiKeyCreate))] pub async fn api_key_create( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::MerchantId>, json_payload: web::Json<api_types::CreateApiKeyRequest>, ) -> impl Responder { let flow = Flow::ApiKeyCreate; let payload = json_payload.into_inner(); let merchant_id = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth_data, payload, _| async { api_keys::create_api_key(state, payload, auth_data.key_store).await }, auth::auth_type( &auth::PlatformOrgAdminAuthWithMerchantIdFromRoute { merchant_id_from_route: merchant_id.clone(), is_admin_auth_allowed: true, }, &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::MerchantApiKeyWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::ApiKeyCreate))] pub async fn api_key_create( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<api_types::CreateApiKeyRequest>, ) -> impl Responder { let flow = Flow::ApiKeyCreate; let payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth::AuthenticationDataWithoutProfile { key_store, .. }, payload, _| async { api_keys::create_api_key(state, payload, key_store).await }, auth::auth_type( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromHeader { required_permission: Permission::MerchantApiKeyWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::ApiKeyRetrieve))] pub async fn api_key_retrieve( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::ApiKeyId>, ) -> impl Responder { let flow = Flow::ApiKeyRetrieve; let key_id = path.into_inner(); api::server_wrap( flow, state, &req, &key_id, |state, auth::AuthenticationDataWithoutProfile { merchant_account, .. }, key_id, _| { api_keys::retrieve_api_key( state, merchant_account.get_id().to_owned(), key_id.to_owned(), ) }, auth::auth_type( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromHeader { required_permission: Permission::MerchantApiKeyRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, ) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::ApiKeyRetrieve))] pub async fn api_key_retrieve( state: web::Data<AppState>, req: HttpRequest, path: web::Path<( common_utils::id_type::MerchantId, common_utils::id_type::ApiKeyId, )>, ) -> impl Responder { let flow = Flow::ApiKeyRetrieve; let (merchant_id, key_id) = path.into_inner(); api::server_wrap( flow, state, &req, (merchant_id.clone(), key_id.clone()), |state, _, (merchant_id, key_id), _| api_keys::retrieve_api_key(state, merchant_id, key_id), auth::auth_type( &auth::PlatformOrgAdminAuthWithMerchantIdFromRoute { merchant_id_from_route: merchant_id.clone(), is_admin_auth_allowed: true, }, &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::MerchantApiKeyRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, ) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::ApiKeyUpdate))] pub async fn api_key_update( state: web::Data<AppState>, req: HttpRequest, path: web::Path<( common_utils::id_type::MerchantId, common_utils::id_type::ApiKeyId, )>, json_payload: web::Json<api_types::UpdateApiKeyRequest>, ) -> impl Responder { let flow = Flow::ApiKeyUpdate; let (merchant_id, key_id) = path.into_inner(); let mut payload = json_payload.into_inner(); payload.key_id = key_id; payload.merchant_id.clone_from(&merchant_id); Box::pin(api::server_wrap( flow, state, &req, payload, |state, _, payload, _| api_keys::update_api_key(state, payload), auth::auth_type( &auth::PlatformOrgAdminAuthWithMerchantIdFromRoute { merchant_id_from_route: merchant_id.clone(), is_admin_auth_allowed: true, }, &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::MerchantApiKeyWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] pub async fn api_key_update( state: web::Data<AppState>, req: HttpRequest, key_id: web::Path<common_utils::id_type::ApiKeyId>, json_payload: web::Json<api_types::UpdateApiKeyRequest>, ) -> impl Responder { let flow = Flow::ApiKeyUpdate; let api_key_id = key_id.into_inner(); let mut payload = json_payload.into_inner(); payload.key_id = api_key_id; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth::AuthenticationDataWithoutProfile { merchant_account, .. }, mut payload, _| { payload.merchant_id = merchant_account.get_id().to_owned(); api_keys::update_api_key(state, payload) }, auth::auth_type( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromHeader { required_permission: Permission::MerchantApiKeyRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::ApiKeyRevoke))] pub async fn api_key_revoke( state: web::Data<AppState>, req: HttpRequest, path: web::Path<( common_utils::id_type::MerchantId, common_utils::id_type::ApiKeyId, )>, ) -> impl Responder { let flow = Flow::ApiKeyRevoke; let (merchant_id, key_id) = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, (&merchant_id, &key_id), |state, _, (merchant_id, key_id), _| { api_keys::revoke_api_key(state, merchant_id.clone(), key_id) }, auth::auth_type( &auth::PlatformOrgAdminAuthWithMerchantIdFromRoute { merchant_id_from_route: merchant_id.clone(), is_admin_auth_allowed: true, }, &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::MerchantApiKeyWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::ApiKeyRevoke))] pub async fn api_key_revoke( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::ApiKeyId>, ) -> impl Responder { let flow = Flow::ApiKeyRevoke; let key_id = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, &key_id, |state, auth::AuthenticationDataWithoutProfile { merchant_account, .. }, key_id, _| api_keys::revoke_api_key(state, merchant_account.get_id().to_owned(), key_id), auth::auth_type( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromHeader { required_permission: Permission::MerchantApiKeyWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::ApiKeyList))] pub async fn api_key_list( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::MerchantId>, query: web::Query<api_types::ListApiKeyConstraints>, ) -> impl Responder { let flow = Flow::ApiKeyList; let list_api_key_constraints = query.into_inner(); let limit = list_api_key_constraints.limit; let offset = list_api_key_constraints.skip; let merchant_id = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, (limit, offset, merchant_id.clone()), |state, _, (limit, offset, merchant_id), _| async move { api_keys::list_api_keys(state, merchant_id, limit, offset).await }, auth::auth_type( &auth::PlatformOrgAdminAuthWithMerchantIdFromRoute { merchant_id_from_route: merchant_id.clone(), is_admin_auth_allowed: true, }, &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::MerchantApiKeyRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::ApiKeyList))] pub async fn api_key_list( state: web::Data<AppState>, req: HttpRequest, query: web::Query<api_types::ListApiKeyConstraints>, ) -> impl Responder { let flow = Flow::ApiKeyList; let payload = query.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth::AuthenticationDataWithoutProfile { merchant_account, .. }, payload, _| async move { let merchant_id = merchant_account.get_id().to_owned(); api_keys::list_api_keys(state, merchant_id, payload.limit, payload.skip).await }, auth::auth_type( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromHeader { required_permission: Permission::MerchantApiKeyRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/api_keys.rs
router::src::routes::api_keys
2,556
true
// File: crates/router/src/routes/customers.rs // Module: router::src::routes::customers use actix_web::{web, HttpRequest, HttpResponse, Responder}; use common_utils::id_type; use router_env::{instrument, tracing, Flow}; use super::app::AppState; use crate::{ core::{api_locking, customers::*}, services::{api, authentication as auth, authorization::permissions::Permission}, types::{api::customers, domain}, }; #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::CustomersCreate))] pub async fn customers_create( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<customers::CustomerRequest>, ) -> HttpResponse { let flow = Flow::CustomersCreate; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); create_customer(state, merchant_context, req, None) }, auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::MerchantCustomerWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::CustomersCreate))] pub async fn customers_create( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<customers::CustomerRequest>, ) -> HttpResponse { let flow = Flow::CustomersCreate; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); create_customer(state, merchant_context, req, None) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantCustomerWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::CustomersRetrieve))] pub async fn customers_retrieve( state: web::Data<AppState>, req: HttpRequest, path: web::Path<id_type::CustomerId>, ) -> HttpResponse { let flow = Flow::CustomersRetrieve; let customer_id = path.into_inner(); let auth = if auth::is_jwt_auth(req.headers()) { Box::new(auth::JWTAuth { permission: Permission::MerchantCustomerRead, }) } else { let api_auth = auth::ApiKeyAuth::default(); match auth::is_ephemeral_auth(req.headers(), api_auth) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(err), } }; Box::pin(api::server_wrap( flow, state, &req, customer_id, |state, auth: auth::AuthenticationData, customer_id, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); retrieve_customer(state, merchant_context, auth.profile_id, customer_id) }, &*auth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::CustomersRetrieve))] pub async fn customers_retrieve( state: web::Data<AppState>, req: HttpRequest, path: web::Path<id_type::GlobalCustomerId>, ) -> HttpResponse { use crate::services::authentication::api_or_client_auth; let flow = Flow::CustomersRetrieve; let id = path.into_inner(); let v2_client_auth = auth::V2ClientAuth( common_utils::types::authentication::ResourceId::Customer(id.clone()), ); let auth = if auth::is_jwt_auth(req.headers()) { &auth::JWTAuth { permission: Permission::MerchantCustomerRead, } } else { api_or_client_auth( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &v2_client_auth, req.headers(), ) }; Box::pin(api::server_wrap( flow, state, &req, id, |state, auth: auth::AuthenticationData, id, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); retrieve_customer(state, merchant_context, id) }, auth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::CustomersList))] pub async fn customers_list( state: web::Data<AppState>, req: HttpRequest, query: web::Query<customers::CustomerListRequest>, ) -> HttpResponse { let flow = Flow::CustomersList; let payload = query.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, request, _| { list_customers( state, auth.merchant_account.get_id().to_owned(), None, auth.key_store, request, ) }, auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::MerchantCustomerRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::CustomersList))] pub async fn customers_list( state: web::Data<AppState>, req: HttpRequest, query: web::Query<customers::CustomerListRequest>, ) -> HttpResponse { let flow = Flow::CustomersList; let payload = query.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, request, _| { list_customers( state, auth.merchant_account.get_id().to_owned(), None, auth.key_store, request, ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantCustomerRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::CustomersListWithConstraints))] pub async fn customers_list_with_count( state: web::Data<AppState>, req: HttpRequest, query: web::Query<customers::CustomerListRequestWithConstraints>, ) -> HttpResponse { let flow = Flow::CustomersListWithConstraints; let payload = query.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, request, _| { list_customers_with_count( state, auth.merchant_account.get_id().to_owned(), None, auth.key_store, request, ) }, auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::MerchantCustomerRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::CustomersListWithConstraints))] pub async fn customers_list_with_count( state: web::Data<AppState>, req: HttpRequest, query: web::Query<customers::CustomerListRequestWithConstraints>, ) -> HttpResponse { let flow = Flow::CustomersListWithConstraints; let payload = query.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, request, _| { list_customers_with_count( state, auth.merchant_account.get_id().to_owned(), None, auth.key_store, request, ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantCustomerRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::CustomersUpdate))] pub async fn customers_update( state: web::Data<AppState>, req: HttpRequest, path: web::Path<id_type::CustomerId>, json_payload: web::Json<customers::CustomerUpdateRequest>, ) -> HttpResponse { let flow = Flow::CustomersUpdate; let customer_id = path.into_inner(); let request = json_payload.into_inner(); let request_internal = customers::CustomerUpdateRequestInternal { customer_id, request, }; Box::pin(api::server_wrap( flow, state, &req, request_internal, |state, auth: auth::AuthenticationData, request_internal, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); update_customer(state, merchant_context, request_internal) }, auth::auth_type( &auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::MerchantCustomerWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::CustomersUpdate))] pub async fn customers_update( state: web::Data<AppState>, req: HttpRequest, path: web::Path<id_type::GlobalCustomerId>, json_payload: web::Json<customers::CustomerUpdateRequest>, ) -> HttpResponse { let flow = Flow::CustomersUpdate; let id = path.into_inner(); let request = json_payload.into_inner(); let request_internal = customers::CustomerUpdateRequestInternal { id, request }; Box::pin(api::server_wrap( flow, state, &req, request_internal, |state, auth: auth::AuthenticationData, request_internal, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); update_customer(state, merchant_context, request_internal) }, auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::MerchantCustomerWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::CustomersDelete))] pub async fn customers_delete( state: web::Data<AppState>, req: HttpRequest, path: web::Path<id_type::GlobalCustomerId>, ) -> impl Responder { let flow = Flow::CustomersDelete; let id = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, id, |state, auth: auth::AuthenticationData, id, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); delete_customer(state, merchant_context, id) }, auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::MerchantCustomerWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::CustomersDelete))] pub async fn customers_delete( state: web::Data<AppState>, req: HttpRequest, path: web::Path<id_type::CustomerId>, ) -> impl Responder { let flow = Flow::CustomersDelete; let customer_id = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, customer_id, |state, auth: auth::AuthenticationData, customer_id, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); delete_customer(state, merchant_context, customer_id) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantCustomerWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::CustomersGetMandates))] pub async fn get_customer_mandates( state: web::Data<AppState>, req: HttpRequest, path: web::Path<id_type::CustomerId>, ) -> impl Responder { let flow = Flow::CustomersGetMandates; let customer_id = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, customer_id, |state, auth: auth::AuthenticationData, customer_id, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); crate::core::mandate::get_customer_mandates(state, merchant_context, customer_id) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantMandateRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/customers.rs
router::src::routes::customers
3,320
true
// File: crates/router/src/routes/gsm.rs // Module: router::src::routes::gsm use actix_web::{web, HttpRequest, Responder}; use api_models::gsm as gsm_api_types; use router_env::{instrument, tracing, Flow}; use super::app::AppState; use crate::{ core::{api_locking, gsm}, services::{api, authentication as auth}, }; #[cfg(feature = "v1")] const ADMIN_API_AUTH: auth::AdminApiAuth = auth::AdminApiAuth; #[cfg(feature = "v2")] const ADMIN_API_AUTH: auth::V2AdminApiAuth = auth::V2AdminApiAuth; /// Gsm - Create /// /// To create a Gsm Rule #[utoipa::path( post, path = "/gsm", request_body( content = GsmCreateRequest, ), responses( (status = 200, description = "Gsm created", body = GsmResponse), (status = 400, description = "Missing Mandatory fields") ), tag = "Gsm", operation_id = "Create Gsm Rule", security(("admin_api_key" = [])), )] #[instrument(skip_all, fields(flow = ?Flow::GsmRuleCreate))] pub async fn create_gsm_rule( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<gsm_api_types::GsmCreateRequest>, ) -> impl Responder { let payload = json_payload.into_inner(); let flow = Flow::GsmRuleCreate; Box::pin(api::server_wrap( flow, state.clone(), &req, payload, |state, _, payload, _| gsm::create_gsm_rule(state, payload), &ADMIN_API_AUTH, api_locking::LockAction::NotApplicable, )) .await } /// Gsm - Get /// /// To get a Gsm Rule #[utoipa::path( post, path = "/gsm/get", request_body( content = GsmRetrieveRequest, ), responses( (status = 200, description = "Gsm retrieved", body = GsmResponse), (status = 400, description = "Missing Mandatory fields") ), tag = "Gsm", operation_id = "Retrieve Gsm Rule", security(("admin_api_key" = [])), )] #[instrument(skip_all, fields(flow = ?Flow::GsmRuleRetrieve))] pub async fn get_gsm_rule( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<gsm_api_types::GsmRetrieveRequest>, ) -> impl Responder { let gsm_retrieve_req = json_payload.into_inner(); let flow = Flow::GsmRuleRetrieve; Box::pin(api::server_wrap( flow, state.clone(), &req, gsm_retrieve_req, |state, _, gsm_retrieve_req, _| gsm::retrieve_gsm_rule(state, gsm_retrieve_req), &ADMIN_API_AUTH, api_locking::LockAction::NotApplicable, )) .await } /// Gsm - Update /// /// To update a Gsm Rule #[utoipa::path( post, path = "/gsm/update", request_body( content = GsmUpdateRequest, ), responses( (status = 200, description = "Gsm updated", body = GsmResponse), (status = 400, description = "Missing Mandatory fields") ), tag = "Gsm", operation_id = "Update Gsm Rule", security(("admin_api_key" = [])), )] #[instrument(skip_all, fields(flow = ?Flow::GsmRuleUpdate))] pub async fn update_gsm_rule( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<gsm_api_types::GsmUpdateRequest>, ) -> impl Responder { let payload = json_payload.into_inner(); let flow = Flow::GsmRuleUpdate; Box::pin(api::server_wrap( flow, state.clone(), &req, payload, |state, _, payload, _| gsm::update_gsm_rule(state, payload), &ADMIN_API_AUTH, api_locking::LockAction::NotApplicable, )) .await } /// Gsm - Delete /// /// To delete a Gsm Rule #[utoipa::path( post, path = "/gsm/delete", request_body( content = GsmDeleteRequest, ), responses( (status = 200, description = "Gsm deleted", body = GsmDeleteResponse), (status = 400, description = "Missing Mandatory fields") ), tag = "Gsm", operation_id = "Delete Gsm Rule", security(("admin_api_key" = [])), )] #[instrument(skip_all, fields(flow = ?Flow::GsmRuleDelete))] pub async fn delete_gsm_rule( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<gsm_api_types::GsmDeleteRequest>, ) -> impl Responder { let payload = json_payload.into_inner(); let flow = Flow::GsmRuleDelete; Box::pin(api::server_wrap( flow, state, &req, payload, |state, _, payload, _| gsm::delete_gsm_rule(state, payload), &ADMIN_API_AUTH, api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/gsm.rs
router::src::routes::gsm
1,216
true
// File: crates/router/src/routes/currency.rs // Module: router::src::routes::currency use actix_web::{web, HttpRequest, HttpResponse}; use router_env::Flow; use crate::{ core::{api_locking, currency}, routes::AppState, services::{api, authentication as auth}, }; #[cfg(feature = "v1")] pub async fn retrieve_forex(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { let flow = Flow::RetrieveForexFlow; Box::pin(api::server_wrap( flow, state, &req, (), |state, _auth: auth::AuthenticationData, _, _| currency::retrieve_forex(state), auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::DashboardNoPermissionAuth, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] pub async fn convert_forex( state: web::Data<AppState>, req: HttpRequest, params: web::Query<api_models::currency::CurrencyConversionParams>, ) -> HttpResponse { let flow = Flow::RetrieveForexFlow; let amount = params.amount; let to_currency = &params.to_currency; let from_currency = &params.from_currency; Box::pin(api::server_wrap( flow, state.clone(), &req, (), |state, _: auth::AuthenticationData, _, _| { currency::convert_forex( state, amount.get_amount_as_i64(), to_currency.to_string(), from_currency.to_string(), ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::DashboardNoPermissionAuth, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/currency.rs
router::src::routes::currency
439
true
// File: crates/router/src/routes/profile_acquirer.rs // Module: router::src::routes::profile_acquirer use actix_web::{web, HttpRequest, HttpResponse}; use api_models::profile_acquirer::{ProfileAcquirerCreate, ProfileAcquirerUpdate}; use router_env::{instrument, tracing, Flow}; use super::app::AppState; use crate::{ core::api_locking, services::{api, authentication as auth, authorization::permissions::Permission}, types::domain, }; #[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all, fields(flow = ?Flow::ProfileAcquirerCreate))] pub async fn create_profile_acquirer( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<ProfileAcquirerCreate>, ) -> HttpResponse { let flow = Flow::ProfileAcquirerCreate; let payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state: super::SessionState, auth_data, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth_data.merchant_account, auth_data.key_store), )); crate::core::profile_acquirer::create_profile_acquirer( state, req, merchant_context.clone(), ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: true, }), &auth::JWTAuth { permission: Permission::ProfileAccountWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all, fields(flow = ?Flow::ProfileAcquirerUpdate))] pub async fn profile_acquirer_update( state: web::Data<AppState>, req: HttpRequest, path: web::Path<( common_utils::id_type::ProfileId, common_utils::id_type::ProfileAcquirerId, )>, json_payload: web::Json<ProfileAcquirerUpdate>, ) -> HttpResponse { let flow = Flow::ProfileAcquirerUpdate; let (profile_id, profile_acquirer_id) = path.into_inner(); let payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state: super::SessionState, auth_data, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth_data.merchant_account, auth_data.key_store), )); crate::core::profile_acquirer::update_profile_acquirer_config( state, profile_id.clone(), profile_acquirer_id.clone(), req, merchant_context.clone(), ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: true, }), &auth::JWTAuth { permission: Permission::ProfileAccountWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/profile_acquirer.rs
router::src::routes::profile_acquirer
698
true
// File: crates/router/src/routes/authentication.rs // Module: router::src::routes::authentication use actix_web::{web, HttpRequest, Responder}; use api_models::authentication::{AuthenticationAuthenticateRequest, AuthenticationCreateRequest}; #[cfg(feature = "v1")] use api_models::authentication::{ AuthenticationEligibilityRequest, AuthenticationSyncPostUpdateRequest, AuthenticationSyncRequest, }; use router_env::{instrument, tracing, Flow}; use crate::{ core::{api_locking, unified_authentication_service}, routes::app::{self}, services::{api, authentication as auth}, types::domain, }; #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::AuthenticationCreate))] pub async fn authentication_create( state: web::Data<app::AppState>, req: HttpRequest, json_payload: web::Json<AuthenticationCreateRequest>, ) -> impl Responder { let flow = Flow::AuthenticationCreate; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); unified_authentication_service::authentication_create_core(state, merchant_context, req) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::AuthenticationEligibility))] pub async fn authentication_eligibility( state: web::Data<app::AppState>, req: HttpRequest, json_payload: web::Json<AuthenticationEligibilityRequest>, path: web::Path<common_utils::id_type::AuthenticationId>, ) -> impl Responder { let flow = Flow::AuthenticationEligibility; let api_auth = auth::ApiKeyAuth::default(); let payload = json_payload.into_inner(); let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) { Ok((auth, _auth_flow)) => (auth, _auth_flow), Err(e) => return api::log_and_return_error_response(e), }; let authentication_id = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); unified_authentication_service::authentication_eligibility_core( state, merchant_context, req, authentication_id.clone(), ) }, &*auth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::AuthenticationAuthenticate))] pub async fn authentication_authenticate( state: web::Data<app::AppState>, req: HttpRequest, json_payload: web::Json<AuthenticationAuthenticateRequest>, path: web::Path<common_utils::id_type::AuthenticationId>, ) -> impl Responder { let flow = Flow::AuthenticationAuthenticate; let authentication_id = path.into_inner(); let api_auth = auth::ApiKeyAuth::default(); let payload = AuthenticationAuthenticateRequest { authentication_id, ..json_payload.into_inner() }; let (auth, auth_flow) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) { Ok((auth, auth_flow)) => (auth, auth_flow), Err(e) => return api::log_and_return_error_response(e), }; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); unified_authentication_service::authentication_authenticate_core( state, merchant_context, req, auth_flow, ) }, &*auth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::AuthenticationSync))] pub async fn authentication_sync( state: web::Data<app::AppState>, req: HttpRequest, path: web::Path<( common_utils::id_type::MerchantId, common_utils::id_type::AuthenticationId, )>, json_payload: web::Query<AuthenticationSyncRequest>, ) -> impl Responder { let flow = Flow::AuthenticationSync; let api_auth = auth::ApiKeyAuth::default(); let (_merchant_id, authentication_id) = path.into_inner(); let payload = AuthenticationSyncRequest { authentication_id, ..json_payload.into_inner() }; let (auth, auth_flow) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) { Ok((auth, auth_flow)) => (auth, auth_flow), Err(e) => return api::log_and_return_error_response(e), }; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); unified_authentication_service::authentication_sync_core( state, merchant_context, auth_flow, req, ) }, &*auth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::AuthenticationSyncPostUpdate))] pub async fn authentication_sync_post_update( state: web::Data<app::AppState>, req: HttpRequest, path: web::Path<( common_utils::id_type::MerchantId, common_utils::id_type::AuthenticationId, )>, ) -> impl Responder { let flow = Flow::AuthenticationSyncPostUpdate; let (merchant_id, authentication_id) = path.into_inner(); let payload = AuthenticationSyncPostUpdateRequest { authentication_id }; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); unified_authentication_service::authentication_post_sync_core( state, merchant_context, req, ) }, &auth::MerchantIdAuth(merchant_id), api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/authentication.rs
router::src::routes::authentication
1,524
true
// File: crates/router/src/routes/routing.rs // Module: router::src::routes::routing //! Analysis for usage of Routing in Payment flows //! //! Functions that are used to perform the api level configuration, retrieval, updation //! of Routing configs. use actix_web::{web, HttpRequest, Responder}; use api_models::{ enums, routing::{ self as routing_types, RoutingEvaluateRequest, RoutingEvaluateResponse, RoutingRetrieveQuery, }, }; use error_stack::ResultExt; use hyperswitch_domain_models::merchant_context::MerchantKeyStore; use payment_methods::core::errors::ApiErrorResponse; use router_env::{ tracing::{self, instrument}, Flow, }; use crate::{ core::{ api_locking, conditional_config, payments::routing::utils::{DecisionEngineApiHandler, EuclidApiClient}, routing, surcharge_decision_config, }, db::errors::StorageErrorExt, routes::AppState, services, services::{api as oss_api, authentication as auth, authorization::permissions::Permission}, types::domain, }; #[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all)] pub async fn routing_create_config( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<routing_types::RoutingConfigRequest>, transaction_type: Option<enums::TransactionType>, ) -> impl Responder { let flow = Flow::RoutingCreateConfig; Box::pin(oss_api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, payload, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::create_routing_algorithm_under_profile( state, merchant_context, auth.profile_id, payload.clone(), transaction_type .or(payload.transaction_type) .unwrap_or(enums::TransactionType::Payment), ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileRoutingWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v2"))] #[instrument(skip_all)] pub async fn routing_create_config( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<routing_types::RoutingConfigRequest>, transaction_type: enums::TransactionType, ) -> impl Responder { let flow = Flow::RoutingCreateConfig; Box::pin(oss_api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, payload, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::create_routing_algorithm_under_profile( state, merchant_context, Some(auth.profile.get_id().clone()), payload, transaction_type, ) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::ProfileRoutingWrite, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { permission: Permission::ProfileRoutingWrite, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all)] pub async fn routing_link_config( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::RoutingId>, json_payload: web::Json<routing_types::RoutingActivatePayload>, transaction_type: Option<enums::TransactionType>, ) -> impl Responder { let flow = Flow::RoutingLinkConfig; Box::pin(oss_api::server_wrap( flow, state, &req, path.into_inner(), |state, auth: auth::AuthenticationData, algorithm, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::link_routing_config( state, merchant_context, auth.profile_id, algorithm, transaction_type .or(json_payload.transaction_type) .unwrap_or(enums::TransactionType::Payment), ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileRoutingWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v2"))] #[instrument(skip_all)] pub async fn routing_link_config( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::ProfileId>, json_payload: web::Json<routing_types::RoutingAlgorithmId>, transaction_type: &enums::TransactionType, ) -> impl Responder { let flow = Flow::RoutingLinkConfig; let wrapper = routing_types::RoutingLinkWrapper { profile_id: path.into_inner(), algorithm_id: json_payload.into_inner(), }; Box::pin(oss_api::server_wrap( flow, state, &req, wrapper.clone(), |state, auth: auth::AuthenticationData, wrapper, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::link_routing_config_under_profile( state, merchant_context, wrapper.profile_id, wrapper.algorithm_id.routing_algorithm_id, transaction_type, ) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuthProfileFromRoute { profile_id: wrapper.profile_id, required_permission: Permission::MerchantRoutingWrite, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuthProfileFromRoute { profile_id: wrapper.profile_id, required_permission: Permission::MerchantRoutingWrite, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all)] pub async fn routing_retrieve_config( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::RoutingId>, ) -> impl Responder { let algorithm_id = path.into_inner(); let flow = Flow::RoutingRetrieveConfig; Box::pin(oss_api::server_wrap( flow, state, &req, algorithm_id, |state, auth: auth::AuthenticationData, algorithm_id, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::retrieve_routing_algorithm_from_algorithm_id( state, merchant_context, auth.profile_id, algorithm_id, ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileRoutingRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v2"))] #[instrument(skip_all)] pub async fn routing_retrieve_config( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::RoutingId>, ) -> impl Responder { let algorithm_id = path.into_inner(); let flow = Flow::RoutingRetrieveConfig; Box::pin(oss_api::server_wrap( flow, state, &req, algorithm_id, |state, auth: auth::AuthenticationData, algorithm_id, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::retrieve_routing_algorithm_from_algorithm_id( state, merchant_context, Some(auth.profile.get_id().clone()), algorithm_id, ) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::ProfileRoutingRead, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { permission: Permission::ProfileRoutingRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "olap")] #[instrument(skip_all)] pub async fn list_routing_configs( state: web::Data<AppState>, req: HttpRequest, query: web::Query<RoutingRetrieveQuery>, transaction_type: Option<enums::TransactionType>, ) -> impl Responder { let flow = Flow::RoutingRetrieveDictionary; Box::pin(oss_api::server_wrap( flow, state, &req, query.into_inner(), |state, auth: auth::AuthenticationData, query_params, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::retrieve_merchant_routing_dictionary( state, merchant_context, None, query_params.clone(), transaction_type .or(query_params.transaction_type) .unwrap_or(enums::TransactionType::Payment), ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantRoutingRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all)] pub async fn list_routing_configs_for_profile( state: web::Data<AppState>, req: HttpRequest, query: web::Query<RoutingRetrieveQuery>, transaction_type: Option<enums::TransactionType>, ) -> impl Responder { let flow = Flow::RoutingRetrieveDictionary; Box::pin(oss_api::server_wrap( flow, state, &req, query.into_inner(), |state, auth: auth::AuthenticationData, query_params, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::retrieve_merchant_routing_dictionary( state, merchant_context, auth.profile_id.map(|profile_id| vec![profile_id]), query_params.clone(), transaction_type .or(query_params.transaction_type) .unwrap_or(enums::TransactionType::Payment), ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileRoutingRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v2"))] #[instrument(skip_all)] pub async fn routing_unlink_config( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::ProfileId>, transaction_type: &enums::TransactionType, ) -> impl Responder { let flow = Flow::RoutingUnlinkConfig; let path = path.into_inner(); Box::pin(oss_api::server_wrap( flow, state, &req, path.clone(), |state, auth: auth::AuthenticationData, path, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::unlink_routing_config_under_profile( state, merchant_context, path, transaction_type, ) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuthProfileFromRoute { profile_id: path, required_permission: Permission::MerchantRoutingWrite, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuthProfileFromRoute { profile_id: path, required_permission: Permission::MerchantRoutingWrite, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all)] pub async fn routing_unlink_config( state: web::Data<AppState>, req: HttpRequest, payload: web::Json<routing_types::RoutingConfigRequest>, transaction_type: Option<enums::TransactionType>, ) -> impl Responder { let flow = Flow::RoutingUnlinkConfig; Box::pin(oss_api::server_wrap( flow, state, &req, payload.into_inner(), |state, auth: auth::AuthenticationData, payload_req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::unlink_routing_config( state, merchant_context, payload_req.clone(), auth.profile_id, transaction_type .or(payload_req.transaction_type) .unwrap_or(enums::TransactionType::Payment), ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileRoutingWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v2"))] #[instrument(skip_all)] pub async fn routing_update_default_config( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::ProfileId>, json_payload: web::Json<Vec<routing_types::RoutableConnectorChoice>>, ) -> impl Responder { let wrapper = routing_types::ProfileDefaultRoutingConfig { profile_id: path.into_inner(), connectors: json_payload.into_inner(), }; Box::pin(oss_api::server_wrap( Flow::RoutingUpdateDefaultConfig, state, &req, wrapper, |state, auth: auth::AuthenticationData, wrapper, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::update_default_fallback_routing( state, merchant_context, wrapper.profile_id, wrapper.connectors, ) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::MerchantRoutingWrite, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { permission: Permission::MerchantRoutingWrite, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all)] pub async fn routing_update_default_config( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<Vec<routing_types::RoutableConnectorChoice>>, transaction_type: &enums::TransactionType, ) -> impl Responder { Box::pin(oss_api::server_wrap( Flow::RoutingUpdateDefaultConfig, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, updated_config, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::update_default_routing_config( state, merchant_context, updated_config, transaction_type, ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantRoutingWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v2"))] #[instrument(skip_all)] pub async fn routing_retrieve_default_config( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::ProfileId>, ) -> impl Responder { let path = path.into_inner(); Box::pin(oss_api::server_wrap( Flow::RoutingRetrieveDefaultConfig, state, &req, path.clone(), |state, auth: auth::AuthenticationData, profile_id, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::retrieve_default_fallback_algorithm_for_profile( state, merchant_context, profile_id, ) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuthProfileFromRoute { profile_id: path, required_permission: Permission::MerchantRoutingRead, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuthProfileFromRoute { profile_id: path, required_permission: Permission::MerchantRoutingRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all)] pub async fn routing_retrieve_default_config( state: web::Data<AppState>, req: HttpRequest, transaction_type: &enums::TransactionType, ) -> impl Responder { Box::pin(oss_api::server_wrap( Flow::RoutingRetrieveDefaultConfig, state, &req, (), |state, auth: auth::AuthenticationData, _, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::retrieve_default_routing_config( state, auth.profile_id, merchant_context, transaction_type, ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileRoutingRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "olap")] #[instrument(skip_all)] pub async fn upsert_surcharge_decision_manager_config( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<api_models::surcharge_decision_configs::SurchargeDecisionConfigReq>, ) -> impl Responder { let flow = Flow::DecisionManagerUpsertConfig; Box::pin(oss_api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, update_decision, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); surcharge_decision_config::upsert_surcharge_decision_config( state, merchant_context, update_decision, ) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantSurchargeDecisionManagerWrite, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { permission: Permission::MerchantSurchargeDecisionManagerWrite, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "olap")] #[instrument(skip_all)] pub async fn delete_surcharge_decision_manager_config( state: web::Data<AppState>, req: HttpRequest, ) -> impl Responder { let flow = Flow::DecisionManagerDeleteConfig; Box::pin(oss_api::server_wrap( flow, state, &req, (), |state, auth: auth::AuthenticationData, (), _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); surcharge_decision_config::delete_surcharge_decision_config(state, merchant_context) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantSurchargeDecisionManagerWrite, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { permission: Permission::MerchantSurchargeDecisionManagerWrite, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "olap")] #[instrument(skip_all)] pub async fn retrieve_surcharge_decision_manager_config( state: web::Data<AppState>, req: HttpRequest, ) -> impl Responder { let flow = Flow::DecisionManagerRetrieveConfig; Box::pin(oss_api::server_wrap( flow, state, &req, (), |state, auth: auth::AuthenticationData, _, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); surcharge_decision_config::retrieve_surcharge_decision_config(state, merchant_context) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantSurchargeDecisionManagerRead, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { permission: Permission::MerchantSurchargeDecisionManagerRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all)] pub async fn upsert_decision_manager_config( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<api_models::conditional_configs::DecisionManager>, ) -> impl Responder { let flow = Flow::DecisionManagerUpsertConfig; Box::pin(oss_api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, update_decision, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); conditional_config::upsert_conditional_config(state, merchant_context, update_decision) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantThreeDsDecisionManagerWrite, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { permission: Permission::MerchantThreeDsDecisionManagerWrite, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v2"))] #[instrument(skip_all)] pub async fn upsert_decision_manager_config( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<api_models::conditional_configs::DecisionManagerRequest>, ) -> impl Responder { let flow = Flow::DecisionManagerUpsertConfig; Box::pin(oss_api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, update_decision, _| { conditional_config::upsert_conditional_config( state, auth.key_store, update_decision, auth.profile, ) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::ProfileThreeDsDecisionManagerWrite, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { permission: Permission::ProfileThreeDsDecisionManagerWrite, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "olap")] #[instrument(skip_all)] pub async fn delete_decision_manager_config( state: web::Data<AppState>, req: HttpRequest, ) -> impl Responder { let flow = Flow::DecisionManagerDeleteConfig; Box::pin(oss_api::server_wrap( flow, state, &req, (), |state, auth: auth::AuthenticationData, (), _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); conditional_config::delete_conditional_config(state, merchant_context) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantThreeDsDecisionManagerWrite, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { permission: Permission::MerchantThreeDsDecisionManagerWrite, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v2"))] #[cfg(feature = "olap")] #[instrument(skip_all)] pub async fn retrieve_decision_manager_config( state: web::Data<AppState>, req: HttpRequest, ) -> impl Responder { let flow = Flow::DecisionManagerRetrieveConfig; Box::pin(oss_api::server_wrap( flow, state, &req, (), |state, auth: auth::AuthenticationData, _, _| { conditional_config::retrieve_conditional_config(state, auth.key_store, auth.profile) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::ProfileThreeDsDecisionManagerWrite, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { permission: Permission::ProfileThreeDsDecisionManagerWrite, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1"))] #[cfg(feature = "olap")] #[instrument(skip_all)] pub async fn retrieve_decision_manager_config( state: web::Data<AppState>, req: HttpRequest, ) -> impl Responder { let flow = Flow::DecisionManagerRetrieveConfig; Box::pin(oss_api::server_wrap( flow, state, &req, (), |state, auth: auth::AuthenticationData, _, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); conditional_config::retrieve_conditional_config(state, merchant_context) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantThreeDsDecisionManagerRead, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { permission: Permission::MerchantThreeDsDecisionManagerRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all)] pub async fn routing_retrieve_linked_config( state: web::Data<AppState>, req: HttpRequest, query: web::Query<routing_types::RoutingRetrieveLinkQuery>, transaction_type: Option<enums::TransactionType>, ) -> impl Responder { use crate::services::authentication::AuthenticationData; let flow = Flow::RoutingRetrieveActiveConfig; let query = query.into_inner(); if let Some(profile_id) = query.profile_id.clone() { Box::pin(oss_api::server_wrap( flow, state, &req, query.clone(), |state, auth: AuthenticationData, query_params, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::retrieve_linked_routing_config( state, merchant_context, auth.profile_id, query_params, transaction_type .or(query.transaction_type) .unwrap_or(enums::TransactionType::Payment), ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuthProfileFromRoute { profile_id, required_permission: Permission::ProfileRoutingRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } else { Box::pin(oss_api::server_wrap( flow, state, &req, query.clone(), |state, auth: AuthenticationData, query_params, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::retrieve_linked_routing_config( state, merchant_context, auth.profile_id, query_params, transaction_type .or(query.transaction_type) .unwrap_or(enums::TransactionType::Payment), ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileRoutingRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } } #[cfg(all(feature = "olap", feature = "v2"))] #[instrument(skip_all)] pub async fn routing_retrieve_linked_config( state: web::Data<AppState>, req: HttpRequest, query: web::Query<RoutingRetrieveQuery>, path: web::Path<common_utils::id_type::ProfileId>, transaction_type: &enums::TransactionType, ) -> impl Responder { use crate::services::authentication::AuthenticationData; let flow = Flow::RoutingRetrieveActiveConfig; let wrapper = routing_types::RoutingRetrieveLinkQueryWrapper { routing_query: query.into_inner(), profile_id: path.into_inner(), }; Box::pin(oss_api::server_wrap( flow, state, &req, wrapper.clone(), |state, auth: AuthenticationData, wrapper, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::retrieve_routing_config_under_profile( state, merchant_context, wrapper.routing_query, wrapper.profile_id, transaction_type, ) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuthProfileFromRoute { profile_id: wrapper.profile_id, required_permission: Permission::ProfileRoutingRead, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuthProfileFromRoute { profile_id: wrapper.profile_id, required_permission: Permission::ProfileRoutingRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "olap")] #[instrument(skip_all)] pub async fn routing_retrieve_default_config_for_profiles( state: web::Data<AppState>, req: HttpRequest, transaction_type: &enums::TransactionType, ) -> impl Responder { Box::pin(oss_api::server_wrap( Flow::RoutingRetrieveDefaultConfig, state, &req, (), |state, auth: auth::AuthenticationData, _, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::retrieve_default_routing_config_for_profiles( state, merchant_context, transaction_type, ) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantRoutingRead, }, req.headers(), ), #[cfg(feature = "release")] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantRoutingRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "olap")] #[instrument(skip_all)] pub async fn routing_update_default_config_for_profile( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::ProfileId>, json_payload: web::Json<Vec<routing_types::RoutableConnectorChoice>>, transaction_type: &enums::TransactionType, ) -> impl Responder { let routing_payload_wrapper = routing_types::RoutingPayloadWrapper { updated_config: json_payload.into_inner(), profile_id: path.into_inner(), }; Box::pin(oss_api::server_wrap( Flow::RoutingUpdateDefaultConfig, state, &req, routing_payload_wrapper.clone(), |state, auth: auth::AuthenticationData, wrapper, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::update_default_routing_config_for_profile( state, merchant_context, wrapper.updated_config, wrapper.profile_id, transaction_type, ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuthProfileFromRoute { profile_id: routing_payload_wrapper.profile_id, required_permission: Permission::ProfileRoutingWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1", feature = "dynamic_routing"))] #[instrument(skip_all)] pub async fn toggle_success_based_routing( state: web::Data<AppState>, req: HttpRequest, query: web::Query<api_models::routing::ToggleDynamicRoutingQuery>, path: web::Path<routing_types::ToggleDynamicRoutingPath>, ) -> impl Responder { let flow = Flow::ToggleDynamicRouting; let wrapper = routing_types::ToggleDynamicRoutingWrapper { feature_to_enable: query.into_inner().enable, profile_id: path.into_inner().profile_id, }; Box::pin(oss_api::server_wrap( flow, state, &req, wrapper.clone(), |state, auth: auth::AuthenticationData, wrapper: routing_types::ToggleDynamicRoutingWrapper, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::toggle_specific_dynamic_routing( state, merchant_context, wrapper.feature_to_enable, wrapper.profile_id, api_models::routing::DynamicRoutingType::SuccessRateBasedRouting, ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuthProfileFromRoute { profile_id: wrapper.profile_id, required_permission: Permission::ProfileRoutingWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1", feature = "dynamic_routing"))] #[instrument(skip_all)] pub async fn create_success_based_routing( state: web::Data<AppState>, req: HttpRequest, query: web::Query<api_models::routing::CreateDynamicRoutingQuery>, path: web::Path<routing_types::ToggleDynamicRoutingPath>, success_based_config: web::Json<routing_types::SuccessBasedRoutingConfig>, ) -> impl Responder { let flow = Flow::CreateDynamicRoutingConfig; let wrapper = routing_types::CreateDynamicRoutingWrapper { feature_to_enable: query.into_inner().enable, profile_id: path.into_inner().profile_id, payload: api_models::routing::DynamicRoutingPayload::SuccessBasedRoutingPayload( success_based_config.into_inner(), ), }; Box::pin(oss_api::server_wrap( flow, state, &req, wrapper.clone(), |state, auth: auth::AuthenticationData, wrapper: routing_types::CreateDynamicRoutingWrapper, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::create_specific_dynamic_routing( state, merchant_context, wrapper.feature_to_enable, wrapper.profile_id, api_models::routing::DynamicRoutingType::SuccessRateBasedRouting, wrapper.payload, ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuthProfileFromRoute { profile_id: wrapper.profile_id, required_permission: Permission::ProfileRoutingWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1", feature = "dynamic_routing"))] #[instrument(skip_all)] pub async fn success_based_routing_update_configs( state: web::Data<AppState>, req: HttpRequest, path: web::Path<routing_types::DynamicRoutingUpdateConfigQuery>, json_payload: web::Json<routing_types::SuccessBasedRoutingConfig>, ) -> impl Responder { let flow = Flow::UpdateDynamicRoutingConfigs; let routing_payload_wrapper = routing_types::SuccessBasedRoutingPayloadWrapper { updated_config: json_payload.into_inner(), algorithm_id: path.clone().algorithm_id, profile_id: path.clone().profile_id, }; Box::pin(oss_api::server_wrap( flow, state, &req, routing_payload_wrapper.clone(), |state, _, wrapper: routing_types::SuccessBasedRoutingPayloadWrapper, _| async { Box::pin(routing::success_based_routing_update_configs( state, wrapper.updated_config, wrapper.algorithm_id, wrapper.profile_id, )) .await }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuthProfileFromRoute { profile_id: routing_payload_wrapper.profile_id, required_permission: Permission::ProfileRoutingWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1", feature = "dynamic_routing"))] #[instrument(skip_all)] pub async fn elimination_routing_update_configs( state: web::Data<AppState>, req: HttpRequest, path: web::Path<routing_types::DynamicRoutingUpdateConfigQuery>, json_payload: web::Json<routing_types::EliminationRoutingConfig>, ) -> impl Responder { let flow = Flow::UpdateDynamicRoutingConfigs; let routing_payload_wrapper = routing_types::EliminationRoutingPayloadWrapper { updated_config: json_payload.into_inner(), algorithm_id: path.clone().algorithm_id, profile_id: path.clone().profile_id, }; Box::pin(oss_api::server_wrap( flow, state, &req, routing_payload_wrapper.clone(), |state, _, wrapper: routing_types::EliminationRoutingPayloadWrapper, _| async { Box::pin(routing::elimination_routing_update_configs( state, wrapper.updated_config, wrapper.algorithm_id, wrapper.profile_id, )) .await }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuthProfileFromRoute { profile_id: routing_payload_wrapper.profile_id, required_permission: Permission::ProfileRoutingWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1", feature = "dynamic_routing"))] #[instrument(skip_all)] pub async fn contract_based_routing_setup_config( state: web::Data<AppState>, req: HttpRequest, path: web::Path<routing_types::ToggleDynamicRoutingPath>, query: web::Query<api_models::routing::ToggleDynamicRoutingQuery>, json_payload: Option<web::Json<routing_types::ContractBasedRoutingConfig>>, ) -> impl Responder { let flow = Flow::ToggleDynamicRouting; let routing_payload_wrapper = routing_types::ContractBasedRoutingSetupPayloadWrapper { config: json_payload.map(|json| json.into_inner()), profile_id: path.into_inner().profile_id, features_to_enable: query.into_inner().enable, }; Box::pin(oss_api::server_wrap( flow, state, &req, routing_payload_wrapper.clone(), |state, auth: auth::AuthenticationData, wrapper: routing_types::ContractBasedRoutingSetupPayloadWrapper, _| async move { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); Box::pin(routing::contract_based_dynamic_routing_setup( state, merchant_context, wrapper.profile_id, wrapper.features_to_enable, wrapper.config, )) .await }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuthProfileFromRoute { profile_id: routing_payload_wrapper.profile_id, required_permission: Permission::ProfileRoutingWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1", feature = "dynamic_routing"))] #[instrument(skip_all)] pub async fn contract_based_routing_update_configs( state: web::Data<AppState>, req: HttpRequest, path: web::Path<routing_types::DynamicRoutingUpdateConfigQuery>, json_payload: web::Json<routing_types::ContractBasedRoutingConfig>, ) -> impl Responder { let flow = Flow::UpdateDynamicRoutingConfigs; let routing_payload_wrapper = routing_types::ContractBasedRoutingPayloadWrapper { updated_config: json_payload.into_inner(), algorithm_id: path.algorithm_id.clone(), profile_id: path.profile_id.clone(), }; Box::pin(oss_api::server_wrap( flow, state, &req, routing_payload_wrapper.clone(), |state, auth: auth::AuthenticationData, wrapper: routing_types::ContractBasedRoutingPayloadWrapper, _| async { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); Box::pin(routing::contract_based_routing_update_configs( state, wrapper.updated_config, merchant_context, wrapper.algorithm_id, wrapper.profile_id, )) .await }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuthProfileFromRoute { profile_id: routing_payload_wrapper.profile_id, required_permission: Permission::ProfileRoutingWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1", feature = "dynamic_routing"))] #[instrument(skip_all)] pub async fn toggle_elimination_routing( state: web::Data<AppState>, req: HttpRequest, query: web::Query<api_models::routing::ToggleDynamicRoutingQuery>, path: web::Path<routing_types::ToggleDynamicRoutingPath>, ) -> impl Responder { let flow = Flow::ToggleDynamicRouting; let wrapper = routing_types::ToggleDynamicRoutingWrapper { feature_to_enable: query.into_inner().enable, profile_id: path.into_inner().profile_id, }; Box::pin(oss_api::server_wrap( flow, state, &req, wrapper.clone(), |state, auth: auth::AuthenticationData, wrapper: routing_types::ToggleDynamicRoutingWrapper, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::toggle_specific_dynamic_routing( state, merchant_context, wrapper.feature_to_enable, wrapper.profile_id, api_models::routing::DynamicRoutingType::EliminationRouting, ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuthProfileFromRoute { profile_id: wrapper.profile_id, required_permission: Permission::ProfileRoutingWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1", feature = "dynamic_routing"))] #[instrument(skip_all)] pub async fn create_elimination_routing( state: web::Data<AppState>, req: HttpRequest, query: web::Query<api_models::routing::CreateDynamicRoutingQuery>, path: web::Path<routing_types::ToggleDynamicRoutingPath>, elimination_config: web::Json<routing_types::EliminationRoutingConfig>, ) -> impl Responder { let flow = Flow::CreateDynamicRoutingConfig; let wrapper = routing_types::CreateDynamicRoutingWrapper { feature_to_enable: query.into_inner().enable, profile_id: path.into_inner().profile_id, payload: api_models::routing::DynamicRoutingPayload::EliminationRoutingPayload( elimination_config.into_inner(), ), }; Box::pin(oss_api::server_wrap( flow, state, &req, wrapper.clone(), |state, auth: auth::AuthenticationData, wrapper: routing_types::CreateDynamicRoutingWrapper, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::create_specific_dynamic_routing( state, merchant_context, wrapper.feature_to_enable, wrapper.profile_id, api_models::routing::DynamicRoutingType::EliminationRouting, wrapper.payload, ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuthProfileFromRoute { profile_id: wrapper.profile_id, required_permission: Permission::ProfileRoutingWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all)] pub async fn set_dynamic_routing_volume_split( state: web::Data<AppState>, req: HttpRequest, query: web::Query<api_models::routing::DynamicRoutingVolumeSplitQuery>, path: web::Path<routing_types::ToggleDynamicRoutingPath>, ) -> impl Responder { let flow = Flow::VolumeSplitOnRoutingType; let routing_info = api_models::routing::RoutingVolumeSplit { routing_type: api_models::routing::RoutingType::Dynamic, split: query.into_inner().split, }; let payload = api_models::routing::RoutingVolumeSplitWrapper { routing_info, profile_id: path.into_inner().profile_id, }; Box::pin(oss_api::server_wrap( flow, state, &req, payload.clone(), |state, auth: auth::AuthenticationData, payload: api_models::routing::RoutingVolumeSplitWrapper, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::configure_dynamic_routing_volume_split( state, merchant_context, payload.profile_id, payload.routing_info, ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuthProfileFromRoute { profile_id: payload.profile_id, required_permission: Permission::ProfileRoutingWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all)] pub async fn get_dynamic_routing_volume_split( state: web::Data<AppState>, req: HttpRequest, path: web::Path<routing_types::ToggleDynamicRoutingPath>, ) -> impl Responder { let flow = Flow::VolumeSplitOnRoutingType; let payload = path.into_inner(); Box::pin(oss_api::server_wrap( flow, state, &req, payload.clone(), |state, auth: auth::AuthenticationData, payload, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::retrieve_dynamic_routing_volume_split( state, merchant_context, payload.profile_id, ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuthProfileFromRoute { profile_id: payload.profile_id, required_permission: Permission::ProfileRoutingRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } const EUCLID_API_TIMEOUT: u64 = 5; #[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all)] pub async fn evaluate_routing_rule( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<RoutingEvaluateRequest>, ) -> impl Responder { let json_payload = json_payload.into_inner(); let flow = Flow::RoutingEvaluateRule; Box::pin(oss_api::server_wrap( flow, state, &req, json_payload.clone(), |state, _auth: auth::AuthenticationData, payload, _| async move { let euclid_response: RoutingEvaluateResponse = EuclidApiClient::send_decision_engine_request( &state, services::Method::Post, "routing/evaluate", Some(payload), Some(EUCLID_API_TIMEOUT), None, ) .await .change_context(ApiErrorResponse::InternalServerError)? .response .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("Failed to evaluate routing rule")?; Ok(services::ApplicationResponse::Json(euclid_response)) }, &auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, api_locking::LockAction::NotApplicable, )) .await } use actix_web::HttpResponse; #[instrument(skip_all, fields(flow = ?Flow::DecisionEngineRuleMigration))] pub async fn migrate_routing_rules_for_profile( state: web::Data<AppState>, req: HttpRequest, query: web::Query<routing_types::RuleMigrationQuery>, ) -> HttpResponse { let flow = Flow::DecisionEngineRuleMigration; Box::pin(oss_api::server_wrap( flow, state, &req, query.into_inner(), |state, _, query_params, _| async move { let merchant_id = query_params.merchant_id.clone(); let (key_store, merchant_account) = get_merchant_account(&state, &merchant_id).await?; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(merchant_account, key_store), )); let res = Box::pin(routing::migrate_rules_for_profile( state, merchant_context, query_params, )) .await?; Ok(services::ApplicationResponse::Json(res)) }, &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } async fn get_merchant_account( state: &super::SessionState, merchant_id: &common_utils::id_type::MerchantId, ) -> common_utils::errors::CustomResult<(MerchantKeyStore, domain::MerchantAccount), ApiErrorResponse> { let key_manager_state = &state.into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .to_not_found_response(ApiErrorResponse::MerchantAccountNotFound)?; let merchant_account = state .store .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store) .await .to_not_found_response(ApiErrorResponse::MerchantAccountNotFound)?; Ok((key_store, merchant_account)) } #[cfg(all(feature = "olap", feature = "v1", feature = "dynamic_routing"))] #[instrument(skip_all)] pub async fn call_decide_gateway_open_router( state: web::Data<AppState>, req: HttpRequest, payload: web::Json<api_models::open_router::OpenRouterDecideGatewayRequest>, ) -> impl Responder { let flow = Flow::DecisionEngineDecideGatewayCall; Box::pin(oss_api::server_wrap( flow, state, &req, payload.clone(), |state, _auth, payload, _| routing::decide_gateway_open_router(state.clone(), payload), &auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1", feature = "dynamic_routing"))] #[instrument(skip_all)] pub async fn call_update_gateway_score_open_router( state: web::Data<AppState>, req: HttpRequest, payload: web::Json<api_models::open_router::UpdateScorePayload>, ) -> impl Responder { let flow = Flow::DecisionEngineGatewayFeedbackCall; Box::pin(oss_api::server_wrap( flow, state, &req, payload.clone(), |state, _auth, payload, _| { routing::update_gateway_score_open_router(state.clone(), payload) }, &auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/routing.rs
router::src::routes::routing
12,608
true
// File: crates/router/src/routes/ephemeral_key.rs // Module: router::src::routes::ephemeral_key use actix_web::{web, HttpRequest, HttpResponse}; use router_env::{instrument, tracing, Flow}; use super::AppState; #[cfg(feature = "v2")] use crate::types::domain; use crate::{ core::{api_locking, payments::helpers}, services::{api, authentication as auth}, }; #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::EphemeralKeyCreate))] pub async fn ephemeral_key_create( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<api_models::ephemeral_key::EphemeralKeyCreateRequest>, ) -> HttpResponse { let flow = Flow::EphemeralKeyCreate; let payload = json_payload.into_inner(); api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, payload, _| { helpers::make_ephemeral_key( state, payload.customer_id, auth.merchant_account.get_id().to_owned(), ) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), api_locking::LockAction::NotApplicable, ) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::EphemeralKeyDelete))] pub async fn ephemeral_key_delete( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, ) -> HttpResponse { let flow = Flow::EphemeralKeyDelete; let payload = path.into_inner(); api::server_wrap( flow, state, &req, payload, |state, _: auth::AuthenticationData, req, _| helpers::delete_ephemeral_key(state, req), &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), api_locking::LockAction::NotApplicable, ) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::EphemeralKeyCreate))] pub async fn client_secret_create( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<api_models::ephemeral_key::ClientSecretCreateRequest>, ) -> HttpResponse { let flow = Flow::EphemeralKeyCreate; let payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, payload, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); helpers::make_client_secret( state, payload.resource_id.to_owned(), merchant_context, req.headers(), ) }, &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::EphemeralKeyDelete))] pub async fn client_secret_delete( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, ) -> HttpResponse { let flow = Flow::EphemeralKeyDelete; let payload = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, _: auth::AuthenticationData, req, _| helpers::delete_client_secret(state, req), &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/ephemeral_key.rs
router::src::routes::ephemeral_key
867
true
// File: crates/router/src/routes/mandates.rs // Module: router::src::routes::mandates use actix_web::{web, HttpRequest, HttpResponse}; use router_env::{instrument, tracing, Flow}; use super::app::AppState; use crate::{ core::{api_locking, mandate}, services::{api, authentication as auth, authorization::permissions::Permission}, types::{api::mandates, domain}, }; /// Mandates - Retrieve Mandate /// /// Retrieves a mandate created using the Payments/Create API #[instrument(skip_all, fields(flow = ?Flow::MandatesRetrieve))] // #[get("/{id}")] pub async fn get_mandate( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, ) -> HttpResponse { let flow = Flow::MandatesRetrieve; let mandate_id = mandates::MandateId { mandate_id: path.into_inner(), }; Box::pin(api::server_wrap( flow, state, &req, mandate_id, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); mandate::get_mandate(state, merchant_context, req) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::MandatesRevoke))] pub async fn revoke_mandate( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, ) -> HttpResponse { let flow = Flow::MandatesRevoke; let mandate_id = mandates::MandateId { mandate_id: path.into_inner(), }; Box::pin(api::server_wrap( flow, state, &req, mandate_id, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); mandate::revoke_mandate(state, merchant_context, req) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), api_locking::LockAction::NotApplicable, )) .await } /// Mandates - List Mandates #[instrument(skip_all, fields(flow = ?Flow::MandatesList))] pub async fn retrieve_mandates_list( state: web::Data<AppState>, req: HttpRequest, payload: web::Query<api_models::mandates::MandateListConstraints>, ) -> HttpResponse { let flow = Flow::MandatesList; let payload = payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); mandate::retrieve_mandates_list(state, merchant_context, req) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantMandateRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/mandates.rs
router::src::routes::mandates
807
true
// File: crates/router/src/routes/feature_matrix.rs // Module: router::src::routes::feature_matrix use actix_web::{web, HttpRequest, Responder}; use api_models::{connector_enums::Connector, feature_matrix}; use common_enums::enums; use hyperswitch_domain_models::{ api::ApplicationResponse, router_response_types::PaymentMethodTypeMetadata, }; use hyperswitch_interfaces::api::ConnectorSpecifications; use router_env::{instrument, tracing, Flow}; use strum::IntoEnumIterator; use crate::{ self as app, core::{api_locking::LockAction, errors::RouterResponse}, services::{api, authentication as auth, connector_integration_interface::ConnectorEnum}, settings, types::api::{self as api_types, payments as payment_types}, }; #[instrument(skip_all)] pub async fn fetch_feature_matrix( state: web::Data<app::AppState>, req: HttpRequest, json_payload: Option<web::Json<payment_types::FeatureMatrixRequest>>, ) -> impl Responder { let flow: Flow = Flow::FeatureMatrix; let payload = json_payload .map(|json_request| json_request.into_inner()) .unwrap_or_else(|| payment_types::FeatureMatrixRequest { connectors: None }); Box::pin(api::server_wrap( flow, state, &req, payload, |state, (), req, _| generate_feature_matrix(state, req), &auth::NoAuth, LockAction::NotApplicable, )) .await } pub async fn generate_feature_matrix( state: app::SessionState, req: payment_types::FeatureMatrixRequest, ) -> RouterResponse<feature_matrix::FeatureMatrixListResponse> { let connector_list = req .connectors .unwrap_or_else(|| Connector::iter().collect()); let feature_matrix_response: Vec<payment_types::ConnectorFeatureMatrixResponse> = connector_list .into_iter() .filter_map(|connector_name| { api_types::feature_matrix::FeatureMatrixConnectorData::convert_connector( &connector_name.to_string(), ) .inspect_err(|_| { router_env::logger::warn!("Failed to fetch {:?} details", connector_name) }) .ok() .and_then(|connector| { build_connector_feature_details(&state, connector, connector_name.to_string()) }) }) .collect(); Ok(ApplicationResponse::Json( payment_types::FeatureMatrixListResponse { connector_count: feature_matrix_response.len(), connectors: feature_matrix_response, }, )) } fn build_connector_feature_details( state: &app::SessionState, connector: ConnectorEnum, connector_name: String, ) -> Option<feature_matrix::ConnectorFeatureMatrixResponse> { let connector_integration_features = connector.get_supported_payment_methods(); let supported_payment_methods = connector_integration_features.map(|connector_integration_feature_data| { connector_integration_feature_data .iter() .flat_map(|(payment_method, supported_payment_method_types)| { build_payment_method_wise_feature_details( state, &connector_name, *payment_method, supported_payment_method_types, ) }) .collect::<Vec<feature_matrix::SupportedPaymentMethod>>() }); let supported_webhook_flows = connector .get_supported_webhook_flows() .map(|webhook_flows| webhook_flows.to_vec()); let connector_about = connector.get_connector_about(); connector_about.map( |connector_about| feature_matrix::ConnectorFeatureMatrixResponse { name: connector_name.to_uppercase(), display_name: connector_about.display_name.to_string(), description: connector_about.description.to_string(), integration_status: connector_about.integration_status, category: connector_about.connector_type, supported_webhook_flows, supported_payment_methods, }, ) } fn build_payment_method_wise_feature_details( state: &app::SessionState, connector_name: &str, payment_method: enums::PaymentMethod, supported_payment_method_types: &PaymentMethodTypeMetadata, ) -> Vec<feature_matrix::SupportedPaymentMethod> { supported_payment_method_types .iter() .map(|(payment_method_type, feature_metadata)| { let payment_method_type_config = state .conf .pm_filters .0 .get(connector_name) .and_then(|selected_connector| { selected_connector.0.get( &settings::PaymentMethodFilterKey::PaymentMethodType( *payment_method_type, ), ) }); let supported_countries = payment_method_type_config.and_then(|config| { config.country.clone().map(|set| { set.into_iter() .map(common_enums::CountryAlpha2::from_alpha2_to_alpha3) .collect::<std::collections::HashSet<_>>() }) }); let supported_currencies = payment_method_type_config.and_then(|config| config.currency.clone()); feature_matrix::SupportedPaymentMethod { payment_method, payment_method_type: *payment_method_type, payment_method_type_display_name: payment_method_type.to_display_name(), mandates: feature_metadata.mandates, refunds: feature_metadata.refunds, supported_capture_methods: feature_metadata.supported_capture_methods.clone(), payment_method_specific_features: feature_metadata.specific_features.clone(), supported_countries, supported_currencies, } }) .collect() }
crates/router/src/routes/feature_matrix.rs
router::src::routes::feature_matrix
1,144
true
// File: crates/router/src/routes/app.rs // Module: router::src::routes::app use std::{collections::HashMap, sync::Arc}; use actix_web::{web, Scope}; #[cfg(all(feature = "olap", feature = "v1"))] use api_models::routing::RoutingRetrieveQuery; use api_models::routing::RuleMigrationQuery; #[cfg(feature = "olap")] use common_enums::{ExecutionMode, TransactionType}; #[cfg(feature = "partial-auth")] use common_utils::crypto::Blake3; use common_utils::{id_type, types::TenantConfig}; #[cfg(feature = "email")] use external_services::email::{ no_email::NoEmailClient, ses::AwsSes, smtp::SmtpServer, EmailClientConfigs, EmailService, }; #[cfg(all(feature = "revenue_recovery", feature = "v2"))] use external_services::grpc_client::revenue_recovery::GrpcRecoveryHeaders; use external_services::{ file_storage::FileStorageInterface, grpc_client::{GrpcClients, GrpcHeaders, GrpcHeadersUcs, GrpcHeadersUcsBuilderInitial}, superposition::SuperpositionClient, }; use hyperswitch_interfaces::{ crm::CrmInterface, encryption_interface::EncryptionManagementInterface, secrets_interface::secret_state::{RawSecret, SecuredSecret}, }; use router_env::tracing_actix_web::RequestId; use scheduler::SchedulerInterface; use storage_impl::{redis::RedisStore, MockDb}; use tokio::sync::oneshot; use self::settings::Tenant; #[cfg(any(feature = "olap", feature = "oltp"))] use super::currency; #[cfg(feature = "dummy_connector")] use super::dummy_connector::*; #[cfg(all(any(feature = "v1", feature = "v2"), feature = "oltp"))] use super::ephemeral_key::*; #[cfg(any(feature = "olap", feature = "oltp"))] use super::payment_methods; #[cfg(feature = "payouts")] use super::payout_link::*; #[cfg(feature = "payouts")] use super::payouts::*; #[cfg(all(feature = "oltp", feature = "v1"))] use super::pm_auth; #[cfg(feature = "oltp")] use super::poll; #[cfg(feature = "v2")] use super::proxy; #[cfg(all(feature = "v2", feature = "revenue_recovery", feature = "oltp"))] use super::recovery_webhooks::*; #[cfg(all(feature = "oltp", feature = "v2"))] use super::refunds; #[cfg(feature = "olap")] use super::routing; #[cfg(all(feature = "oltp", feature = "v2"))] use super::tokenization as tokenization_routes; #[cfg(all(feature = "olap", any(feature = "v1", feature = "v2")))] use super::verification::{apple_pay_merchant_registration, retrieve_apple_pay_verified_domains}; #[cfg(feature = "oltp")] use super::webhooks::*; use super::{ admin, api_keys, cache::*, chat, connector_onboarding, disputes, files, gsm, health::*, profiles, relay, user, user_role, }; #[cfg(feature = "v1")] use super::{ apple_pay_certificates_migration, blocklist, payment_link, subscription, webhook_events, }; #[cfg(any(feature = "olap", feature = "oltp"))] use super::{configs::*, customers, payments}; #[cfg(all(any(feature = "olap", feature = "oltp"), feature = "v1"))] use super::{mandates::*, refunds::*}; #[cfg(feature = "olap")] pub use crate::analytics::opensearch::OpenSearchClient; #[cfg(feature = "olap")] use crate::analytics::AnalyticsProvider; #[cfg(feature = "partial-auth")] use crate::errors::RouterResult; #[cfg(feature = "oltp")] use crate::routes::authentication; #[cfg(feature = "v1")] use crate::routes::cards_info::{ card_iin_info, create_cards_info, migrate_cards_info, update_cards_info, }; #[cfg(all(feature = "olap", feature = "v1"))] use crate::routes::feature_matrix; #[cfg(all(feature = "frm", feature = "oltp"))] use crate::routes::fraud_check as frm_routes; #[cfg(all(feature = "olap", feature = "v1"))] use crate::routes::profile_acquirer; #[cfg(all(feature = "recon", feature = "olap"))] use crate::routes::recon as recon_routes; pub use crate::{ configs::settings, db::{ AccountsStorageInterface, CommonStorageInterface, GlobalStorageInterface, StorageImpl, StorageInterface, }, events::EventsHandler, services::{get_cache_store, get_store}, }; use crate::{ configs::{secrets_transformers, Settings}, db::kafka_store::{KafkaStore, TenantID}, routes::{hypersense as hypersense_routes, three_ds_decision_rule}, }; #[derive(Clone)] pub struct ReqState { pub event_context: events::EventContext<crate::events::EventType, EventsHandler>, } #[derive(Clone)] pub struct SessionState { pub store: Box<dyn StorageInterface>, /// Global store is used for global schema operations in tables like Users and Tenants pub global_store: Box<dyn GlobalStorageInterface>, pub accounts_store: Box<dyn AccountsStorageInterface>, pub conf: Arc<settings::Settings<RawSecret>>, pub api_client: Box<dyn crate::services::ApiClient>, pub event_handler: EventsHandler, #[cfg(feature = "email")] pub email_client: Arc<Box<dyn EmailService>>, #[cfg(feature = "olap")] pub pool: AnalyticsProvider, pub file_storage_client: Arc<dyn FileStorageInterface>, pub request_id: Option<RequestId>, pub base_url: String, pub tenant: Tenant, #[cfg(feature = "olap")] pub opensearch_client: Option<Arc<OpenSearchClient>>, pub grpc_client: Arc<GrpcClients>, pub theme_storage_client: Arc<dyn FileStorageInterface>, pub locale: String, pub crm_client: Arc<dyn CrmInterface>, pub infra_components: Option<serde_json::Value>, pub enhancement: Option<HashMap<String, String>>, pub superposition_service: Option<Arc<SuperpositionClient>>, } impl scheduler::SchedulerSessionState for SessionState { fn get_db(&self) -> Box<dyn SchedulerInterface> { self.store.get_scheduler_db() } } impl SessionState { pub fn get_req_state(&self) -> ReqState { ReqState { event_context: events::EventContext::new(self.event_handler.clone()), } } pub fn get_grpc_headers(&self) -> GrpcHeaders { GrpcHeaders { tenant_id: self.tenant.tenant_id.get_string_repr().to_string(), request_id: self.request_id.map(|req_id| (*req_id).to_string()), } } pub fn get_grpc_headers_ucs( &self, unified_connector_service_execution_mode: ExecutionMode, ) -> GrpcHeadersUcsBuilderInitial { let tenant_id = self.tenant.tenant_id.get_string_repr().to_string(); let request_id = self.request_id.map(|req_id| (*req_id).to_string()); let shadow_mode = match unified_connector_service_execution_mode { ExecutionMode::Primary => false, ExecutionMode::Shadow => true, }; GrpcHeadersUcs::builder() .tenant_id(tenant_id) .request_id(request_id) .shadow_mode(Some(shadow_mode)) } #[cfg(all(feature = "revenue_recovery", feature = "v2"))] pub fn get_recovery_grpc_headers(&self) -> GrpcRecoveryHeaders { GrpcRecoveryHeaders { request_id: self.request_id.map(|req_id| (*req_id).to_string()), } } } pub trait SessionStateInfo { fn conf(&self) -> settings::Settings<RawSecret>; fn store(&self) -> Box<dyn StorageInterface>; fn event_handler(&self) -> EventsHandler; fn get_request_id(&self) -> Option<String>; fn add_request_id(&mut self, request_id: RequestId); #[cfg(feature = "partial-auth")] fn get_detached_auth(&self) -> RouterResult<(Blake3, &[u8])>; fn session_state(&self) -> SessionState; fn global_store(&self) -> Box<dyn GlobalStorageInterface>; } impl SessionStateInfo for SessionState { fn store(&self) -> Box<dyn StorageInterface> { self.store.to_owned() } fn conf(&self) -> settings::Settings<RawSecret> { self.conf.as_ref().to_owned() } fn event_handler(&self) -> EventsHandler { self.event_handler.clone() } fn get_request_id(&self) -> Option<String> { self.api_client.get_request_id_str() } fn add_request_id(&mut self, request_id: RequestId) { self.api_client.add_request_id(request_id); self.store.add_request_id(request_id.to_string()); self.request_id.replace(request_id); } #[cfg(feature = "partial-auth")] fn get_detached_auth(&self) -> RouterResult<(Blake3, &[u8])> { use error_stack::ResultExt; use hyperswitch_domain_models::errors::api_error_response as errors; use masking::prelude::PeekInterface as _; use router_env::logger; let output = CHECKSUM_KEY.get_or_try_init(|| { let conf = self.conf(); let context = conf .api_keys .get_inner() .checksum_auth_context .peek() .clone(); let key = conf.api_keys.get_inner().checksum_auth_key.peek(); hex::decode(key).map(|key| { ( masking::StrongSecret::new(context), masking::StrongSecret::new(key), ) }) }); match output { Ok((context, key)) => Ok((Blake3::new(context.peek().clone()), key.peek())), Err(err) => { logger::error!("Failed to get checksum key"); Err(err).change_context(errors::ApiErrorResponse::InternalServerError) } } } fn session_state(&self) -> SessionState { self.clone() } fn global_store(&self) -> Box<dyn GlobalStorageInterface> { self.global_store.to_owned() } } impl hyperswitch_interfaces::api_client::ApiClientWrapper for SessionState { fn get_api_client(&self) -> &dyn crate::services::ApiClient { self.api_client.as_ref() } fn get_proxy(&self) -> hyperswitch_interfaces::types::Proxy { self.conf.proxy.clone() } fn get_request_id(&self) -> Option<RequestId> { self.request_id } fn get_request_id_str(&self) -> Option<String> { self.request_id .map(|req_id| req_id.as_hyphenated().to_string()) } fn get_tenant(&self) -> Tenant { self.tenant.clone() } fn get_connectors(&self) -> hyperswitch_domain_models::connector_endpoints::Connectors { self.conf.connectors.clone() } fn event_handler(&self) -> &dyn hyperswitch_interfaces::events::EventHandlerInterface { &self.event_handler } } #[derive(Clone)] pub struct AppState { pub flow_name: String, pub global_store: Box<dyn GlobalStorageInterface>, // TODO: use a separate schema for accounts_store pub accounts_store: HashMap<id_type::TenantId, Box<dyn AccountsStorageInterface>>, pub stores: HashMap<id_type::TenantId, Box<dyn StorageInterface>>, pub conf: Arc<settings::Settings<RawSecret>>, pub event_handler: EventsHandler, #[cfg(feature = "email")] pub email_client: Arc<Box<dyn EmailService>>, pub api_client: Box<dyn crate::services::ApiClient>, #[cfg(feature = "olap")] pub pools: HashMap<id_type::TenantId, AnalyticsProvider>, #[cfg(feature = "olap")] pub opensearch_client: Option<Arc<OpenSearchClient>>, pub request_id: Option<RequestId>, pub file_storage_client: Arc<dyn FileStorageInterface>, pub encryption_client: Arc<dyn EncryptionManagementInterface>, pub grpc_client: Arc<GrpcClients>, pub theme_storage_client: Arc<dyn FileStorageInterface>, pub crm_client: Arc<dyn CrmInterface>, pub infra_components: Option<serde_json::Value>, pub enhancement: Option<HashMap<String, String>>, pub superposition_service: Option<Arc<SuperpositionClient>>, } impl scheduler::SchedulerAppState for AppState { fn get_tenants(&self) -> Vec<id_type::TenantId> { self.conf.multitenancy.get_tenant_ids() } } pub trait AppStateInfo { fn conf(&self) -> settings::Settings<RawSecret>; fn event_handler(&self) -> EventsHandler; #[cfg(feature = "email")] fn email_client(&self) -> Arc<Box<dyn EmailService>>; fn add_request_id(&mut self, request_id: RequestId); fn add_flow_name(&mut self, flow_name: String); fn get_request_id(&self) -> Option<String>; } #[cfg(feature = "partial-auth")] static CHECKSUM_KEY: once_cell::sync::OnceCell<( masking::StrongSecret<String>, masking::StrongSecret<Vec<u8>>, )> = once_cell::sync::OnceCell::new(); impl AppStateInfo for AppState { fn conf(&self) -> settings::Settings<RawSecret> { self.conf.as_ref().to_owned() } #[cfg(feature = "email")] fn email_client(&self) -> Arc<Box<dyn EmailService>> { self.email_client.to_owned() } fn event_handler(&self) -> EventsHandler { self.event_handler.clone() } fn add_request_id(&mut self, request_id: RequestId) { self.api_client.add_request_id(request_id); self.request_id.replace(request_id); } fn add_flow_name(&mut self, flow_name: String) { self.api_client.add_flow_name(flow_name); } fn get_request_id(&self) -> Option<String> { self.api_client.get_request_id_str() } } impl AsRef<Self> for AppState { fn as_ref(&self) -> &Self { self } } #[cfg(feature = "email")] pub async fn create_email_client( settings: &settings::Settings<RawSecret>, ) -> Box<dyn EmailService> { match &settings.email.client_config { EmailClientConfigs::Ses { aws_ses } => Box::new( AwsSes::create( &settings.email, aws_ses, settings.proxy.https_url.to_owned(), ) .await, ), EmailClientConfigs::Smtp { smtp } => { Box::new(SmtpServer::create(&settings.email, smtp.clone()).await) } EmailClientConfigs::NoEmailClient => Box::new(NoEmailClient::create().await), } } impl AppState { /// # Panics /// /// Panics if Store can't be created or JWE decryption fails pub async fn with_storage( conf: settings::Settings<SecuredSecret>, storage_impl: StorageImpl, shut_down_signal: oneshot::Sender<()>, api_client: Box<dyn crate::services::ApiClient>, ) -> Self { #[allow(clippy::expect_used)] let secret_management_client = conf .secrets_management .get_secret_management_client() .await .expect("Failed to create secret management client"); let conf = Box::pin(secrets_transformers::fetch_raw_secrets( conf, &*secret_management_client, )) .await; #[allow(clippy::expect_used)] let encryption_client = conf .encryption_management .get_encryption_management_client() .await .expect("Failed to create encryption client"); Box::pin(async move { let testable = storage_impl == StorageImpl::PostgresqlTest; #[allow(clippy::expect_used)] let event_handler = conf .events .get_event_handler() .await .expect("Failed to create event handler"); #[allow(clippy::expect_used)] #[cfg(feature = "olap")] let opensearch_client = conf .opensearch .get_opensearch_client() .await .expect("Failed to initialize OpenSearch client.") .map(Arc::new); #[allow(clippy::expect_used)] let cache_store = get_cache_store(&conf.clone(), shut_down_signal, testable) .await .expect("Failed to create store"); let global_store: Box<dyn GlobalStorageInterface> = Self::get_store_interface( &storage_impl, &event_handler, &conf, &conf.multitenancy.global_tenant, Arc::clone(&cache_store), testable, ) .await .get_global_storage_interface(); #[cfg(feature = "olap")] let pools = conf .multitenancy .tenants .get_pools_map(conf.analytics.get_inner()) .await; let stores = conf .multitenancy .tenants .get_store_interface_map(&storage_impl, &conf, Arc::clone(&cache_store), testable) .await; let accounts_store = conf .multitenancy .tenants .get_accounts_store_interface_map( &storage_impl, &conf, Arc::clone(&cache_store), testable, ) .await; #[cfg(feature = "email")] let email_client = Arc::new(create_email_client(&conf).await); let file_storage_client = conf.file_storage.get_file_storage_client().await; let theme_storage_client = conf.theme.storage.get_file_storage_client().await; let crm_client = conf.crm.get_crm_client().await; let grpc_client = conf.grpc_client.get_grpc_client_interface().await; let infra_component_values = Self::process_env_mappings(conf.infra_values.clone()); let enhancement = conf.enhancement.clone(); let superposition_service = if conf.superposition.get_inner().enabled { match SuperpositionClient::new(conf.superposition.get_inner().clone()).await { Ok(client) => { router_env::logger::info!("Superposition client initialized successfully"); Some(Arc::new(client)) } Err(err) => { router_env::logger::warn!( "Failed to initialize superposition client: {:?}. Continuing without superposition support.", err ); None } } } else { None }; Self { flow_name: String::from("default"), stores, global_store, accounts_store, conf: Arc::new(conf), #[cfg(feature = "email")] email_client, api_client, event_handler, #[cfg(feature = "olap")] pools, #[cfg(feature = "olap")] opensearch_client, request_id: None, file_storage_client, encryption_client, grpc_client, theme_storage_client, crm_client, infra_components: infra_component_values, enhancement, superposition_service, } }) .await } /// # Panics /// /// Panics if Failed to create store pub async fn get_store_interface( storage_impl: &StorageImpl, event_handler: &EventsHandler, conf: &Settings, tenant: &dyn TenantConfig, cache_store: Arc<RedisStore>, testable: bool, ) -> Box<dyn CommonStorageInterface> { match storage_impl { StorageImpl::Postgresql | StorageImpl::PostgresqlTest => match event_handler { EventsHandler::Kafka(kafka_client) => Box::new( KafkaStore::new( #[allow(clippy::expect_used)] get_store(&conf.clone(), tenant, Arc::clone(&cache_store), testable) .await .expect("Failed to create store"), kafka_client.clone(), TenantID(tenant.get_tenant_id().get_string_repr().to_owned()), tenant, ) .await, ), EventsHandler::Logs(_) => Box::new( #[allow(clippy::expect_used)] get_store(conf, tenant, Arc::clone(&cache_store), testable) .await .expect("Failed to create store"), ), }, #[allow(clippy::expect_used)] StorageImpl::Mock => Box::new( MockDb::new(&conf.redis) .await .expect("Failed to create mock store"), ), } } pub async fn new( conf: settings::Settings<SecuredSecret>, shut_down_signal: oneshot::Sender<()>, api_client: Box<dyn crate::services::ApiClient>, ) -> Self { Box::pin(Self::with_storage( conf, StorageImpl::Postgresql, shut_down_signal, api_client, )) .await } pub fn get_session_state<E, F>( self: Arc<Self>, tenant: &id_type::TenantId, locale: Option<String>, err: F, ) -> Result<SessionState, E> where F: FnOnce() -> E + Copy, { let tenant_conf = self.conf.multitenancy.get_tenant(tenant).ok_or_else(err)?; let mut event_handler = self.event_handler.clone(); event_handler.add_tenant(tenant_conf); let store = self.stores.get(tenant).ok_or_else(err)?.clone(); Ok(SessionState { store, global_store: self.global_store.clone(), accounts_store: self.accounts_store.get(tenant).ok_or_else(err)?.clone(), conf: Arc::clone(&self.conf), api_client: self.api_client.clone(), event_handler, #[cfg(feature = "olap")] pool: self.pools.get(tenant).ok_or_else(err)?.clone(), file_storage_client: self.file_storage_client.clone(), request_id: self.request_id, base_url: tenant_conf.base_url.clone(), tenant: tenant_conf.clone(), #[cfg(feature = "email")] email_client: Arc::clone(&self.email_client), #[cfg(feature = "olap")] opensearch_client: self.opensearch_client.clone(), grpc_client: Arc::clone(&self.grpc_client), theme_storage_client: self.theme_storage_client.clone(), locale: locale.unwrap_or(common_utils::consts::DEFAULT_LOCALE.to_string()), crm_client: self.crm_client.clone(), infra_components: self.infra_components.clone(), enhancement: self.enhancement.clone(), superposition_service: self.superposition_service.clone(), }) } pub fn process_env_mappings( mappings: Option<HashMap<String, String>>, ) -> Option<serde_json::Value> { let result: HashMap<String, String> = mappings? .into_iter() .filter_map(|(key, env_var)| std::env::var(&env_var).ok().map(|value| (key, value))) .collect(); if result.is_empty() { None } else { Some(serde_json::Value::Object( result .into_iter() .map(|(k, v)| (k, serde_json::Value::String(v))) .collect(), )) } } } pub struct Health; #[cfg(feature = "v1")] impl Health { pub fn server(state: AppState) -> Scope { web::scope("health") .app_data(web::Data::new(state)) .service(web::resource("").route(web::get().to(health))) .service(web::resource("/ready").route(web::get().to(deep_health_check))) } } #[cfg(feature = "v2")] impl Health { pub fn server(state: AppState) -> Scope { web::scope("/v2/health") .app_data(web::Data::new(state)) .service(web::resource("").route(web::get().to(health))) .service(web::resource("/ready").route(web::get().to(deep_health_check))) } } #[cfg(feature = "dummy_connector")] pub struct DummyConnector; #[cfg(all(feature = "dummy_connector", feature = "v1"))] impl DummyConnector { pub fn server(state: AppState) -> Scope { let mut routes_with_restricted_access = web::scope(""); #[cfg(not(feature = "external_access_dc"))] { routes_with_restricted_access = routes_with_restricted_access.guard(actix_web::guard::Host("localhost")); } routes_with_restricted_access = routes_with_restricted_access .service(web::resource("/payment").route(web::post().to(dummy_connector_payment))) .service( web::resource("/payments/{payment_id}") .route(web::get().to(dummy_connector_payment_data)), ) .service( web::resource("/{payment_id}/refund").route(web::post().to(dummy_connector_refund)), ) .service( web::resource("/refunds/{refund_id}") .route(web::get().to(dummy_connector_refund_data)), ); web::scope("/dummy-connector") .app_data(web::Data::new(state)) .service( web::resource("/authorize/{attempt_id}") .route(web::get().to(dummy_connector_authorize_payment)), ) .service( web::resource("/complete/{attempt_id}") .route(web::get().to(dummy_connector_complete_payment)), ) .service(routes_with_restricted_access) } } #[cfg(all(feature = "dummy_connector", feature = "v2"))] impl DummyConnector { pub fn server(state: AppState) -> Scope { let mut routes_with_restricted_access = web::scope(""); #[cfg(not(feature = "external_access_dc"))] { routes_with_restricted_access = routes_with_restricted_access.guard(actix_web::guard::Host("localhost")); } routes_with_restricted_access = routes_with_restricted_access .service(web::resource("/payment").route(web::post().to(dummy_connector_payment))); web::scope("/dummy-connector") .app_data(web::Data::new(state)) .service(routes_with_restricted_access) } } pub struct Payments; #[cfg(all(any(feature = "olap", feature = "oltp"), feature = "v2"))] impl Payments { pub fn server(state: AppState) -> Scope { let mut route = web::scope("/v2/payments").app_data(web::Data::new(state)); route = route .service( web::resource("/create-intent") .route(web::post().to(payments::payments_create_intent)), ) .service(web::resource("/filter").route(web::get().to(payments::get_payment_filters))) .service( web::resource("/profile/filter") .route(web::get().to(payments::get_payment_filters_profile)), ) .service( web::resource("") .route(web::post().to(payments::payments_create_and_confirm_intent)), ) .service(web::resource("/list").route(web::get().to(payments::payments_list))) .service( web::resource("/aggregate").route(web::get().to(payments::get_payments_aggregates)), ) .service( web::resource("/recovery") .route(web::post().to(payments::recovery_payments_create)), ) .service( web::resource("/profile/aggregate") .route(web::get().to(payments::get_payments_aggregates_profile)), ); route = route .service(web::resource("/ref/{merchant_reference_id}").route( web::get().to(payments::payment_get_intent_using_merchant_reference_id), )); route = route.service( web::scope("/{payment_id}") .service( web::resource("/confirm-intent") .route(web::post().to(payments::payment_confirm_intent)), ) // TODO: Deprecated. Remove this in favour of /list-attempts .service( web::resource("/list_attempts") .route(web::get().to(payments::list_payment_attempts)), ) .service( web::resource("/list-attempts") .route(web::get().to(payments::list_payment_attempts)), ) .service( web::resource("/proxy-confirm-intent") .route(web::post().to(payments::proxy_confirm_intent)), ) .service( web::resource("/confirm-intent/external-vault-proxy") .route(web::post().to(payments::confirm_intent_with_external_vault_proxy)), ) .service( web::resource("/get-intent") .route(web::get().to(payments::payments_get_intent)), ) .service( web::resource("/update-intent") .route(web::put().to(payments::payments_update_intent)), ) .service( web::resource("/create-external-sdk-tokens") .route(web::post().to(payments::payments_connector_session)), ) .service( web::resource("") .route(web::get().to(payments::payment_status)) .route(web::post().to(payments::payments_status_with_gateway_creds)), ) .service( web::resource("/start-redirection") .route(web::get().to(payments::payments_start_redirection)), ) .service( web::resource("/payment-methods") .route(web::get().to(payments::list_payment_methods)), ) .service( web::resource("/finish-redirection/{publishable_key}/{profile_id}") .route(web::get().to(payments::payments_finish_redirection)), ) .service( web::resource("/capture").route(web::post().to(payments::payments_capture)), ) .service( web::resource("/check-gift-card-balance") .route(web::post().to(payments::payment_check_gift_card_balance)), ) .service(web::resource("/cancel").route(web::post().to(payments::payments_cancel))), ); route } } pub struct Relay; #[cfg(feature = "oltp")] impl Relay { pub fn server(state: AppState) -> Scope { web::scope("/relay") .app_data(web::Data::new(state)) .service(web::resource("").route(web::post().to(relay::relay))) .service(web::resource("/{relay_id}").route(web::get().to(relay::relay_retrieve))) } } #[cfg(feature = "v2")] pub struct Proxy; #[cfg(all(feature = "oltp", feature = "v2"))] impl Proxy { pub fn server(state: AppState) -> Scope { web::scope("/v2/proxy") .app_data(web::Data::new(state)) .service(web::resource("").route(web::post().to(proxy::proxy))) } } #[cfg(feature = "v1")] impl Payments { pub fn server(state: AppState) -> Scope { let mut route = web::scope("/payments").app_data(web::Data::new(state)); #[cfg(feature = "olap")] { route = route .service( web::resource("/list") .route(web::get().to(payments::payments_list)) .route(web::post().to(payments::payments_list_by_filter)), ) .service( web::resource("/profile/list") .route(web::get().to(payments::profile_payments_list)) .route(web::post().to(payments::profile_payments_list_by_filter)), ) .service( web::resource("/filter") .route(web::post().to(payments::get_filters_for_payments)), ) .service( web::resource("/v2/filter").route(web::get().to(payments::get_payment_filters)), ) .service( web::resource("/aggregate") .route(web::get().to(payments::get_payments_aggregates)), ) .service( web::resource("/profile/aggregate") .route(web::get().to(payments::get_payments_aggregates_profile)), ) .service( web::resource("/v2/profile/filter") .route(web::get().to(payments::get_payment_filters_profile)), ) .service( web::resource("/{payment_id}/manual-update") .route(web::put().to(payments::payments_manual_update)), ) } #[cfg(feature = "oltp")] { route = route .service(web::resource("").route(web::post().to(payments::payments_create))) .service( web::resource("/session_tokens") .route(web::post().to(payments::payments_connector_session)), ) .service( web::resource("/sync") .route(web::post().to(payments::payments_retrieve_with_gateway_creds)), ) .service( web::resource("/{payment_id}") .route(web::get().to(payments::payments_retrieve)) .route(web::post().to(payments::payments_update)), ) .service( web::resource("/{payment_id}/post_session_tokens").route(web::post().to(payments::payments_post_session_tokens)), ) .service( web::resource("/{payment_id}/confirm").route(web::post().to(payments::payments_confirm)), ) .service( web::resource("/{payment_id}/cancel").route(web::post().to(payments::payments_cancel)), ) .service( web::resource("/{payment_id}/cancel_post_capture").route(web::post().to(payments::payments_cancel_post_capture)), ) .service( web::resource("/{payment_id}/capture").route(web::post().to(payments::payments_capture)), ) .service( web::resource("/{payment_id}/approve") .route(web::post().to(payments::payments_approve)), ) .service( web::resource("/{payment_id}/reject") .route(web::post().to(payments::payments_reject)), ) .service( web::resource("/{payment_id}/eligibility") .route(web::post().to(payments::payments_submit_eligibility)), ) .service( web::resource("/redirect/{payment_id}/{merchant_id}/{attempt_id}") .route(web::get().to(payments::payments_start)), ) .service( web::resource( "/{payment_id}/{merchant_id}/redirect/response/{connector}/{creds_identifier}", ) .route(web::get().to(payments::payments_redirect_response_with_creds_identifier)), ) .service( web::resource("/{payment_id}/{merchant_id}/redirect/response/{connector}") .route(web::get().to(payments::payments_redirect_response)) .route(web::post().to(payments::payments_redirect_response)) ) .service( web::resource("/{payment_id}/{merchant_id}/redirect/complete/{connector}/{creds_identifier}") .route(web::get().to(payments::payments_complete_authorize_redirect_with_creds_identifier)) .route(web::post().to(payments::payments_complete_authorize_redirect_with_creds_identifier)) ) .service( web::resource("/{payment_id}/{merchant_id}/redirect/complete/{connector}") .route(web::get().to(payments::payments_complete_authorize_redirect)) .route(web::post().to(payments::payments_complete_authorize_redirect)), ) .service( web::resource("/{payment_id}/complete_authorize") .route(web::post().to(payments::payments_complete_authorize)), ) .service( web::resource("/{payment_id}/incremental_authorization").route(web::post().to(payments::payments_incremental_authorization)), ) .service( web::resource("/{payment_id}/extend_authorization").route(web::post().to(payments::payments_extend_authorization)), ) .service( web::resource("/{payment_id}/{merchant_id}/authorize/{connector}") .route(web::post().to(payments::post_3ds_payments_authorize)) .route(web::get().to(payments::post_3ds_payments_authorize)) ) .service( web::resource("/{payment_id}/3ds/authentication").route(web::post().to(payments::payments_external_authentication)), ) .service( web::resource("/{payment_id}/extended_card_info").route(web::get().to(payments::retrieve_extended_card_info)), ) .service( web::resource("{payment_id}/calculate_tax") .route(web::post().to(payments::payments_dynamic_tax_calculation)), ) .service( web::resource("{payment_id}/update_metadata") .route(web::post().to(payments::payments_update_metadata)), ); } route } } #[cfg(any(feature = "olap", feature = "oltp"))] pub struct Forex; #[cfg(all(any(feature = "olap", feature = "oltp"), feature = "v1"))] impl Forex { pub fn server(state: AppState) -> Scope { web::scope("/forex") .app_data(web::Data::new(state.clone())) .app_data(web::Data::new(state.clone())) .service(web::resource("/rates").route(web::get().to(currency::retrieve_forex))) .service( web::resource("/convert_from_minor").route(web::get().to(currency::convert_forex)), ) } } #[cfg(feature = "olap")] pub struct Routing; #[cfg(all(feature = "olap", feature = "v2"))] impl Routing { pub fn server(state: AppState) -> Scope { web::scope("/v2/routing-algorithms") .app_data(web::Data::new(state.clone())) .service( web::resource("").route(web::post().to(|state, req, payload| { routing::routing_create_config(state, req, payload, TransactionType::Payment) })), ) .service( web::resource("/{algorithm_id}") .route(web::get().to(routing::routing_retrieve_config)), ) } } #[cfg(all(feature = "olap", feature = "v1"))] impl Routing { pub fn server(state: AppState) -> Scope { #[allow(unused_mut)] let mut route = web::scope("/routing") .app_data(web::Data::new(state.clone())) .service( web::resource("/active").route(web::get().to(|state, req, query_params| { routing::routing_retrieve_linked_config(state, req, query_params, None) })), ) .service( web::resource("") .route( web::get().to(|state, req, path: web::Query<RoutingRetrieveQuery>| { routing::list_routing_configs(state, req, path, None) }), ) .route(web::post().to(|state, req, payload| { routing::routing_create_config(state, req, payload, None) })), ) .service(web::resource("/list/profile").route(web::get().to( |state, req, query: web::Query<RoutingRetrieveQuery>| { routing::list_routing_configs_for_profile(state, req, query, None) }, ))) .service( web::resource("/default").route(web::post().to(|state, req, payload| { routing::routing_update_default_config( state, req, payload, &TransactionType::Payment, ) })), ) .service(web::resource("/rule/migrate").route(web::post().to( |state, req, query: web::Query<RuleMigrationQuery>| { routing::migrate_routing_rules_for_profile(state, req, query) }, ))) .service( web::resource("/deactivate").route(web::post().to(|state, req, payload| { routing::routing_unlink_config(state, req, payload, None) })), ) .service( web::resource("/decision") .route(web::put().to(routing::upsert_decision_manager_config)) .route(web::get().to(routing::retrieve_decision_manager_config)) .route(web::delete().to(routing::delete_decision_manager_config)), ) .service( web::resource("/decision/surcharge") .route(web::put().to(routing::upsert_surcharge_decision_manager_config)) .route(web::get().to(routing::retrieve_surcharge_decision_manager_config)) .route(web::delete().to(routing::delete_surcharge_decision_manager_config)), ) .service( web::resource("/default/profile/{profile_id}").route(web::post().to( |state, req, path, payload| { routing::routing_update_default_config_for_profile( state, req, path, payload, &TransactionType::Payment, ) }, )), ) .service( web::resource("/default/profile").route(web::get().to(|state, req| { routing::routing_retrieve_default_config(state, req, &TransactionType::Payment) })), ); #[cfg(feature = "dynamic_routing")] { route = route .service( web::resource("/evaluate") .route(web::post().to(routing::call_decide_gateway_open_router)), ) .service( web::resource("/feedback") .route(web::post().to(routing::call_update_gateway_score_open_router)), ) } #[cfg(feature = "payouts")] { route = route .service( web::resource("/payouts") .route(web::get().to( |state, req, path: web::Query<RoutingRetrieveQuery>| { routing::list_routing_configs( state, req, path, Some(TransactionType::Payout), ) }, )) .route(web::post().to(|state, req, payload| { routing::routing_create_config( state, req, payload, Some(TransactionType::Payout), ) })), ) .service(web::resource("/payouts/list/profile").route(web::get().to( |state, req, query: web::Query<RoutingRetrieveQuery>| { routing::list_routing_configs_for_profile( state, req, query, Some(TransactionType::Payout), ) }, ))) .service(web::resource("/payouts/active").route(web::get().to( |state, req, query_params| { routing::routing_retrieve_linked_config( state, req, query_params, Some(TransactionType::Payout), ) }, ))) .service( web::resource("/payouts/default") .route(web::get().to(|state, req| { routing::routing_retrieve_default_config( state, req, &TransactionType::Payout, ) })) .route(web::post().to(|state, req, payload| { routing::routing_update_default_config( state, req, payload, &TransactionType::Payout, ) })), ) .service( web::resource("/payouts/{algorithm_id}/activate").route(web::post().to( |state, req, path, payload| { routing::routing_link_config( state, req, path, payload, Some(TransactionType::Payout), ) }, )), ) .service(web::resource("/payouts/deactivate").route(web::post().to( |state, req, payload| { routing::routing_unlink_config( state, req, payload, Some(TransactionType::Payout), ) }, ))) .service( web::resource("/payouts/default/profile/{profile_id}").route(web::post().to( |state, req, path, payload| { routing::routing_update_default_config_for_profile( state, req, path, payload, &TransactionType::Payout, ) }, )), ) .service( web::resource("/payouts/default/profile").route(web::get().to(|state, req| { routing::routing_retrieve_default_config_for_profiles( state, req, &TransactionType::Payout, ) })), ); } route = route .service( web::resource("/{algorithm_id}") .route(web::get().to(routing::routing_retrieve_config)), ) .service( web::resource("/{algorithm_id}/activate").route(web::post().to( |state, req, payload, path| { routing::routing_link_config(state, req, path, payload, None) }, )), ) .service( web::resource("/rule/evaluate") .route(web::post().to(routing::evaluate_routing_rule)), ); route } } #[cfg(feature = "oltp")] pub struct Subscription; #[cfg(all(feature = "oltp", feature = "v1"))] impl Subscription { pub fn server(state: AppState) -> Scope { let route = web::scope("/subscriptions").app_data(web::Data::new(state.clone())); route .service( web::resource("").route(web::post().to(|state, req, payload| { subscription::create_and_confirm_subscription(state, req, payload) })), ) .service(web::resource("/create").route( web::post().to(|state, req, payload| { subscription::create_subscription(state, req, payload) }), )) .service(web::resource("/estimate").route(web::get().to(subscription::get_estimate))) .service( web::resource("/plans").route(web::get().to(subscription::get_subscription_plans)), ) .service( web::resource("/{subscription_id}/confirm").route(web::post().to( |state, req, id, payload| { subscription::confirm_subscription(state, req, id, payload) }, )), ) .service( web::resource("/{subscription_id}/update").route(web::put().to( |state, req, id, payload| { subscription::update_subscription(state, req, id, payload) }, )), ) .service( web::resource("/{subscription_id}") .route(web::get().to(subscription::get_subscription)), ) } } pub struct Customers; #[cfg(all(feature = "v2", any(feature = "olap", feature = "oltp")))] impl Customers { pub fn server(state: AppState) -> Scope { let mut route = web::scope("/v2/customers").app_data(web::Data::new(state)); #[cfg(all(feature = "olap", feature = "v2"))] { route = route .service(web::resource("/list").route(web::get().to(customers::customers_list))) .service( web::resource("/list_with_count") .route(web::get().to(customers::customers_list_with_count)), ) .service( web::resource("/total-payment-methods") .route(web::get().to(payment_methods::get_total_payment_method_count)), ) .service( web::resource("/{id}/saved-payment-methods") .route(web::get().to(payment_methods::list_customer_payment_method_api)), ) } #[cfg(all(feature = "oltp", feature = "v2"))] { route = route .service(web::resource("").route(web::post().to(customers::customers_create))) .service( web::resource("/{id}") .route(web::put().to(customers::customers_update)) .route(web::get().to(customers::customers_retrieve)) .route(web::delete().to(customers::customers_delete)), ) } route } } #[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))] impl Customers { pub fn server(state: AppState) -> Scope { let mut route = web::scope("/customers").app_data(web::Data::new(state)); #[cfg(feature = "olap")] { route = route .service( web::resource("/{customer_id}/mandates") .route(web::get().to(customers::get_customer_mandates)), ) .service(web::resource("/list").route(web::get().to(customers::customers_list))) .service( web::resource("/list_with_count") .route(web::get().to(customers::customers_list_with_count)), ) } #[cfg(feature = "oltp")] { route = route .service(web::resource("").route(web::post().to(customers::customers_create))) .service( web::resource("/payment_methods").route( web::get().to(payment_methods::list_customer_payment_method_api_client), ), ) .service( web::resource("/{customer_id}/payment_methods") .route(web::get().to(payment_methods::list_customer_payment_method_api)), ) .service( web::resource("/{customer_id}/payment_methods/{payment_method_id}/default") .route(web::post().to(payment_methods::default_payment_method_set_api)), ) .service( web::resource("/{customer_id}") .route(web::get().to(customers::customers_retrieve)) .route(web::post().to(customers::customers_update)) .route(web::delete().to(customers::customers_delete)), ) } route } } pub struct Refunds; #[cfg(all(any(feature = "olap", feature = "oltp"), feature = "v1"))] impl Refunds { pub fn server(state: AppState) -> Scope { let mut route = web::scope("/refunds").app_data(web::Data::new(state)); #[cfg(feature = "olap")] { route = route .service(web::resource("/list").route(web::post().to(refunds_list))) .service(web::resource("/profile/list").route(web::post().to(refunds_list_profile))) .service(web::resource("/filter").route(web::post().to(refunds_filter_list))) .service(web::resource("/v2/filter").route(web::get().to(get_refunds_filters))) .service(web::resource("/aggregate").route(web::get().to(get_refunds_aggregates))) .service( web::resource("/profile/aggregate") .route(web::get().to(get_refunds_aggregate_profile)), ) .service( web::resource("/v2/profile/filter") .route(web::get().to(get_refunds_filters_profile)), ) .service( web::resource("/{id}/manual-update") .route(web::put().to(refunds_manual_update)), ); } #[cfg(feature = "oltp")] { route = route .service(web::resource("").route(web::post().to(refunds_create))) .service(web::resource("/sync").route(web::post().to(refunds_retrieve_with_body))) .service( web::resource("/{id}") .route(web::get().to(refunds_retrieve)) .route(web::post().to(refunds_update)), ); } route } } #[cfg(all(feature = "v2", any(feature = "olap", feature = "oltp")))] impl Refunds { pub fn server(state: AppState) -> Scope { let mut route = web::scope("/v2/refunds").app_data(web::Data::new(state)); #[cfg(feature = "olap")] { route = route.service(web::resource("/list").route(web::post().to(refunds::refunds_list))); } #[cfg(feature = "oltp")] { route = route .service(web::resource("").route(web::post().to(refunds::refunds_create))) .service( web::resource("/{id}") .route(web::get().to(refunds::refunds_retrieve)) .route(web::post().to(refunds::refunds_retrieve_with_gateway_creds)), ) .service( web::resource("/{id}/update-metadata") .route(web::put().to(refunds::refunds_metadata_update)), ); } route } } #[cfg(feature = "payouts")] pub struct Payouts; #[cfg(all(feature = "payouts", feature = "v1"))] impl Payouts { pub fn server(state: AppState) -> Scope { let mut route = web::scope("/payouts").app_data(web::Data::new(state)); route = route.service(web::resource("/create").route(web::post().to(payouts_create))); #[cfg(feature = "olap")] { route = route .service( web::resource("/list") .route(web::get().to(payouts_list)) .route(web::post().to(payouts_list_by_filter)), ) .service( web::resource("/profile/list") .route(web::get().to(payouts_list_profile)) .route(web::post().to(payouts_list_by_filter_profile)), ) .service( web::resource("/filter") .route(web::post().to(payouts_list_available_filters_for_merchant)), ) .service( web::resource("/profile/filter") .route(web::post().to(payouts_list_available_filters_for_profile)), ); } route = route .service( web::resource("/{payout_id}") .route(web::get().to(payouts_retrieve)) .route(web::put().to(payouts_update)), ) .service(web::resource("/{payout_id}/confirm").route(web::post().to(payouts_confirm))) .service(web::resource("/{payout_id}/cancel").route(web::post().to(payouts_cancel))) .service(web::resource("/{payout_id}/fulfill").route(web::post().to(payouts_fulfill))); route } } #[cfg(all(feature = "v2", any(feature = "olap", feature = "oltp")))] impl PaymentMethods { pub fn server(state: AppState) -> Scope { let mut route = web::scope("/v2/payment-methods").app_data(web::Data::new(state)); #[cfg(feature = "olap")] { route = route.service(web::resource("/filter").route( web::get().to( payment_methods::list_countries_currencies_for_connector_payment_method, ), )); } #[cfg(feature = "oltp")] { route = route .service( web::resource("") .route(web::post().to(payment_methods::create_payment_method_api)), ) .service( web::resource("/create-intent") .route(web::post().to(payment_methods::create_payment_method_intent_api)), ) .service( web::resource("/{payment_method_id}/check-network-token-status") .route(web::get().to(payment_methods::network_token_status_check_api)), ); route = route.service( web::scope("/{id}") .service( web::resource("") .route(web::get().to(payment_methods::payment_method_retrieve_api)) .route(web::delete().to(payment_methods::payment_method_delete_api)), ) .service(web::resource("/list-enabled-payment-methods").route( web::get().to(payment_methods::payment_method_session_list_payment_methods), )) .service( web::resource("/update-saved-payment-method") .route(web::put().to(payment_methods::payment_method_update_api)), ) .service( web::resource("/get-token") .route(web::get().to(payment_methods::get_payment_method_token_data)), ), ); } route } } pub struct PaymentMethods; #[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))] impl PaymentMethods { pub fn server(state: AppState) -> Scope { let mut route = web::scope("/payment_methods").app_data(web::Data::new(state)); #[cfg(feature = "olap")] { route = route.service(web::resource("/filter").route( web::get().to( payment_methods::list_countries_currencies_for_connector_payment_method, ), )); } #[cfg(feature = "oltp")] { route = route .service( web::resource("") .route(web::post().to(payment_methods::create_payment_method_api)) .route(web::get().to(payment_methods::list_payment_method_api)), // TODO : added for sdk compatibility for now, need to deprecate this later ) .service( web::resource("/migrate") .route(web::post().to(payment_methods::migrate_payment_method_api)), ) .service( web::resource("/migrate-batch") .route(web::post().to(payment_methods::migrate_payment_methods)), ) .service( web::resource("/update-batch") .route(web::post().to(payment_methods::update_payment_methods)), ) .service( web::resource("/tokenize-card") .route(web::post().to(payment_methods::tokenize_card_api)), ) .service( web::resource("/tokenize-card-batch") .route(web::post().to(payment_methods::tokenize_card_batch_api)), ) .service( web::resource("/collect") .route(web::post().to(payment_methods::initiate_pm_collect_link_flow)), ) .service( web::resource("/collect/{merchant_id}/{collect_id}") .route(web::get().to(payment_methods::render_pm_collect_link)), ) .service( web::resource("/{payment_method_id}") .route(web::get().to(payment_methods::payment_method_retrieve_api)) .route(web::delete().to(payment_methods::payment_method_delete_api)), ) .service( web::resource("/{payment_method_id}/tokenize-card") .route(web::post().to(payment_methods::tokenize_card_using_pm_api)), ) .service( web::resource("/{payment_method_id}/update") .route(web::post().to(payment_methods::payment_method_update_api)), ) .service( web::resource("/{payment_method_id}/save") .route(web::post().to(payment_methods::save_payment_method_api)), ) .service( web::resource("/auth/link").route(web::post().to(pm_auth::link_token_create)), ) .service( web::resource("/auth/exchange").route(web::post().to(pm_auth::exchange_token)), ) } route } } #[cfg(all(feature = "v2", feature = "oltp"))] pub struct PaymentMethodSession; #[cfg(all(feature = "v2", feature = "oltp"))] impl PaymentMethodSession { pub fn server(state: AppState) -> Scope { let mut route = web::scope("/v2/payment-method-sessions").app_data(web::Data::new(state)); route = route.service( web::resource("") .route(web::post().to(payment_methods::payment_methods_session_create)), ); route = route.service( web::scope("/{payment_method_session_id}") .service( web::resource("") .route(web::get().to(payment_methods::payment_methods_session_retrieve)) .route(web::put().to(payment_methods::payment_methods_session_update)) .route(web::delete().to( payment_methods::payment_method_session_delete_saved_payment_method, )), ) .service(web::resource("/list-payment-methods").route( web::get().to(payment_methods::payment_method_session_list_payment_methods), )) .service( web::resource("/confirm") .route(web::post().to(payment_methods::payment_method_session_confirm)), ) .service(web::resource("/update-saved-payment-method").route( web::put().to( payment_methods::payment_method_session_update_saved_payment_method, ), )), ); route } } #[cfg(all(feature = "v2", feature = "oltp"))] pub struct Tokenization; #[cfg(all(feature = "v2", feature = "oltp"))] impl Tokenization { pub fn server(state: AppState) -> Scope { web::scope("/v2/tokenize") .app_data(web::Data::new(state)) .service( web::resource("") .route(web::post().to(tokenization_routes::create_token_vault_api)), ) .service( web::resource("/{id}") .route(web::delete().to(tokenization_routes::delete_tokenized_data_api)), ) } } #[cfg(all(feature = "olap", feature = "recon", feature = "v1"))] pub struct Recon; #[cfg(all(feature = "olap", feature = "recon", feature = "v1"))] impl Recon { pub fn server(state: AppState) -> Scope { web::scope("/recon") .app_data(web::Data::new(state)) .service( web::resource("/{merchant_id}/update") .route(web::post().to(recon_routes::update_merchant)), ) .service(web::resource("/token").route(web::get().to(recon_routes::get_recon_token))) .service( web::resource("/request").route(web::post().to(recon_routes::request_for_recon)), ) .service( web::resource("/verify_token") .route(web::get().to(recon_routes::verify_recon_token)), ) } } pub struct Hypersense; impl Hypersense { pub fn server(state: AppState) -> Scope { web::scope("/hypersense") .app_data(web::Data::new(state)) .service( web::resource("/token") .route(web::get().to(hypersense_routes::get_hypersense_token)), ) .service( web::resource("/verify_token") .route(web::post().to(hypersense_routes::verify_hypersense_token)), ) .service( web::resource("/signout") .route(web::post().to(hypersense_routes::signout_hypersense_token)), ) } } #[cfg(feature = "olap")] pub struct Blocklist; #[cfg(all(feature = "olap", feature = "v1"))] impl Blocklist { pub fn server(state: AppState) -> Scope { web::scope("/blocklist") .app_data(web::Data::new(state)) .service( web::resource("") .route(web::get().to(blocklist::list_blocked_payment_methods)) .route(web::post().to(blocklist::add_entry_to_blocklist)) .route(web::delete().to(blocklist::remove_entry_from_blocklist)), ) .service( web::resource("/toggle").route(web::post().to(blocklist::toggle_blocklist_guard)), ) } } #[cfg(feature = "olap")] pub struct Organization; #[cfg(all(feature = "olap", feature = "v1"))] impl Organization { pub fn server(state: AppState) -> Scope { web::scope("/organization") .app_data(web::Data::new(state)) .service(web::resource("").route(web::post().to(admin::organization_create))) .service( web::resource("/{id}") .route(web::get().to(admin::organization_retrieve)) .route(web::put().to(admin::organization_update)), ) } } #[cfg(all(feature = "v2", feature = "olap"))] impl Organization { pub fn server(state: AppState) -> Scope { web::scope("/v2/organizations") .app_data(web::Data::new(state)) .service(web::resource("").route(web::post().to(admin::organization_create))) .service( web::scope("/{id}") .service( web::resource("") .route(web::get().to(admin::organization_retrieve)) .route(web::put().to(admin::organization_update)), ) .service( web::resource("/merchant-accounts") .route(web::get().to(admin::merchant_account_list)), ), ) } } pub struct MerchantAccount; #[cfg(all(feature = "v2", feature = "olap"))] impl MerchantAccount { pub fn server(state: AppState) -> Scope { web::scope("/v2/merchant-accounts") .app_data(web::Data::new(state)) .service(web::resource("").route(web::post().to(admin::merchant_account_create))) .service( web::scope("/{id}") .service( web::resource("") .route(web::get().to(admin::retrieve_merchant_account)) .route(web::put().to(admin::update_merchant_account)), ) .service( web::resource("/profiles").route(web::get().to(profiles::profiles_list)), ) .service( web::resource("/kv") .route(web::post().to(admin::merchant_account_toggle_kv)) .route(web::get().to(admin::merchant_account_kv_status)), ), ) } } #[cfg(all(feature = "olap", feature = "v1"))] impl MerchantAccount { pub fn server(state: AppState) -> Scope { let mut routes = web::scope("/accounts") .service(web::resource("").route(web::post().to(admin::merchant_account_create))) .service(web::resource("/list").route(web::get().to(admin::merchant_account_list))) .service( web::resource("/{id}/kv") .route(web::post().to(admin::merchant_account_toggle_kv)) .route(web::get().to(admin::merchant_account_kv_status)), ) .service( web::resource("/transfer") .route(web::post().to(admin::merchant_account_transfer_keys)), ) .service( web::resource("/kv").route(web::post().to(admin::merchant_account_toggle_all_kv)), ) .service( web::resource("/{id}") .route(web::get().to(admin::retrieve_merchant_account)) .route(web::post().to(admin::update_merchant_account)) .route(web::delete().to(admin::delete_merchant_account)), ); if state.conf.platform.enabled { routes = routes.service( web::resource("/{id}/platform") .route(web::post().to(admin::merchant_account_enable_platform_account)), ) } routes.app_data(web::Data::new(state)) } } pub struct MerchantConnectorAccount; #[cfg(all(any(feature = "olap", feature = "oltp"), feature = "v2"))] impl MerchantConnectorAccount { pub fn server(state: AppState) -> Scope { let mut route = web::scope("/v2/connector-accounts").app_data(web::Data::new(state)); #[cfg(feature = "olap")] { use super::admin::*; route = route .service(web::resource("").route(web::post().to(connector_create))) .service( web::resource("/{id}") .route(web::put().to(connector_update)) .route(web::get().to(connector_retrieve)) .route(web::delete().to(connector_delete)), ); } route } } #[cfg(all(any(feature = "olap", feature = "oltp"), feature = "v1"))] impl MerchantConnectorAccount { pub fn server(state: AppState) -> Scope { let mut route = web::scope("/account").app_data(web::Data::new(state)); #[cfg(feature = "olap")] { use super::admin::*; route = route .service( web::resource("/connectors/verify") .route(web::post().to(super::verify_connector::payment_connector_verify)), ) .service( web::resource("/{merchant_id}/connectors") .route(web::post().to(connector_create)) .route(web::get().to(connector_list)), ) .service( web::resource("/{merchant_id}/connectors/{merchant_connector_id}") .route(web::get().to(connector_retrieve)) .route(web::post().to(connector_update)) .route(web::delete().to(connector_delete)), ); } #[cfg(feature = "oltp")] { route = route.service( web::resource("/payment_methods") .route(web::get().to(payment_methods::list_payment_method_api)), ); } route } } pub struct EphemeralKey; #[cfg(all(feature = "v1", feature = "oltp"))] impl EphemeralKey { pub fn server(config: AppState) -> Scope { web::scope("/ephemeral_keys") .app_data(web::Data::new(config)) .service(web::resource("").route(web::post().to(ephemeral_key_create))) .service(web::resource("/{id}").route(web::delete().to(ephemeral_key_delete))) } } #[cfg(feature = "v2")] impl EphemeralKey { pub fn server(config: AppState) -> Scope { web::scope("/v2/client-secret") .app_data(web::Data::new(config)) .service(web::resource("").route(web::post().to(client_secret_create))) .service(web::resource("/{id}").route(web::delete().to(client_secret_delete))) } } pub struct Mandates; #[cfg(all(any(feature = "olap", feature = "oltp"), feature = "v1"))] impl Mandates { pub fn server(state: AppState) -> Scope { let mut route = web::scope("/mandates").app_data(web::Data::new(state)); #[cfg(feature = "olap")] { route = route.service(web::resource("/list").route(web::get().to(retrieve_mandates_list))); route = route.service(web::resource("/{id}").route(web::get().to(get_mandate))); } #[cfg(feature = "oltp")] { route = route.service(web::resource("/revoke/{id}").route(web::post().to(revoke_mandate))); } route } } pub struct Webhooks; #[cfg(all(feature = "oltp", feature = "v1"))] impl Webhooks { pub fn server(config: AppState) -> Scope { use api_models::webhooks as webhook_type; #[allow(unused_mut)] let mut route = web::scope("/webhooks") .app_data(web::Data::new(config)) .service( web::resource("/network_token_requestor/ref") .route( web::post().to(receive_network_token_requestor_incoming_webhook::< webhook_type::OutgoingWebhook, >), ) .route( web::get().to(receive_network_token_requestor_incoming_webhook::< webhook_type::OutgoingWebhook, >), ) .route( web::put().to(receive_network_token_requestor_incoming_webhook::< webhook_type::OutgoingWebhook, >), ), ) .service( web::resource("/{merchant_id}/{connector_id_or_name}") .route( web::post().to(receive_incoming_webhook::<webhook_type::OutgoingWebhook>), ) .route(web::get().to(receive_incoming_webhook::<webhook_type::OutgoingWebhook>)) .route( web::put().to(receive_incoming_webhook::<webhook_type::OutgoingWebhook>), ), ); #[cfg(feature = "frm")] { route = route.service( web::resource("/frm_fulfillment") .route(web::post().to(frm_routes::frm_fulfillment)), ); } route } } pub struct RelayWebhooks; #[cfg(feature = "oltp")] impl RelayWebhooks { pub fn server(state: AppState) -> Scope { use api_models::webhooks as webhook_type; web::scope("/webhooks/relay") .app_data(web::Data::new(state)) .service(web::resource("/{merchant_id}/{connector_id}").route( web::post().to(receive_incoming_relay_webhook::<webhook_type::OutgoingWebhook>), )) } } #[cfg(all(feature = "oltp", feature = "v2"))] impl Webhooks { pub fn server(config: AppState) -> Scope { use api_models::webhooks as webhook_type; #[allow(unused_mut)] let mut route = web::scope("/v2/webhooks") .app_data(web::Data::new(config)) .service( web::resource("/{merchant_id}/{profile_id}/{connector_id}") .route( web::post().to(receive_incoming_webhook::<webhook_type::OutgoingWebhook>), ) .route(web::get().to(receive_incoming_webhook::<webhook_type::OutgoingWebhook>)) .route( web::put().to(receive_incoming_webhook::<webhook_type::OutgoingWebhook>), ), ); #[cfg(all(feature = "revenue_recovery", feature = "v2"))] { route = route.service( web::resource("/recovery/{merchant_id}/{profile_id}/{connector_id}").route( web::post() .to(recovery_receive_incoming_webhook::<webhook_type::OutgoingWebhook>), ), ); } route } } pub struct Configs; #[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))] impl Configs { pub fn server(config: AppState) -> Scope { web::scope("/configs") .app_data(web::Data::new(config)) .service(web::resource("/").route(web::post().to(config_key_create))) .service( web::resource("/{key}") .route(web::get().to(config_key_retrieve)) .route(web::post().to(config_key_update)) .route(web::delete().to(config_key_delete)), ) } } #[cfg(all(feature = "v2", any(feature = "olap", feature = "oltp")))] impl Configs { pub fn server(config: AppState) -> Scope { web::scope("/v2/configs") .app_data(web::Data::new(config)) .service(web::resource("/").route(web::post().to(config_key_create))) .service( web::resource("/{key}") .route(web::get().to(config_key_retrieve)) .route(web::post().to(config_key_update)) .route(web::delete().to(config_key_delete)), ) } } pub struct ApplePayCertificatesMigration; #[cfg(all(feature = "olap", feature = "v1"))] impl ApplePayCertificatesMigration { pub fn server(state: AppState) -> Scope { web::scope("/apple_pay_certificates_migration") .app_data(web::Data::new(state)) .service(web::resource("").route( web::post().to(apple_pay_certificates_migration::apple_pay_certificates_migration), )) } } pub struct Poll; #[cfg(all(feature = "oltp", feature = "v1"))] impl Poll { pub fn server(config: AppState) -> Scope { web::scope("/poll") .app_data(web::Data::new(config)) .service( web::resource("/status/{poll_id}").route(web::get().to(poll::retrieve_poll_status)), ) } } pub struct ApiKeys; #[cfg(all(feature = "olap", feature = "v2"))] impl ApiKeys { pub fn server(state: AppState) -> Scope { web::scope("/v2/api-keys") .app_data(web::Data::new(state)) .service(web::resource("").route(web::post().to(api_keys::api_key_create))) .service(web::resource("/list").route(web::get().to(api_keys::api_key_list))) .service( web::resource("/{key_id}") .route(web::get().to(api_keys::api_key_retrieve)) .route(web::put().to(api_keys::api_key_update)) .route(web::delete().to(api_keys::api_key_revoke)), ) } } #[cfg(all(feature = "olap", feature = "v1"))] impl ApiKeys { pub fn server(state: AppState) -> Scope { web::scope("/api_keys/{merchant_id}") .app_data(web::Data::new(state)) .service(web::resource("").route(web::post().to(api_keys::api_key_create))) .service(web::resource("/list").route(web::get().to(api_keys::api_key_list))) .service( web::resource("/{key_id}") .route(web::get().to(api_keys::api_key_retrieve)) .route(web::post().to(api_keys::api_key_update)) .route(web::delete().to(api_keys::api_key_revoke)), ) } } pub struct Disputes; #[cfg(all(feature = "olap", feature = "v1"))] impl Disputes { pub fn server(state: AppState) -> Scope { web::scope("/disputes") .app_data(web::Data::new(state)) .service(web::resource("/list").route(web::get().to(disputes::retrieve_disputes_list))) .service( web::resource("/profile/list") .route(web::get().to(disputes::retrieve_disputes_list_profile)), ) .service(web::resource("/filter").route(web::get().to(disputes::get_disputes_filters))) .service( web::resource("/profile/filter") .route(web::get().to(disputes::get_disputes_filters_profile)), ) .service( web::resource("/accept/{dispute_id}") .route(web::post().to(disputes::accept_dispute)), ) .service( web::resource("/aggregate").route(web::get().to(disputes::get_disputes_aggregate)), ) .service( web::resource("/profile/aggregate") .route(web::get().to(disputes::get_disputes_aggregate_profile)), ) .service( web::resource("/evidence") .route(web::post().to(disputes::submit_dispute_evidence)) .route(web::put().to(disputes::attach_dispute_evidence)) .route(web::delete().to(disputes::delete_dispute_evidence)), ) .service( web::resource("/evidence/{dispute_id}") .route(web::get().to(disputes::retrieve_dispute_evidence)), ) .service( web::resource("/{dispute_id}").route(web::get().to(disputes::retrieve_dispute)), ) .service( web::resource("/{connector_id}/fetch") .route(web::get().to(disputes::fetch_disputes)), ) } } pub struct Cards; #[cfg(all(feature = "oltp", feature = "v1"))] impl Cards { pub fn server(state: AppState) -> Scope { web::scope("/cards") .app_data(web::Data::new(state)) .service(web::resource("/create").route(web::post().to(create_cards_info))) .service(web::resource("/update").route(web::post().to(update_cards_info))) .service(web::resource("/update-batch").route(web::post().to(migrate_cards_info))) .service(web::resource("/{bin}").route(web::get().to(card_iin_info))) } } pub struct Files; #[cfg(all(feature = "olap", feature = "v1"))] impl Files { pub fn server(state: AppState) -> Scope { web::scope("/files") .app_data(web::Data::new(state)) .service(web::resource("").route(web::post().to(files::files_create))) .service( web::resource("/{file_id}") .route(web::delete().to(files::files_delete)) .route(web::get().to(files::files_retrieve)), ) } } pub struct Cache; impl Cache { pub fn server(state: AppState) -> Scope { web::scope("/cache") .app_data(web::Data::new(state)) .service(web::resource("/invalidate/{key}").route(web::post().to(invalidate))) } } pub struct PaymentLink; #[cfg(all(feature = "olap", feature = "v1"))] impl PaymentLink { pub fn server(state: AppState) -> Scope { web::scope("/payment_link") .app_data(web::Data::new(state)) .service(web::resource("/list").route(web::post().to(payment_link::payments_link_list))) .service( web::resource("/{payment_link_id}") .route(web::get().to(payment_link::payment_link_retrieve)), ) .service( web::resource("{merchant_id}/{payment_id}") .route(web::get().to(payment_link::initiate_payment_link)), ) .service( web::resource("s/{merchant_id}/{payment_id}") .route(web::get().to(payment_link::initiate_secure_payment_link)), ) .service( web::resource("status/{merchant_id}/{payment_id}") .route(web::get().to(payment_link::payment_link_status)), ) } } #[cfg(feature = "payouts")] pub struct PayoutLink; #[cfg(all(feature = "payouts", feature = "v1"))] impl PayoutLink { pub fn server(state: AppState) -> Scope { let mut route = web::scope("/payout_link").app_data(web::Data::new(state)); route = route.service( web::resource("/{merchant_id}/{payout_id}").route(web::get().to(render_payout_link)), ); route } } pub struct Profile; #[cfg(all(feature = "olap", feature = "v2"))] impl Profile { pub fn server(state: AppState) -> Scope { web::scope("/v2/profiles") .app_data(web::Data::new(state)) .service(web::resource("").route(web::post().to(profiles::profile_create))) .service( web::scope("/{profile_id}") .service( web::resource("") .route(web::get().to(profiles::profile_retrieve)) .route(web::put().to(profiles::profile_update)), ) .service( web::resource("/connector-accounts") .route(web::get().to(admin::connector_list)), ) .service( web::resource("/fallback-routing") .route(web::get().to(routing::routing_retrieve_default_config)) .route(web::patch().to(routing::routing_update_default_config)), ) .service( web::resource("/activate-routing-algorithm").route(web::patch().to( |state, req, path, payload| { routing::routing_link_config( state, req, path, payload, &TransactionType::Payment, ) }, )), ) .service( web::resource("/deactivate-routing-algorithm").route(web::patch().to( |state, req, path| { routing::routing_unlink_config( state, req, path, &TransactionType::Payment, ) }, )), ) .service(web::resource("/routing-algorithm").route(web::get().to( |state, req, query_params, path| { routing::routing_retrieve_linked_config( state, req, query_params, path, &TransactionType::Payment, ) }, ))) .service( web::resource("/decision") .route(web::put().to(routing::upsert_decision_manager_config)) .route(web::get().to(routing::retrieve_decision_manager_config)), ), ) } } #[cfg(all(feature = "olap", feature = "v1"))] impl Profile { pub fn server(state: AppState) -> Scope { let mut route = web::scope("/account/{account_id}/business_profile") .app_data(web::Data::new(state)) .service( web::resource("") .route(web::post().to(profiles::profile_create)) .route(web::get().to(profiles::profiles_list)), ); #[cfg(feature = "dynamic_routing")] { route = route.service( web::scope("/{profile_id}/dynamic_routing") .service( web::scope("/success_based") .service( web::resource("/toggle") .route(web::post().to(routing::toggle_success_based_routing)), ) .service( web::resource("/create") .route(web::post().to(routing::create_success_based_routing)), ) .service(web::resource("/config/{algorithm_id}").route( web::patch().to(|state, req, path, payload| { routing::success_based_routing_update_configs( state, req, path, payload, ) }), )), ) .service( web::resource("/set_volume_split") .route(web::post().to(routing::set_dynamic_routing_volume_split)), ) .service( web::resource("/get_volume_split") .route(web::get().to(routing::get_dynamic_routing_volume_split)), ) .service( web::scope("/elimination") .service( web::resource("/toggle") .route(web::post().to(routing::toggle_elimination_routing)), ) .service( web::resource("/create") .route(web::post().to(routing::create_elimination_routing)), ) .service(web::resource("config/{algorithm_id}").route( web::patch().to(|state, req, path, payload| { routing::elimination_routing_update_configs( state, req, path, payload, ) }), )), ) .service( web::scope("/contracts") .service(web::resource("/toggle").route( web::post().to(routing::contract_based_routing_setup_config), )) .service(web::resource("/config/{algorithm_id}").route( web::patch().to(|state, req, path, payload| { routing::contract_based_routing_update_configs( state, req, path, payload, ) }), )), ), ); } route = route.service( web::scope("/{profile_id}") .service( web::resource("") .route(web::get().to(profiles::profile_retrieve)) .route(web::post().to(profiles::profile_update)) .route(web::delete().to(profiles::profile_delete)), ) .service( web::resource("/toggle_extended_card_info") .route(web::post().to(profiles::toggle_extended_card_info)), ) .service( web::resource("/toggle_connector_agnostic_mit") .route(web::post().to(profiles::toggle_connector_agnostic_mit)), ), ); route } } pub struct ProfileNew; #[cfg(feature = "olap")] impl ProfileNew { #[cfg(feature = "v1")] pub fn server(state: AppState) -> Scope { web::scope("/account/{account_id}/profile") .app_data(web::Data::new(state)) .service( web::resource("").route(web::get().to(profiles::profiles_list_at_profile_level)), ) .service( web::resource("/connectors").route(web::get().to(admin::connector_list_profile)), ) } #[cfg(feature = "v2")] pub fn server(state: AppState) -> Scope { web::scope("/account/{account_id}/profile").app_data(web::Data::new(state)) } } pub struct Gsm; #[cfg(all(feature = "v1", feature = "olap"))] impl Gsm { pub fn server(state: AppState) -> Scope { web::scope("/gsm") .app_data(web::Data::new(state)) .service(web::resource("").route(web::post().to(gsm::create_gsm_rule))) .service(web::resource("/get").route(web::post().to(gsm::get_gsm_rule))) .service(web::resource("/update").route(web::post().to(gsm::update_gsm_rule))) .service(web::resource("/delete").route(web::post().to(gsm::delete_gsm_rule))) } } #[cfg(all(feature = "v2", feature = "olap"))] impl Gsm { pub fn server(state: AppState) -> Scope { web::scope("/v2/gsm") .app_data(web::Data::new(state)) .service(web::resource("").route(web::post().to(gsm::create_gsm_rule))) .service(web::resource("/get").route(web::post().to(gsm::get_gsm_rule))) .service(web::resource("/update").route(web::post().to(gsm::update_gsm_rule))) .service(web::resource("/delete").route(web::post().to(gsm::delete_gsm_rule))) } } pub struct Chat; #[cfg(feature = "olap")] impl Chat { pub fn server(state: AppState) -> Scope { let mut route = web::scope("/chat").app_data(web::Data::new(state.clone())); if state.conf.chat.get_inner().enabled { route = route.service( web::scope("/ai") .service( web::resource("/data") .route(web::post().to(chat::get_data_from_hyperswitch_ai_workflow)), ) .service( web::resource("/list").route(web::get().to(chat::get_all_conversations)), ), ); } route } } pub struct ThreeDsDecisionRule; #[cfg(feature = "oltp")] impl ThreeDsDecisionRule { pub fn server(state: AppState) -> Scope { web::scope("/three_ds_decision") .app_data(web::Data::new(state)) .service( web::resource("/execute") .route(web::post().to(three_ds_decision_rule::execute_decision_rule)), ) } } #[cfg(feature = "olap")] pub struct Verify; #[cfg(all(feature = "olap", feature = "v1"))] impl Verify { pub fn server(state: AppState) -> Scope { web::scope("/verify") .app_data(web::Data::new(state)) .service( web::resource("/apple_pay/{merchant_id}") .route(web::post().to(apple_pay_merchant_registration)), ) .service( web::resource("/applepay_verified_domains") .route(web::get().to(retrieve_apple_pay_verified_domains)), ) } } #[cfg(all(feature = "olap", feature = "v2"))] impl Verify { pub fn server(state: AppState) -> Scope { web::scope("/v2/verify") .app_data(web::Data::new(state)) .service( web::resource("/apple-pay/{merchant_id}") .route(web::post().to(apple_pay_merchant_registration)), ) .service( web::resource("/applepay-verified-domains") .route(web::get().to(retrieve_apple_pay_verified_domains)), ) } } pub struct UserDeprecated; #[cfg(all(feature = "olap", feature = "v2"))] impl UserDeprecated { pub fn server(state: AppState) -> Scope { // TODO: Deprecated. Remove this in favour of /v2/users let mut route = web::scope("/v2/user").app_data(web::Data::new(state)); route = route.service( web::resource("/create_merchant") .route(web::post().to(user::user_merchant_account_create)), ); route = route.service( web::scope("/list") .service( web::resource("/merchant") .route(web::get().to(user::list_merchants_for_user_in_org)), ) .service( web::resource("/profile") .route(web::get().to(user::list_profiles_for_user_in_org_and_merchant)), ), ); route = route.service( web::scope("/switch") .service( web::resource("/merchant") .route(web::post().to(user::switch_merchant_for_user_in_org)), ) .service( web::resource("/profile") .route(web::post().to(user::switch_profile_for_user_in_org_and_merchant)), ), ); route = route.service( web::resource("/data") .route(web::get().to(user::get_multiple_dashboard_metadata)) .route(web::post().to(user::set_dashboard_metadata)), ); route } } pub struct User; #[cfg(all(feature = "olap", feature = "v2"))] impl User { pub fn server(state: AppState) -> Scope { let mut route = web::scope("/v2/users").app_data(web::Data::new(state)); route = route.service( web::resource("/create-merchant") .route(web::post().to(user::user_merchant_account_create)), ); route = route.service( web::scope("/list") .service( web::resource("/merchant") .route(web::get().to(user::list_merchants_for_user_in_org)), ) .service( web::resource("/profile") .route(web::get().to(user::list_profiles_for_user_in_org_and_merchant)), ), ); route = route.service( web::scope("/switch") .service( web::resource("/merchant") .route(web::post().to(user::switch_merchant_for_user_in_org)), ) .service( web::resource("/profile") .route(web::post().to(user::switch_profile_for_user_in_org_and_merchant)), ), ); route = route.service( web::resource("/data") .route(web::get().to(user::get_multiple_dashboard_metadata)) .route(web::post().to(user::set_dashboard_metadata)), ); route } } #[cfg(all(feature = "olap", feature = "v1"))] impl User { pub fn server(state: AppState) -> Scope { let mut route = web::scope("/user").app_data(web::Data::new(state.clone())); route = route .service(web::resource("").route(web::get().to(user::get_user_details))) .service(web::resource("/signin").route(web::post().to(user::user_signin))) .service(web::resource("/v2/signin").route(web::post().to(user::user_signin))) // signin/signup with sso using openidconnect .service(web::resource("/oidc").route(web::post().to(user::sso_sign))) .service(web::resource("/signout").route(web::post().to(user::signout))) .service(web::resource("/rotate_password").route(web::post().to(user::rotate_password))) .service(web::resource("/change_password").route(web::post().to(user::change_password))) .service( web::resource("/internal_signup").route(web::post().to(user::internal_user_signup)), ) .service( web::resource("/tenant_signup").route(web::post().to(user::create_tenant_user)), ) .service(web::resource("/create_org").route(web::post().to(user::user_org_create))) .service( web::resource("/create_merchant") .route(web::post().to(user::user_merchant_account_create)), ) // TODO: To be deprecated .service( web::resource("/permission_info") .route(web::get().to(user_role::get_authorization_info)), ) // TODO: To be deprecated .service( web::resource("/module/list").route(web::get().to(user_role::get_role_information)), ) .service( web::resource("/parent/list") .route(web::get().to(user_role::get_parent_group_info)), ) .service( web::resource("/update").route(web::post().to(user::update_user_account_details)), ) .service( web::resource("/data") .route(web::get().to(user::get_multiple_dashboard_metadata)) .route(web::post().to(user::set_dashboard_metadata)), ); if state.conf.platform.enabled { route = route.service( web::resource("/create_platform").route(web::post().to(user::create_platform)), ) } route = route .service(web::scope("/key").service( web::resource("/transfer").route(web::post().to(user::transfer_user_key)), )); route = route.service( web::scope("/list") .service(web::resource("/org").route(web::get().to(user::list_orgs_for_user))) .service( web::resource("/merchant") .route(web::get().to(user::list_merchants_for_user_in_org)), ) .service( web::resource("/profile") .route(web::get().to(user::list_profiles_for_user_in_org_and_merchant)), ) .service( web::resource("/invitation") .route(web::get().to(user_role::list_invitations_for_user)), ), ); route = route.service( web::scope("/switch") .service(web::resource("/org").route(web::post().to(user::switch_org_for_user))) .service( web::resource("/merchant") .route(web::post().to(user::switch_merchant_for_user_in_org)), ) .service( web::resource("/profile") .route(web::post().to(user::switch_profile_for_user_in_org_and_merchant)), ), ); // Two factor auth routes route = route.service( web::scope("/2fa") // TODO: to be deprecated .service(web::resource("").route(web::get().to(user::check_two_factor_auth_status))) .service( web::resource("/v2") .route(web::get().to(user::check_two_factor_auth_status_with_attempts)), ) .service( web::scope("/totp") .service(web::resource("/begin").route(web::get().to(user::totp_begin))) .service(web::resource("/reset").route(web::get().to(user::totp_reset))) .service( web::resource("/verify") .route(web::post().to(user::totp_verify)) .route(web::put().to(user::totp_update)), ), ) .service( web::scope("/recovery_code") .service( web::resource("/verify") .route(web::post().to(user::verify_recovery_code)), ) .service( web::resource("/generate") .route(web::get().to(user::generate_recovery_codes)), ), ) .service( web::resource("/terminate") .route(web::get().to(user::terminate_two_factor_auth)), ), ); route = route.service( web::scope("/auth") .service( web::resource("") .route(web::post().to(user::create_user_authentication_method)) .route(web::put().to(user::update_user_authentication_method)), ) .service( web::resource("/list") .route(web::get().to(user::list_user_authentication_methods)), ) .service(web::resource("/url").route(web::get().to(user::get_sso_auth_url))) .service( web::resource("/select").route(web::post().to(user::terminate_auth_select)), ), ); #[cfg(feature = "email")] { route = route .service(web::resource("/from_email").route(web::post().to(user::user_from_email))) .service( web::resource("/connect_account") .route(web::post().to(user::user_connect_account)), ) .service( web::resource("/forgot_password").route(web::post().to(user::forgot_password)), ) .service( web::resource("/reset_password").route(web::post().to(user::reset_password)), ) .service( web::resource("/signup_with_merchant_id") .route(web::post().to(user::user_signup_with_merchant_id)), ) .service(web::resource("/verify_email").route(web::post().to(user::verify_email))) .service( web::resource("/v2/verify_email").route(web::post().to(user::verify_email)), ) .service( web::resource("/verify_email_request") .route(web::post().to(user::verify_email_request)), ) .service( web::resource("/user/resend_invite").route(web::post().to(user::resend_invite)), ) .service( web::resource("/accept_invite_from_email") .route(web::post().to(user::accept_invite_from_email)), ); } #[cfg(not(feature = "email"))] { route = route.service(web::resource("/signup").route(web::post().to(user::user_signup))) } // User management route = route.service( web::scope("/user") .service(web::resource("").route(web::post().to(user::list_user_roles_details))) // TODO: To be deprecated .service(web::resource("/v2").route(web::post().to(user::list_user_roles_details))) .service( web::resource("/list").route(web::get().to(user_role::list_users_in_lineage)), ) // TODO: To be deprecated .service( web::resource("/v2/list") .route(web::get().to(user_role::list_users_in_lineage)), ) .service( web::resource("/invite_multiple") .route(web::post().to(user::invite_multiple_user)), ) .service( web::scope("/invite/accept") .service( web::resource("") .route(web::post().to(user_role::accept_invitations_v2)), ) .service( web::resource("/pre_auth") .route(web::post().to(user_role::accept_invitations_pre_auth)), ) .service( web::scope("/v2") .service( web::resource("") .route(web::post().to(user_role::accept_invitations_v2)), ) .service( web::resource("/pre_auth").route( web::post().to(user_role::accept_invitations_pre_auth), ), ), ), ) .service( web::resource("/update_role") .route(web::post().to(user_role::update_user_role)), ) .service( web::resource("/delete").route(web::delete().to(user_role::delete_user_role)), ), ); if state.conf().clone_connector_allowlist.is_some() { route = route.service( web::resource("/clone_connector").route(web::post().to(user::clone_connector)), ); } // Role information route = route.service( web::scope("/role") .service( web::resource("") .route(web::get().to(user_role::get_role_from_token)) // TODO: To be deprecated .route(web::post().to(user_role::create_role)), ) .service( web::resource("/v2") .route(web::post().to(user_role::create_role_v2)) .route( web::get() .to(user_role::get_groups_and_resources_for_role_from_token), ), ) .service(web::resource("/v3").route( web::get().to(user_role::get_parent_groups_info_for_role_from_token), )) // TODO: To be deprecated .service( web::resource("/v2/list") .route(web::get().to(user_role::list_roles_with_info)), ) .service( web::scope("/list") .service( web::resource("") .route(web::get().to(user_role::list_roles_with_info)), ) .service(web::resource("/invite").route( web::get().to(user_role::list_invitable_roles_at_entity_level), )) .service(web::resource("/update").route( web::get().to(user_role::list_updatable_roles_at_entity_level), )), ) .service( web::resource("/{role_id}") .route(web::get().to(user_role::get_role)) .route(web::put().to(user_role::update_role)), ) .service( web::resource("/{role_id}/v2") .route(web::get().to(user_role::get_parent_info_for_role)), ), ); #[cfg(feature = "dummy_connector")] { route = route.service( web::resource("/sample_data") .route(web::post().to(user::generate_sample_data)) .route(web::delete().to(user::delete_sample_data)), ) } // Admin Theme // TODO: To be deprecated route = route.service( web::scope("/admin/theme") .service( web::resource("") .route(web::get().to(user::theme::get_theme_using_lineage)) .route(web::post().to(user::theme::create_theme)), ) .service( web::resource("/{theme_id}") .route(web::get().to(user::theme::get_theme_using_theme_id)) .route(web::put().to(user::theme::update_theme)) .route(web::post().to(user::theme::upload_file_to_theme_storage)) .route(web::delete().to(user::theme::delete_theme)), ), ); // User Theme route = route.service( web::scope("/theme") .service( web::resource("") .route(web::post().to(user::theme::create_user_theme)) .route(web::get().to(user::theme::get_user_theme_using_lineage)), ) .service( web::resource("/list") .route(web::get().to(user::theme::list_all_themes_in_lineage)), ) .service( web::resource("/{theme_id}") .route(web::get().to(user::theme::get_user_theme_using_theme_id)) .route(web::put().to(user::theme::update_user_theme)) .route(web::post().to(user::theme::upload_file_to_user_theme_storage)) .route(web::delete().to(user::theme::delete_user_theme)), ), ); route } } pub struct ConnectorOnboarding; #[cfg(all(feature = "olap", feature = "v1"))] impl ConnectorOnboarding { pub fn server(state: AppState) -> Scope { web::scope("/connector_onboarding") .app_data(web::Data::new(state)) .service( web::resource("/action_url") .route(web::post().to(connector_onboarding::get_action_url)), ) .service( web::resource("/sync") .route(web::post().to(connector_onboarding::sync_onboarding_status)), ) .service( web::resource("/reset_tracking_id") .route(web::post().to(connector_onboarding::reset_tracking_id)), ) } } #[cfg(feature = "olap")] pub struct WebhookEvents; #[cfg(all(feature = "olap", feature = "v1"))] impl WebhookEvents { pub fn server(config: AppState) -> Scope { web::scope("/events") .app_data(web::Data::new(config)) .service(web::scope("/profile/list").service(web::resource("").route( web::post().to(webhook_events::list_initial_webhook_delivery_attempts_with_jwtauth), ))) .service( web::scope("/{merchant_id}") .service(web::resource("").route( web::post().to(webhook_events::list_initial_webhook_delivery_attempts), )) .service( web::scope("/{event_id}") .service(web::resource("attempts").route( web::get().to(webhook_events::list_webhook_delivery_attempts), )) .service(web::resource("retry").route( web::post().to(webhook_events::retry_webhook_delivery_attempt), )), ), ) } } #[cfg(feature = "olap")] pub struct FeatureMatrix; #[cfg(all(feature = "olap", feature = "v1"))] impl FeatureMatrix { pub fn server(state: AppState) -> Scope { web::scope("/feature_matrix") .app_data(web::Data::new(state)) .service(web::resource("").route(web::get().to(feature_matrix::fetch_feature_matrix))) } } #[cfg(feature = "olap")] pub struct ProcessTrackerDeprecated; #[cfg(all(feature = "olap", feature = "v2"))] impl ProcessTrackerDeprecated { pub fn server(state: AppState) -> Scope { use super::process_tracker::revenue_recovery; // TODO: Deprecated. Remove this in favour of /v2/process-trackers web::scope("/v2/process_tracker/revenue_recovery_workflow") .app_data(web::Data::new(state.clone())) .service( web::resource("/{revenue_recovery_id}") .route(web::get().to(revenue_recovery::revenue_recovery_pt_retrieve_api)), ) } } #[cfg(feature = "olap")] pub struct ProcessTracker; #[cfg(all(feature = "olap", feature = "v2"))] impl ProcessTracker { pub fn server(state: AppState) -> Scope { use super::process_tracker::revenue_recovery; web::scope("/v2/process-trackers/revenue-recovery-workflow") .app_data(web::Data::new(state.clone())) .service( web::scope("/{revenue_recovery_id}") .service( web::resource("").route( web::get().to(revenue_recovery::revenue_recovery_pt_retrieve_api), ), ) .service( web::resource("/resume") .route(web::post().to(revenue_recovery::revenue_recovery_resume_api)), ), ) } } pub struct Authentication; #[cfg(feature = "v1")] impl Authentication { pub fn server(state: AppState) -> Scope { web::scope("/authentication") .app_data(web::Data::new(state)) .service(web::resource("").route(web::post().to(authentication::authentication_create))) .service( web::resource("/{authentication_id}/eligibility") .route(web::post().to(authentication::authentication_eligibility)), ) .service( web::resource("/{authentication_id}/authenticate") .route(web::post().to(authentication::authentication_authenticate)), ) .service( web::resource("{merchant_id}/{authentication_id}/redirect") .route(web::post().to(authentication::authentication_sync_post_update)), ) .service( web::resource("{merchant_id}/{authentication_id}/sync") .route(web::post().to(authentication::authentication_sync)), ) } } #[cfg(feature = "olap")] pub struct ProfileAcquirer; #[cfg(all(feature = "olap", feature = "v1"))] impl ProfileAcquirer { pub fn server(state: AppState) -> Scope { web::scope("/profile_acquirer") .app_data(web::Data::new(state)) .service( web::resource("").route(web::post().to(profile_acquirer::create_profile_acquirer)), ) .service( web::resource("/{profile_id}/{profile_acquirer_id}") .route(web::post().to(profile_acquirer::profile_acquirer_update)), ) } } #[cfg(feature = "v2")] pub struct RecoveryDataBackfill; #[cfg(feature = "v2")] impl RecoveryDataBackfill { pub fn server(state: AppState) -> Scope { web::scope("/v2/recovery/data-backfill") .app_data(web::Data::new(state)) .service( web::resource("").route( web::post() .to(super::revenue_recovery_data_backfill::revenue_recovery_data_backfill), ), ) .service(web::resource("/status/{token_id}").route( web::post().to( super::revenue_recovery_data_backfill::revenue_recovery_data_backfill_status, ), )) .service(web::resource("/redis-data/{token_id}").route( web::get().to( super::revenue_recovery_redis::get_revenue_recovery_redis_data, ), )) .service(web::resource("/update-token").route( web::put().to( super::revenue_recovery_data_backfill::update_revenue_recovery_additional_redis_data, ), )) } }
crates/router/src/routes/app.rs
router::src::routes::app
24,662
true
// File: crates/router/src/routes/apple_pay_certificates_migration.rs // Module: router::src::routes::apple_pay_certificates_migration use actix_web::{web, HttpRequest, HttpResponse}; use router_env::Flow; use super::AppState; use crate::{ core::{api_locking, apple_pay_certificates_migration}, services::{api, authentication as auth}, }; pub async fn apple_pay_certificates_migration( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json< api_models::apple_pay_certificates_migration::ApplePayCertificatesMigrationRequest, >, ) -> HttpResponse { let flow = Flow::ApplePayCertificatesMigration; Box::pin(api::server_wrap( flow, state, &req, &json_payload.into_inner(), |state, _, req, _| { apple_pay_certificates_migration::apple_pay_certificates_migration(state, req) }, &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/apple_pay_certificates_migration.rs
router::src::routes::apple_pay_certificates_migration
222
true
// File: crates/router/src/routes/three_ds_decision_rule.rs // Module: router::src::routes::three_ds_decision_rule use actix_web::{web, Responder}; use hyperswitch_domain_models::merchant_context::{Context, MerchantContext}; use router_env::{instrument, tracing, Flow}; use crate::{ self as app, core::{api_locking, three_ds_decision_rule as three_ds_decision_rule_core}, services::{api, authentication as auth}, }; #[instrument(skip_all, fields(flow = ?Flow::ThreeDsDecisionRuleExecute))] #[cfg(feature = "oltp")] pub async fn execute_decision_rule( state: web::Data<app::AppState>, req: actix_web::HttpRequest, payload: web::Json<api_models::three_ds_decision_rule::ThreeDsDecisionRuleExecuteRequest>, ) -> impl Responder { let flow = Flow::ThreeDsDecisionRuleExecute; let payload = payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = MerchantContext::NormalMerchant(Box::new(Context( auth.merchant_account, auth.key_store, ))); three_ds_decision_rule_core::execute_three_ds_decision_rule( state, merchant_context, req, ) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/three_ds_decision_rule.rs
router::src::routes::three_ds_decision_rule
337
true
// File: crates/router/src/routes/webhook_events.rs // Module: router::src::routes::webhook_events use actix_web::{web, HttpRequest, Responder}; use router_env::{instrument, tracing, Flow}; use crate::{ core::{api_locking, webhooks::webhook_events}, routes::AppState, services::{ api, authentication::{self as auth, UserFromToken}, authorization::permissions::Permission, }, types::api::webhook_events::{ EventListConstraints, EventListRequestInternal, WebhookDeliveryAttemptListRequestInternal, WebhookDeliveryRetryRequestInternal, }, }; #[instrument(skip_all, fields(flow = ?Flow::WebhookEventInitialDeliveryAttemptList))] pub async fn list_initial_webhook_delivery_attempts( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::MerchantId>, json_payload: web::Json<EventListConstraints>, ) -> impl Responder { let flow = Flow::WebhookEventInitialDeliveryAttemptList; let merchant_id = path.into_inner(); let constraints = json_payload.into_inner(); let request_internal = EventListRequestInternal { merchant_id: merchant_id.clone(), constraints, }; Box::pin(api::server_wrap( flow, state, &req, request_internal, |state, _, request_internal, _| { webhook_events::list_initial_delivery_attempts( state, request_internal.merchant_id, request_internal.constraints, ) }, auth::auth_type( &auth::AdminApiAuth, &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::MerchantWebhookEventRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::WebhookEventInitialDeliveryAttemptList))] pub async fn list_initial_webhook_delivery_attempts_with_jwtauth( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<EventListConstraints>, ) -> impl Responder { let flow = Flow::WebhookEventInitialDeliveryAttemptList; let constraints = json_payload.into_inner(); let request_internal = EventListRequestInternal { merchant_id: common_utils::id_type::MerchantId::default(), constraints, }; Box::pin(api::server_wrap( flow, state, &req, request_internal, |state, auth: UserFromToken, mut request_internal, _| { let merchant_id = auth.merchant_id; let profile_id = auth.profile_id; request_internal.merchant_id = merchant_id; request_internal.constraints.profile_id = Some(profile_id); webhook_events::list_initial_delivery_attempts( state, request_internal.merchant_id, request_internal.constraints, ) }, &auth::JWTAuth { permission: Permission::ProfileWebhookEventRead, }, api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::WebhookEventDeliveryAttemptList))] pub async fn list_webhook_delivery_attempts( state: web::Data<AppState>, req: HttpRequest, path: web::Path<(common_utils::id_type::MerchantId, String)>, ) -> impl Responder { let flow = Flow::WebhookEventDeliveryAttemptList; let (merchant_id, initial_attempt_id) = path.into_inner(); let request_internal = WebhookDeliveryAttemptListRequestInternal { merchant_id: merchant_id.clone(), initial_attempt_id, }; Box::pin(api::server_wrap( flow, state, &req, request_internal, |state, _, request_internal, _| { webhook_events::list_delivery_attempts( state, request_internal.merchant_id, request_internal.initial_attempt_id, ) }, auth::auth_type( &auth::AdminApiAuth, &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::MerchantWebhookEventRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::WebhookEventDeliveryRetry))] #[cfg(feature = "v1")] pub async fn retry_webhook_delivery_attempt( state: web::Data<AppState>, req: HttpRequest, path: web::Path<(common_utils::id_type::MerchantId, String)>, ) -> impl Responder { let flow = Flow::WebhookEventDeliveryRetry; let (merchant_id, event_id) = path.into_inner(); let request_internal = WebhookDeliveryRetryRequestInternal { merchant_id: merchant_id.clone(), event_id, }; Box::pin(api::server_wrap( flow, state, &req, request_internal, |state, _, request_internal, _| { webhook_events::retry_delivery_attempt( state, request_internal.merchant_id, request_internal.event_id, ) }, auth::auth_type( &auth::AdminApiAuth, &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::MerchantWebhookEventWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/webhook_events.rs
router::src::routes::webhook_events
1,160
true
// File: crates/router/src/routes/relay.rs // Module: router::src::routes::relay use actix_web::{web, Responder}; use router_env::{instrument, tracing, Flow}; use crate::{ self as app, core::{api_locking, relay}, services::{api, authentication as auth}, }; #[instrument(skip_all, fields(flow = ?Flow::Relay))] #[cfg(feature = "oltp")] pub async fn relay( state: web::Data<app::AppState>, req: actix_web::HttpRequest, payload: web::Json<api_models::relay::RelayRequest>, ) -> impl Responder { let flow = Flow::Relay; let payload = payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = crate::types::domain::MerchantContext::NormalMerchant(Box::new( crate::types::domain::Context(auth.merchant_account, auth.key_store), )); relay::relay_flow_decider( state, merchant_context, #[cfg(feature = "v1")] auth.profile_id, #[cfg(feature = "v2")] Some(auth.profile.get_id().clone()), req, ) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::RelayRetrieve))] #[cfg(feature = "oltp")] pub async fn relay_retrieve( state: web::Data<app::AppState>, path: web::Path<common_utils::id_type::RelayId>, req: actix_web::HttpRequest, query_params: web::Query<api_models::relay::RelayRetrieveBody>, ) -> impl Responder { let flow = Flow::RelayRetrieve; let relay_retrieve_request = api_models::relay::RelayRetrieveRequest { force_sync: query_params.force_sync, id: path.into_inner(), }; Box::pin(api::server_wrap( flow, state, &req, relay_retrieve_request, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = crate::types::domain::MerchantContext::NormalMerchant(Box::new( crate::types::domain::Context(auth.merchant_account, auth.key_store), )); relay::relay_retrieve( state, merchant_context, #[cfg(feature = "v1")] auth.profile_id, #[cfg(feature = "v2")] Some(auth.profile.get_id().clone()), req, ) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/relay.rs
router::src::routes::relay
645
true
// File: crates/router/src/routes/admin.rs // Module: router::src::routes::admin use actix_web::{web, HttpRequest, HttpResponse}; use router_env::{instrument, tracing, Flow}; use super::app::AppState; use crate::{ core::{admin::*, api_locking, errors}, services::{api, authentication as auth, authorization::permissions::Permission}, types::{api::admin, domain}, }; #[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all, fields(flow = ?Flow::OrganizationCreate))] pub async fn organization_create( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<admin::OrganizationCreateRequest>, ) -> HttpResponse { let flow = Flow::OrganizationCreate; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, _, req, _| create_organization(state, req), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v2"))] #[instrument(skip_all, fields(flow = ?Flow::OrganizationCreate))] pub async fn organization_create( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<admin::OrganizationCreateRequest>, ) -> HttpResponse { let flow = Flow::OrganizationCreate; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, _, req, _| create_organization(state, req), &auth::V2AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all, fields(flow = ?Flow::OrganizationUpdate))] pub async fn organization_update( state: web::Data<AppState>, req: HttpRequest, org_id: web::Path<common_utils::id_type::OrganizationId>, json_payload: web::Json<admin::OrganizationUpdateRequest>, ) -> HttpResponse { let flow = Flow::OrganizationUpdate; let organization_id = org_id.into_inner(); let org_id = admin::OrganizationId { organization_id: organization_id.clone(), }; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, _, req, _| update_organization(state, org_id.clone(), req), auth::auth_type( &auth::PlatformOrgAdminAuth { is_admin_auth_allowed: true, organization_id: Some(organization_id.clone()), }, &auth::JWTAuthOrganizationFromRoute { organization_id, required_permission: Permission::OrganizationAccountWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v2"))] #[instrument(skip_all, fields(flow = ?Flow::OrganizationUpdate))] pub async fn organization_update( state: web::Data<AppState>, req: HttpRequest, org_id: web::Path<common_utils::id_type::OrganizationId>, json_payload: web::Json<admin::OrganizationUpdateRequest>, ) -> HttpResponse { let flow = Flow::OrganizationUpdate; let organization_id = org_id.into_inner(); let org_id = admin::OrganizationId { organization_id: organization_id.clone(), }; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, _, req, _| update_organization(state, org_id.clone(), req), auth::auth_type( &auth::V2AdminApiAuth, &auth::JWTAuthOrganizationFromRoute { organization_id, required_permission: Permission::OrganizationAccountWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all, fields(flow = ?Flow::OrganizationRetrieve))] pub async fn organization_retrieve( state: web::Data<AppState>, req: HttpRequest, org_id: web::Path<common_utils::id_type::OrganizationId>, ) -> HttpResponse { let flow = Flow::OrganizationRetrieve; let organization_id = org_id.into_inner(); let payload = admin::OrganizationId { organization_id: organization_id.clone(), }; Box::pin(api::server_wrap( flow, state, &req, payload, |state, _, req, _| get_organization(state, req), auth::auth_type( &auth::PlatformOrgAdminAuth { is_admin_auth_allowed: true, organization_id: Some(organization_id.clone()), }, &auth::JWTAuthOrganizationFromRoute { organization_id, required_permission: Permission::OrganizationAccountRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v2"))] #[instrument(skip_all, fields(flow = ?Flow::OrganizationRetrieve))] pub async fn organization_retrieve( state: web::Data<AppState>, req: HttpRequest, org_id: web::Path<common_utils::id_type::OrganizationId>, ) -> HttpResponse { let flow = Flow::OrganizationRetrieve; let organization_id = org_id.into_inner(); let payload = admin::OrganizationId { organization_id: organization_id.clone(), }; Box::pin(api::server_wrap( flow, state, &req, payload, |state, _, req, _| get_organization(state, req), auth::auth_type( &auth::V2AdminApiAuth, &auth::JWTAuthOrganizationFromRoute { organization_id, required_permission: Permission::OrganizationAccountRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all, fields(flow = ?Flow::MerchantsAccountCreate))] pub async fn merchant_account_create( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<admin::MerchantAccountCreate>, ) -> HttpResponse { let flow = Flow::MerchantsAccountCreate; let payload = json_payload.into_inner(); if let Err(api_error) = payload .webhook_details .as_ref() .map(|details| { details .validate() .map_err(|message| errors::ApiErrorResponse::InvalidRequestData { message }) }) .transpose() { return api::log_and_return_error_response(api_error.into()); } Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth, req, _| create_merchant_account(state, req, auth), &auth::PlatformOrgAdminAuth { is_admin_auth_allowed: true, organization_id: None, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v2"))] #[instrument(skip_all, fields(flow = ?Flow::MerchantsAccountCreate))] pub async fn merchant_account_create( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<api_models::admin::MerchantAccountCreateWithoutOrgId>, ) -> HttpResponse { let flow = Flow::MerchantsAccountCreate; let headers = req.headers(); let org_id = match auth::HeaderMapStruct::new(headers).get_organization_id_from_header() { Ok(org_id) => org_id, Err(e) => return api::log_and_return_error_response(e), }; // Converting from MerchantAccountCreateWithoutOrgId to MerchantAccountCreate so we can use the existing // `create_merchant_account` function for v2 as well let json_payload = json_payload.into_inner(); let new_request_payload_with_org_id = api_models::admin::MerchantAccountCreate { merchant_name: json_payload.merchant_name, merchant_details: json_payload.merchant_details, metadata: json_payload.metadata, organization_id: org_id, product_type: json_payload.product_type, }; Box::pin(api::server_wrap( flow, state, &req, new_request_payload_with_org_id, |state, _, req, _| create_merchant_account(state, req, None), &auth::V2AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::MerchantsAccountRetrieve))] pub async fn retrieve_merchant_account( state: web::Data<AppState>, req: HttpRequest, mid: web::Path<common_utils::id_type::MerchantId>, ) -> HttpResponse { let flow = Flow::MerchantsAccountRetrieve; let merchant_id = mid.into_inner(); let payload = admin::MerchantId { merchant_id: merchant_id.clone(), }; api::server_wrap( flow, state, &req, payload, |state, _, req, _| get_merchant_account(state, req, None), auth::auth_type( &auth::PlatformOrgAdminAuthWithMerchantIdFromRoute { merchant_id_from_route: merchant_id.clone(), is_admin_auth_allowed: true, }, &auth::JWTAuthMerchantFromRoute { merchant_id, // This should ideally be MerchantAccountRead, but since FE is calling this API for // profile level users currently keeping this as ProfileAccountRead. FE is removing // this API call for profile level users. // TODO: Convert this to MerchantAccountRead once FE changes are done. required_permission: Permission::ProfileAccountRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, ) .await } /// Merchant Account - Retrieve /// /// Retrieve a merchant account details. #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::MerchantsAccountRetrieve))] pub async fn retrieve_merchant_account( state: web::Data<AppState>, req: HttpRequest, mid: web::Path<common_utils::id_type::MerchantId>, ) -> HttpResponse { let flow = Flow::MerchantsAccountRetrieve; let merchant_id = mid.into_inner(); let payload = admin::MerchantId { merchant_id: merchant_id.clone(), }; api::server_wrap( flow, state, &req, payload, |state, _, req, _| get_merchant_account(state, req, None), auth::auth_type( &auth::V2AdminApiAuth, &auth::JWTAuthMerchantFromRoute { merchant_id, // This should ideally be MerchantAccountRead, but since FE is calling this API for // profile level users currently keeping this as ProfileAccountRead. FE is removing // this API call for profile level users. // TODO: Convert this to MerchantAccountRead once FE changes are done. required_permission: Permission::ProfileAccountRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, ) .await } #[cfg(all(feature = "olap", feature = "v2"))] #[instrument(skip_all, fields(flow = ?Flow::MerchantAccountList))] pub async fn merchant_account_list( state: web::Data<AppState>, req: HttpRequest, organization_id: web::Path<common_utils::id_type::OrganizationId>, ) -> HttpResponse { let flow = Flow::MerchantAccountList; let organization_id = admin::OrganizationId { organization_id: organization_id.into_inner(), }; Box::pin(api::server_wrap( flow, state, &req, organization_id, |state, _, request, _| list_merchant_account(state, request), auth::auth_type( &auth::V2AdminApiAuth, &auth::JWTAuthMerchantFromHeader { required_permission: Permission::MerchantAccountRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all, fields(flow = ?Flow::MerchantAccountList))] pub async fn merchant_account_list( state: web::Data<AppState>, req: HttpRequest, query_params: web::Query<api_models::admin::MerchantAccountListRequest>, ) -> HttpResponse { let flow = Flow::MerchantAccountList; Box::pin(api::server_wrap( flow, state, &req, query_params.into_inner(), |state, auth, request, _| list_merchant_account(state, request, auth), auth::auth_type( &auth::PlatformOrgAdminAuth { is_admin_auth_allowed: true, organization_id: None, }, &auth::JWTAuthMerchantFromHeader { required_permission: Permission::MerchantAccountRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } /// Merchant Account - Update /// /// To update an existing merchant account. Helpful in updating merchant details such as email, contact details, or other configuration details like webhook, routing algorithm etc #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::MerchantsAccountUpdate))] pub async fn update_merchant_account( state: web::Data<AppState>, req: HttpRequest, mid: web::Path<common_utils::id_type::MerchantId>, json_payload: web::Json<admin::MerchantAccountUpdate>, ) -> HttpResponse { let flow = Flow::MerchantsAccountUpdate; let merchant_id = mid.into_inner(); Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, _, req, _| merchant_account_update(state, &merchant_id, None, req), auth::auth_type( &auth::V2AdminApiAuth, &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::MerchantAccountWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::MerchantsAccountUpdate))] pub async fn update_merchant_account( state: web::Data<AppState>, req: HttpRequest, mid: web::Path<common_utils::id_type::MerchantId>, json_payload: web::Json<admin::MerchantAccountUpdate>, ) -> HttpResponse { let flow = Flow::MerchantsAccountUpdate; let merchant_id = mid.into_inner(); Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, _, req, _| merchant_account_update(state, &merchant_id, None, req), auth::auth_type( &auth::PlatformOrgAdminAuthWithMerchantIdFromRoute { merchant_id_from_route: merchant_id.clone(), is_admin_auth_allowed: true, }, &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::MerchantAccountWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } /// Merchant Account - Delete /// /// To delete a merchant account #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::MerchantsAccountDelete))] pub async fn delete_merchant_account( state: web::Data<AppState>, req: HttpRequest, mid: web::Path<common_utils::id_type::MerchantId>, ) -> HttpResponse { let flow = Flow::MerchantsAccountDelete; let mid = mid.into_inner(); let payload = web::Json(admin::MerchantId { merchant_id: mid }).into_inner(); api::server_wrap( flow, state, &req, payload, |state, _, req, _| merchant_account_delete(state, req.merchant_id), &auth::V2AdminApiAuth, api_locking::LockAction::NotApplicable, ) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::MerchantsAccountDelete))] pub async fn delete_merchant_account( state: web::Data<AppState>, req: HttpRequest, mid: web::Path<common_utils::id_type::MerchantId>, ) -> HttpResponse { let flow = Flow::MerchantsAccountDelete; let mid = mid.into_inner(); let payload = web::Json(admin::MerchantId { merchant_id: mid }).into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, _, req, _| merchant_account_delete(state, req.merchant_id), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } /// Merchant Connector - Create /// /// Create a new Merchant Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc." #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::MerchantConnectorsCreate))] pub async fn connector_create( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::MerchantId>, json_payload: web::Json<admin::MerchantConnectorCreate>, ) -> HttpResponse { let flow = Flow::MerchantConnectorsCreate; let payload = json_payload.into_inner(); let merchant_id = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth_data, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth_data.merchant_account, auth_data.key_store), )); create_connector(state, req, merchant_context, auth_data.profile_id) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::ProfileConnectorWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } /// Merchant Connector - Create /// /// Create a new Merchant Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc." #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::MerchantConnectorsCreate))] pub async fn connector_create( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<admin::MerchantConnectorCreate>, ) -> HttpResponse { let flow = Flow::MerchantConnectorsCreate; let payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth_data: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth_data.merchant_account, auth_data.key_store), )); create_connector(state, req, merchant_context, None) }, auth::auth_type( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromHeader { required_permission: Permission::MerchantConnectorWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } /// Merchant Connector - Retrieve /// /// Retrieve Merchant Connector Details #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::MerchantConnectorsRetrieve))] pub async fn connector_retrieve( state: web::Data<AppState>, req: HttpRequest, path: web::Path<( common_utils::id_type::MerchantId, common_utils::id_type::MerchantConnectorAccountId, )>, ) -> HttpResponse { let flow = Flow::MerchantConnectorsRetrieve; let (merchant_id, merchant_connector_id) = path.into_inner(); let payload = web::Json(admin::MerchantConnectorId { merchant_id: merchant_id.clone(), merchant_connector_id, }) .into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth, req, _| { retrieve_connector( state, req.merchant_id, auth.profile_id, req.merchant_connector_id, ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id, // This should ideally be ProfileConnectorRead, but since this API responds with // sensitive data, keeping this as ProfileConnectorWrite // TODO: Convert this to ProfileConnectorRead once data is masked. required_permission: Permission::ProfileConnectorWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } /// Merchant Connector - Retrieve /// /// Retrieve Merchant Connector Details #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::MerchantConnectorsRetrieve))] pub async fn connector_retrieve( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::MerchantConnectorAccountId>, ) -> HttpResponse { let flow = Flow::MerchantConnectorsRetrieve; let id = path.into_inner(); let payload = web::Json(admin::MerchantConnectorId { id: id.clone() }).into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth::AuthenticationData { merchant_account, key_store, .. }, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(merchant_account, key_store), )); retrieve_connector(state, merchant_context, req.id.clone()) }, auth::auth_type( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromHeader { required_permission: Permission::MerchantConnectorRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v2"))] #[instrument(skip_all, fields(flow = ?Flow::MerchantConnectorsList))] pub async fn connector_list( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::ProfileId>, ) -> HttpResponse { let flow = Flow::MerchantConnectorsList; let profile_id = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, profile_id.to_owned(), |state, auth::AuthenticationData { key_store, .. }, _, _| { list_connectors_for_a_profile(state, key_store, profile_id.clone()) }, auth::auth_type( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromHeader { required_permission: Permission::MerchantConnectorRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } /// Merchant Connector - List /// /// List Merchant Connector Details for the merchant #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::MerchantConnectorsList))] pub async fn connector_list( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::MerchantId>, ) -> HttpResponse { let flow = Flow::MerchantConnectorsList; let merchant_id = path.into_inner(); api::server_wrap( flow, state, &req, merchant_id.to_owned(), |state, _auth, merchant_id, _| list_payment_connectors(state, merchant_id, None), auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::MerchantConnectorRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, ) .await } #[cfg(all(feature = "v1", feature = "olap"))] /// Merchant Connector - List /// /// List Merchant Connector Details for the merchant #[instrument(skip_all, fields(flow = ?Flow::MerchantConnectorsList))] pub async fn connector_list_profile( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::MerchantId>, ) -> HttpResponse { let flow = Flow::MerchantConnectorsList; let merchant_id = path.into_inner(); api::server_wrap( flow, state, &req, merchant_id.to_owned(), |state, auth, merchant_id, _| { list_payment_connectors( state, merchant_id, auth.profile_id.map(|profile_id| vec![profile_id]), ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::ProfileConnectorRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, ) .await } /// Merchant Connector - Update /// /// To update an existing Merchant Connector. Helpful in enabling / disabling different payment methods and other settings for the connector etc. #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::MerchantConnectorsUpdate))] pub async fn connector_update( state: web::Data<AppState>, req: HttpRequest, path: web::Path<( common_utils::id_type::MerchantId, common_utils::id_type::MerchantConnectorAccountId, )>, json_payload: web::Json<api_models::admin::MerchantConnectorUpdate>, ) -> HttpResponse { let flow = Flow::MerchantConnectorsUpdate; let (merchant_id, merchant_connector_id) = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth, req, _| { update_connector( state, &merchant_id, auth.profile_id, &merchant_connector_id, req, ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::ProfileConnectorWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } /// Merchant Connector - Update /// /// To update an existing Merchant Connector. Helpful in enabling / disabling different payment methods and other settings for the connector etc. #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::MerchantConnectorsUpdate))] pub async fn connector_update( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::MerchantConnectorAccountId>, json_payload: web::Json<api_models::admin::MerchantConnectorUpdate>, ) -> HttpResponse { let flow = Flow::MerchantConnectorsUpdate; let id = path.into_inner(); let payload = json_payload.into_inner(); let merchant_id = payload.merchant_id.clone(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, _, req, _| update_connector(state, &merchant_id, None, &id, req), auth::auth_type( &auth::V2AdminApiAuth, &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::MerchantConnectorWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } /// Merchant Connector - Delete /// /// Delete or Detach a Merchant Connector from Merchant Account #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::MerchantConnectorsDelete))] pub async fn connector_delete( state: web::Data<AppState>, req: HttpRequest, path: web::Path<( common_utils::id_type::MerchantId, common_utils::id_type::MerchantConnectorAccountId, )>, ) -> HttpResponse { let flow = Flow::MerchantConnectorsDelete; let (merchant_id, merchant_connector_id) = path.into_inner(); let payload = web::Json(admin::MerchantConnectorId { merchant_id: merchant_id.clone(), merchant_connector_id, }) .into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, _, req, _| delete_connector(state, req.merchant_id, req.merchant_connector_id), auth::auth_type( &auth::AdminApiAuth, &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::MerchantConnectorWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } /// Merchant Connector - Delete /// /// Delete or Detach a Merchant Connector from Merchant Account #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::MerchantConnectorsDelete))] pub async fn connector_delete( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::MerchantConnectorAccountId>, ) -> HttpResponse { let flow = Flow::MerchantConnectorsDelete; let id = path.into_inner(); let payload = web::Json(admin::MerchantConnectorId { id: id.clone() }).into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth::AuthenticationData { merchant_account, key_store, .. }, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(merchant_account, key_store), )); delete_connector(state, merchant_context, req.id) }, auth::auth_type( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromHeader { required_permission: Permission::MerchantConnectorWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } /// Merchant Account - Toggle KV /// /// Toggle KV mode for the Merchant Account #[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn merchant_account_toggle_kv( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::MerchantId>, json_payload: web::Json<admin::ToggleKVRequest>, ) -> HttpResponse { let flow = Flow::ConfigKeyUpdate; let mut payload = json_payload.into_inner(); payload.merchant_id = path.into_inner(); api::server_wrap( flow, state, &req, payload, |state, _, payload, _| kv_for_merchant(state, payload.merchant_id, payload.kv_enabled), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, ) .await } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn merchant_account_toggle_kv( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::MerchantId>, json_payload: web::Json<admin::ToggleKVRequest>, ) -> HttpResponse { let flow = Flow::ConfigKeyUpdate; let mut payload = json_payload.into_inner(); payload.merchant_id = path.into_inner(); api::server_wrap( flow, state, &req, payload, |state, _, payload, _| kv_for_merchant(state, payload.merchant_id, payload.kv_enabled), &auth::V2AdminApiAuth, api_locking::LockAction::NotApplicable, ) .await } /// Merchant Account - Transfer Keys /// /// Transfer Merchant Encryption key to keymanager #[instrument(skip_all)] pub async fn merchant_account_toggle_all_kv( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<admin::ToggleAllKVRequest>, ) -> HttpResponse { let flow = Flow::MerchantTransferKey; let payload = json_payload.into_inner(); api::server_wrap( flow, state, &req, payload, |state, _, payload, _| toggle_kv_for_all_merchants(state, payload.kv_enabled), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, ) .await } /// Merchant Account - KV Status /// /// Toggle KV mode for the Merchant Account #[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn merchant_account_kv_status( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::MerchantId>, ) -> HttpResponse { let flow = Flow::ConfigKeyFetch; let merchant_id = path.into_inner(); api::server_wrap( flow, state, &req, merchant_id, |state, _, req, _| check_merchant_account_kv_status(state, req), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, ) .await } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn merchant_account_kv_status( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::MerchantId>, ) -> HttpResponse { let flow = Flow::ConfigKeyFetch; let merchant_id = path.into_inner(); api::server_wrap( flow, state, &req, merchant_id, |state, _, req, _| check_merchant_account_kv_status(state, req), &auth::V2AdminApiAuth, api_locking::LockAction::NotApplicable, ) .await } /// Merchant Account - KV Status /// /// Toggle KV mode for the Merchant Account #[instrument(skip_all)] pub async fn merchant_account_transfer_keys( state: web::Data<AppState>, req: HttpRequest, payload: web::Json<api_models::admin::MerchantKeyTransferRequest>, ) -> HttpResponse { let flow = Flow::ConfigKeyFetch; Box::pin(api::server_wrap( flow, state, &req, payload.into_inner(), |state, _, req, _| transfer_key_store_to_key_manager(state, req), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } /// Merchant Account - Platform Account /// /// Enable platform account #[instrument(skip_all)] pub async fn merchant_account_enable_platform_account( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::MerchantId>, ) -> HttpResponse { let flow = Flow::EnablePlatformAccount; let merchant_id = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, merchant_id, |state, _, req, _| enable_platform_account(state, req), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/admin.rs
router::src::routes::admin
7,833
true
// File: crates/router/src/routes/connector_onboarding.rs // Module: router::src::routes::connector_onboarding use actix_web::{web, HttpRequest, HttpResponse}; use api_models::connector_onboarding as api_types; use router_env::Flow; use super::AppState; use crate::{ core::{api_locking, connector_onboarding as core}, services::{api, authentication as auth, authorization::permissions::Permission}, }; pub async fn get_action_url( state: web::Data<AppState>, http_req: HttpRequest, json_payload: web::Json<api_types::ActionUrlRequest>, ) -> HttpResponse { let flow = Flow::GetActionUrl; let req_payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow.clone(), state, &http_req, req_payload.clone(), core::get_action_url, &auth::JWTAuth { permission: Permission::MerchantAccountWrite, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn sync_onboarding_status( state: web::Data<AppState>, http_req: HttpRequest, json_payload: web::Json<api_types::OnboardingSyncRequest>, ) -> HttpResponse { let flow = Flow::SyncOnboardingStatus; let req_payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow.clone(), state, &http_req, req_payload.clone(), core::sync_onboarding_status, &auth::JWTAuth { permission: Permission::MerchantAccountWrite, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn reset_tracking_id( state: web::Data<AppState>, http_req: HttpRequest, json_payload: web::Json<api_types::ResetTrackingIdRequest>, ) -> HttpResponse { let flow = Flow::ResetTrackingId; let req_payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow.clone(), state, &http_req, req_payload.clone(), core::reset_tracking_id, &auth::JWTAuth { permission: Permission::MerchantAccountWrite, }, api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/connector_onboarding.rs
router::src::routes::connector_onboarding
489
true
// File: crates/router/src/routes/chat.rs // Module: router::src::routes::chat use actix_web::{web, HttpRequest, HttpResponse}; #[cfg(feature = "olap")] use api_models::chat as chat_api; use router_env::{instrument, tracing, Flow}; use super::AppState; use crate::{ core::{api_locking, chat as chat_core}, routes::metrics, services::{ api, authentication::{self as auth}, authorization::permissions::Permission, }, }; #[instrument(skip_all)] pub async fn get_data_from_hyperswitch_ai_workflow( state: web::Data<AppState>, http_req: HttpRequest, payload: web::Json<chat_api::ChatRequest>, ) -> HttpResponse { let flow = Flow::GetDataFromHyperswitchAiFlow; let session_id = http_req .headers() .get(common_utils::consts::X_CHAT_SESSION_ID) .and_then(|header_value| header_value.to_str().ok()); Box::pin(api::server_wrap( flow.clone(), state, &http_req, payload.into_inner(), |state, user: auth::UserFromToken, payload, _| { metrics::CHAT_REQUEST_COUNT.add( 1, router_env::metric_attributes!(("merchant_id", user.merchant_id.clone())), ); chat_core::get_data_from_hyperswitch_ai_workflow(state, user, payload, session_id) }, // At present, the AI service retrieves data scoped to the merchant level &auth::JWTAuth { permission: Permission::MerchantPaymentRead, }, api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all)] pub async fn get_all_conversations( state: web::Data<AppState>, http_req: HttpRequest, payload: web::Query<chat_api::ChatListRequest>, ) -> HttpResponse { let flow = Flow::ListAllChatInteractions; Box::pin(api::server_wrap( flow.clone(), state, &http_req, payload.into_inner(), |state, user: auth::UserFromToken, payload, _| { chat_core::list_chat_conversations(state, user, payload) }, &auth::DashboardNoPermissionAuth, api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/chat.rs
router::src::routes::chat
506
true
// File: crates/router/src/routes/pm_auth.rs // Module: router::src::routes::pm_auth use actix_web::{web, HttpRequest, Responder}; use api_models as api_types; use router_env::{instrument, tracing, types::Flow}; use crate::{ core::api_locking, routes::AppState, services::{api, authentication as auth}, types::transformers::ForeignTryFrom, }; #[instrument(skip_all, fields(flow = ?Flow::PmAuthLinkTokenCreate))] pub async fn link_token_create( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<api_types::pm_auth::LinkTokenCreateRequest>, ) -> impl Responder { let payload = json_payload.into_inner(); let flow = Flow::PmAuthLinkTokenCreate; let api_auth = auth::ApiKeyAuth::default(); let (auth, _) = match crate::services::authentication::check_client_secret_and_get_auth( req.headers(), &payload, api_auth, ) { Ok((auth, _auth_flow)) => (auth, _auth_flow), Err(e) => return api::log_and_return_error_response(e), }; let header_payload = match hyperswitch_domain_models::payments::HeaderPayload::foreign_try_from(req.headers()) { Ok(headers) => headers, Err(err) => { return api::log_and_return_error_response(err); } }; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth, payload, _| { let merchant_context = crate::types::domain::MerchantContext::NormalMerchant(Box::new( crate::types::domain::Context(auth.merchant_account, auth.key_store), )); crate::core::pm_auth::create_link_token( state, merchant_context, payload, Some(header_payload.clone()), ) }, &*auth, api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::PmAuthExchangeToken))] pub async fn exchange_token( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<api_types::pm_auth::ExchangeTokenCreateRequest>, ) -> impl Responder { let payload = json_payload.into_inner(); let flow = Flow::PmAuthExchangeToken; let api_auth = auth::ApiKeyAuth::default(); let (auth, _) = match crate::services::authentication::check_client_secret_and_get_auth( req.headers(), &payload, api_auth, ) { Ok((auth, _auth_flow)) => (auth, _auth_flow), Err(e) => return api::log_and_return_error_response(e), }; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth, payload, _| { let merchant_context = crate::types::domain::MerchantContext::NormalMerchant(Box::new( crate::types::domain::Context(auth.merchant_account, auth.key_store), )); crate::core::pm_auth::exchange_token_core(state, merchant_context, payload) }, &*auth, api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/pm_auth.rs
router::src::routes::pm_auth
716
true
// File: crates/router/src/routes/metrics/request.rs // Module: router::src::routes::metrics::request use crate::services::ApplicationResponse; pub fn track_response_status_code<Q>(response: &ApplicationResponse<Q>) -> i64 { match response { ApplicationResponse::Json(_) | ApplicationResponse::StatusOk | ApplicationResponse::TextPlain(_) | ApplicationResponse::Form(_) | ApplicationResponse::GenericLinkForm(_) | ApplicationResponse::PaymentLinkForm(_) | ApplicationResponse::FileData(_) | ApplicationResponse::JsonWithHeaders(_) => 200, ApplicationResponse::JsonForRedirection(_) => 302, } }
crates/router/src/routes/metrics/request.rs
router::src::routes::metrics::request
151
true
// File: crates/router/src/routes/metrics/bg_metrics_collector.rs // Module: router::src::routes::metrics::bg_metrics_collector use storage_impl::redis::cache; const DEFAULT_BG_METRICS_COLLECTION_INTERVAL_IN_SECS: u16 = 15; pub fn spawn_metrics_collector(metrics_collection_interval_in_secs: Option<u16>) { let metrics_collection_interval = metrics_collection_interval_in_secs .unwrap_or(DEFAULT_BG_METRICS_COLLECTION_INTERVAL_IN_SECS); let cache_instances = [ &cache::CONFIG_CACHE, &cache::ACCOUNTS_CACHE, &cache::ROUTING_CACHE, &cache::CGRAPH_CACHE, &cache::PM_FILTERS_CGRAPH_CACHE, &cache::DECISION_MANAGER_CACHE, &cache::SURCHARGE_CACHE, &cache::SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE, &cache::CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE, &cache::ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE, ]; tokio::spawn(async move { loop { for instance in cache_instances { instance.record_entry_count_metric().await } tokio::time::sleep(std::time::Duration::from_secs( metrics_collection_interval.into(), )) .await } }); }
crates/router/src/routes/metrics/bg_metrics_collector.rs
router::src::routes::metrics::bg_metrics_collector
271
true
// File: crates/router/src/routes/payments/helpers.rs // Module: router::src::routes::payments::helpers use error_stack::ResultExt; use crate::{ core::errors::{self, RouterResult}, logger, types::{self, api}, utils::{Encode, ValueExt}, }; #[cfg(feature = "v1")] pub fn populate_browser_info( req: &actix_web::HttpRequest, payload: &mut api::PaymentsRequest, header_payload: &hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<()> { let mut browser_info: types::BrowserInformation = payload .browser_info .clone() .map(|v| v.parse_value("BrowserInformation")) .transpose() .change_context_lazy(|| errors::ApiErrorResponse::InvalidRequestData { message: "invalid format for 'browser_info' provided".to_string(), })? .unwrap_or(types::BrowserInformation { color_depth: None, java_enabled: None, java_script_enabled: None, language: None, screen_height: None, screen_width: None, time_zone: None, accept_header: None, user_agent: None, ip_address: None, os_type: None, os_version: None, device_model: None, accept_language: None, referer: None, }); let ip_address = req .connection_info() .realip_remote_addr() .map(ToOwned::to_owned); if ip_address.is_some() { logger::debug!("Extracted ip address from request"); } browser_info.ip_address = browser_info.ip_address.or_else(|| { ip_address .as_ref() .map(|ip| ip.parse()) .transpose() .unwrap_or_else(|error| { logger::error!( ?error, "failed to parse ip address which is extracted from the request" ); None }) }); // If the locale is present in the header payload, we will use it as the accept language if header_payload.locale.is_some() { browser_info.accept_language = browser_info .accept_language .or(header_payload.locale.clone()); } if let Some(api::MandateData { customer_acceptance: Some(api::CustomerAcceptance { online: Some(api::OnlineMandate { ip_address: req_ip, .. }), .. }), .. }) = &mut payload.mandate_data { *req_ip = req_ip .clone() .or_else(|| ip_address.map(|ip| masking::Secret::new(ip.to_string()))); } let encoded = browser_info .encode_to_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "failed to re-encode browser information to json after setting ip address", )?; payload.browser_info = Some(encoded); Ok(()) }
crates/router/src/routes/payments/helpers.rs
router::src::routes::payments::helpers
636
true
// File: crates/router/src/routes/process_tracker/revenue_recovery.rs // Module: router::src::routes::process_tracker::revenue_recovery use actix_web::{web, HttpRequest, HttpResponse}; use api_models::process_tracker::revenue_recovery as revenue_recovery_api; use router_env::Flow; use crate::{ core::{api_locking, revenue_recovery}, routes::AppState, services::{api, authentication as auth, authorization::permissions::Permission}, }; pub async fn revenue_recovery_pt_retrieve_api( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::GlobalPaymentId>, ) -> HttpResponse { let flow = Flow::RevenueRecoveryRetrieve; let id = path.into_inner(); let payload = revenue_recovery_api::RevenueRecoveryId { revenue_recovery_id: id, }; Box::pin(api::server_wrap( flow, state, &req, payload, |state, _: (), id, _| { revenue_recovery::retrieve_revenue_recovery_process_tracker( state, id.revenue_recovery_id, ) }, &auth::JWTAuth { permission: Permission::ProfileRevenueRecoveryRead, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn revenue_recovery_resume_api( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::GlobalPaymentId>, json_payload: web::Json<revenue_recovery_api::RevenueRecoveryRetriggerRequest>, ) -> HttpResponse { let flow = Flow::RevenueRecoveryResume; let id = path.into_inner(); let payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, _, payload, _| { revenue_recovery::resume_revenue_recovery_process_tracker(state, id.clone(), payload) }, &auth::V2AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/process_tracker/revenue_recovery.rs
router::src::routes::process_tracker::revenue_recovery
449
true
// File: crates/router/src/routes/dummy_connector/core.rs // Module: router::src::routes::dummy_connector::core use app::SessionState; use common_utils::generate_id_with_default_len; use error_stack::ResultExt; use super::{errors, types, utils}; use crate::{ routes::{app, dummy_connector::consts}, services::api, utils::OptionExt, }; #[cfg(feature = "dummy_connector")] pub async fn payment( state: SessionState, req: types::DummyConnectorPaymentRequest, ) -> types::DummyConnectorResponse<types::DummyConnectorPaymentResponse> { utils::tokio_mock_sleep( state.conf.dummy_connector.payment_duration, state.conf.dummy_connector.payment_tolerance, ) .await; let payment_attempt: types::DummyConnectorPaymentAttempt = req.into(); let payment_data = types::DummyConnectorPaymentData::process_payment_attempt(&state, payment_attempt)?; utils::store_data_in_redis( &state, payment_data.attempt_id.clone(), payment_data.payment_id.clone(), state.conf.dummy_connector.authorize_ttl, ) .await?; utils::store_data_in_redis( &state, payment_data.payment_id.get_string_repr().to_owned(), payment_data.clone(), state.conf.dummy_connector.payment_ttl, ) .await?; Ok(api::ApplicationResponse::Json(payment_data.into())) } pub async fn payment_data( state: SessionState, req: types::DummyConnectorPaymentRetrieveRequest, ) -> types::DummyConnectorResponse<types::DummyConnectorPaymentResponse> { utils::tokio_mock_sleep( state.conf.dummy_connector.payment_retrieve_duration, state.conf.dummy_connector.payment_retrieve_tolerance, ) .await; let payment_data = utils::get_payment_data_from_payment_id(&state, req.payment_id).await?; Ok(api::ApplicationResponse::Json(payment_data.into())) } #[cfg(all(feature = "dummy_connector", feature = "v1"))] pub async fn payment_authorize( state: SessionState, req: types::DummyConnectorPaymentConfirmRequest, ) -> types::DummyConnectorResponse<String> { let payment_data = utils::get_payment_data_by_attempt_id(&state, req.attempt_id.clone()).await; let dummy_connector_conf = &state.conf.dummy_connector; if let Ok(payment_data_inner) = payment_data { let return_url = format!( "{}/dummy-connector/complete/{}", state.base_url, req.attempt_id ); Ok(api::ApplicationResponse::FileData(( utils::get_authorize_page(payment_data_inner, return_url, dummy_connector_conf) .as_bytes() .to_vec(), mime::TEXT_HTML, ))) } else { Ok(api::ApplicationResponse::FileData(( utils::get_expired_page(dummy_connector_conf) .as_bytes() .to_vec(), mime::TEXT_HTML, ))) } } #[cfg(all(feature = "dummy_connector", feature = "v1"))] pub async fn payment_complete( state: SessionState, req: types::DummyConnectorPaymentCompleteRequest, ) -> types::DummyConnectorResponse<()> { utils::tokio_mock_sleep( state.conf.dummy_connector.payment_duration, state.conf.dummy_connector.payment_tolerance, ) .await; let payment_data = utils::get_payment_data_by_attempt_id(&state, req.attempt_id.clone()).await; let payment_status = if req.confirm { types::DummyConnectorStatus::Succeeded } else { types::DummyConnectorStatus::Failed }; let redis_conn = state .store .get_redis_conn() .change_context(errors::DummyConnectorErrors::InternalServerError) .attach_printable("Failed to get redis connection")?; let _ = redis_conn.delete_key(&req.attempt_id.as_str().into()).await; if let Ok(payment_data) = payment_data { let updated_payment_data = types::DummyConnectorPaymentData { status: payment_status, next_action: None, ..payment_data }; utils::store_data_in_redis( &state, updated_payment_data.payment_id.get_string_repr().to_owned(), updated_payment_data.clone(), state.conf.dummy_connector.payment_ttl, ) .await?; return Ok(api::ApplicationResponse::JsonForRedirection( api_models::payments::RedirectionResponse { return_url: String::new(), params: vec![], return_url_with_query_params: updated_payment_data .return_url .unwrap_or(state.conf.dummy_connector.default_return_url.clone()), http_method: "GET".to_string(), headers: vec![], }, )); } Ok(api::ApplicationResponse::JsonForRedirection( api_models::payments::RedirectionResponse { return_url: String::new(), params: vec![], return_url_with_query_params: state.conf.dummy_connector.default_return_url.clone(), http_method: "GET".to_string(), headers: vec![], }, )) } #[cfg(all(feature = "dummy_connector", feature = "v1"))] pub async fn refund_payment( state: SessionState, req: types::DummyConnectorRefundRequest, ) -> types::DummyConnectorResponse<types::DummyConnectorRefundResponse> { utils::tokio_mock_sleep( state.conf.dummy_connector.refund_duration, state.conf.dummy_connector.refund_tolerance, ) .await; let payment_id = req .payment_id .get_required_value("payment_id") .change_context(errors::DummyConnectorErrors::MissingRequiredField { field_name: "payment_id", })?; let mut payment_data = utils::get_payment_data_from_payment_id(&state, payment_id.get_string_repr().to_owned()) .await?; payment_data.is_eligible_for_refund(req.amount)?; let refund_id = generate_id_with_default_len(consts::REFUND_ID_PREFIX); payment_data.eligible_amount -= req.amount; utils::store_data_in_redis( &state, payment_id.get_string_repr().to_owned(), payment_data.to_owned(), state.conf.dummy_connector.payment_ttl, ) .await?; let refund_data = types::DummyConnectorRefundResponse::new( types::DummyConnectorStatus::Succeeded, refund_id.to_owned(), payment_data.currency, common_utils::date_time::now(), payment_data.amount, req.amount, ); utils::store_data_in_redis( &state, refund_id, refund_data.to_owned(), state.conf.dummy_connector.refund_ttl, ) .await?; Ok(api::ApplicationResponse::Json(refund_data)) } #[cfg(all(feature = "dummy_connector", feature = "v1"))] pub async fn refund_data( state: SessionState, req: types::DummyConnectorRefundRetrieveRequest, ) -> types::DummyConnectorResponse<types::DummyConnectorRefundResponse> { let refund_id = req.refund_id; utils::tokio_mock_sleep( state.conf.dummy_connector.refund_retrieve_duration, state.conf.dummy_connector.refund_retrieve_tolerance, ) .await; let redis_conn = state .store .get_redis_conn() .change_context(errors::DummyConnectorErrors::InternalServerError) .attach_printable("Failed to get redis connection")?; let refund_data = redis_conn .get_and_deserialize_key::<types::DummyConnectorRefundResponse>( &refund_id.as_str().into(), "DummyConnectorRefundResponse", ) .await .change_context(errors::DummyConnectorErrors::RefundNotFound)?; Ok(api::ApplicationResponse::Json(refund_data)) }
crates/router/src/routes/dummy_connector/core.rs
router::src::routes::dummy_connector::core
1,662
true
// File: crates/router/src/routes/dummy_connector/consts.rs // Module: router::src::routes::dummy_connector::consts pub const ATTEMPT_ID_PREFIX: &str = "dummy_attempt"; pub const REFUND_ID_PREFIX: &str = "dummy_ref"; pub const THREE_DS_CSS: &str = include_str!("threeds_page.css"); pub const DUMMY_CONNECTOR_UPI_FAILURE_VPA_ID: &str = "failure@upi"; pub const DUMMY_CONNECTOR_UPI_SUCCESS_VPA_ID: &str = "success@upi";
crates/router/src/routes/dummy_connector/consts.rs
router::src::routes::dummy_connector::consts
119
true
// File: crates/router/src/routes/dummy_connector/types.rs // Module: router::src::routes::dummy_connector::types use api_models::enums::Currency; use common_utils::{errors::CustomResult, generate_id_with_default_len, pii}; use error_stack::report; use masking::Secret; use router_env::types::FlowMetric; use strum::Display; use time::PrimitiveDateTime; use super::{consts, errors::DummyConnectorErrors}; use crate::services; #[derive(Debug, Display, Clone, PartialEq, Eq)] #[allow(clippy::enum_variant_names)] pub enum Flow { DummyPaymentCreate, DummyPaymentRetrieve, DummyPaymentAuthorize, DummyPaymentComplete, DummyRefundCreate, DummyRefundRetrieve, } impl FlowMetric for Flow {} #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, strum::Display, Eq, PartialEq)] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DummyConnectors { #[serde(rename = "phonypay")] #[strum(serialize = "phonypay")] PhonyPay, #[serde(rename = "fauxpay")] #[strum(serialize = "fauxpay")] FauxPay, #[serde(rename = "pretendpay")] #[strum(serialize = "pretendpay")] PretendPay, StripeTest, AdyenTest, CheckoutTest, PaypalTest, } impl DummyConnectors { pub fn get_connector_image_link(self, base_url: &str) -> String { let image_name = match self { Self::PhonyPay => "PHONYPAY.svg", Self::FauxPay => "FAUXPAY.svg", Self::PretendPay => "PRETENDPAY.svg", Self::StripeTest => "STRIPE_TEST.svg", Self::PaypalTest => "PAYPAL_TEST.svg", _ => "PHONYPAY.svg", }; format!("{base_url}{image_name}") } } #[derive( Default, serde::Serialize, serde::Deserialize, strum::Display, Clone, PartialEq, Debug, Eq, )] #[serde(rename_all = "lowercase")] pub enum DummyConnectorStatus { Succeeded, #[default] Processing, Failed, } #[derive(Clone, Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)] pub struct DummyConnectorPaymentAttempt { pub timestamp: PrimitiveDateTime, pub attempt_id: String, pub payment_id: common_utils::id_type::PaymentId, pub payment_request: DummyConnectorPaymentRequest, } impl From<DummyConnectorPaymentRequest> for DummyConnectorPaymentAttempt { fn from(payment_request: DummyConnectorPaymentRequest) -> Self { let timestamp = common_utils::date_time::now(); let payment_id = common_utils::id_type::PaymentId::default(); let attempt_id = generate_id_with_default_len(consts::ATTEMPT_ID_PREFIX); Self { timestamp, attempt_id, payment_id, payment_request, } } } impl DummyConnectorPaymentAttempt { pub fn build_payment_data( self, status: DummyConnectorStatus, next_action: Option<DummyConnectorNextAction>, return_url: Option<String>, ) -> DummyConnectorPaymentData { DummyConnectorPaymentData { attempt_id: self.attempt_id, payment_id: self.payment_id, status, amount: self.payment_request.amount, eligible_amount: self.payment_request.amount, connector: self.payment_request.connector, created: self.timestamp, currency: self.payment_request.currency, payment_method_type: self.payment_request.payment_method_data.into(), next_action, return_url, } } } #[derive(Clone, Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)] pub struct DummyConnectorPaymentRequest { pub amount: i64, pub currency: Currency, pub payment_method_data: DummyConnectorPaymentMethodData, pub return_url: Option<String>, pub connector: DummyConnectors, } pub trait GetPaymentMethodDetails { fn get_name(&self) -> &'static str; fn get_image_link(&self, base_url: &str) -> String; } #[derive(Clone, Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)] #[serde(rename_all = "lowercase")] pub enum DummyConnectorPaymentMethodData { Card(DummyConnectorCard), Upi(DummyConnectorUpi), Wallet(DummyConnectorWallet), PayLater(DummyConnectorPayLater), } #[derive( Default, serde::Serialize, serde::Deserialize, strum::Display, PartialEq, Debug, Clone, )] #[serde(rename_all = "lowercase")] pub enum DummyConnectorPaymentMethodType { #[default] Card, Upi(DummyConnectorUpiType), Wallet(DummyConnectorWallet), PayLater(DummyConnectorPayLater), } impl From<DummyConnectorPaymentMethodData> for DummyConnectorPaymentMethodType { fn from(value: DummyConnectorPaymentMethodData) -> Self { match value { DummyConnectorPaymentMethodData::Card(_) => Self::Card, DummyConnectorPaymentMethodData::Upi(upi_data) => match upi_data { DummyConnectorUpi::UpiCollect(_) => Self::Upi(DummyConnectorUpiType::UpiCollect), }, DummyConnectorPaymentMethodData::Wallet(wallet) => Self::Wallet(wallet), DummyConnectorPaymentMethodData::PayLater(pay_later) => Self::PayLater(pay_later), } } } impl GetPaymentMethodDetails for DummyConnectorPaymentMethodType { fn get_name(&self) -> &'static str { match self { Self::Card => "3D Secure", Self::Upi(upi_type) => upi_type.get_name(), Self::Wallet(wallet) => wallet.get_name(), Self::PayLater(pay_later) => pay_later.get_name(), } } fn get_image_link(&self, base_url: &str) -> String { match self { Self::Card => format!("{}{}", base_url, "CARD.svg"), Self::Upi(upi_type) => upi_type.get_image_link(base_url), Self::Wallet(wallet) => wallet.get_image_link(base_url), Self::PayLater(pay_later) => pay_later.get_image_link(base_url), } } } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct DummyConnectorCard { pub name: Secret<String>, pub number: cards::CardNumber, pub expiry_month: Secret<String>, pub expiry_year: Secret<String>, pub cvc: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct DummyConnectorUpiCollect { pub vpa_id: Secret<String, pii::UpiVpaMaskingStrategy>, } #[derive(Clone, Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum DummyConnectorUpi { UpiCollect(DummyConnectorUpiCollect), } pub enum DummyConnectorCardFlow { NoThreeDS(DummyConnectorStatus, Option<DummyConnectorErrors>), ThreeDS(DummyConnectorStatus, Option<DummyConnectorErrors>), } #[derive(Clone, Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)] pub enum DummyConnectorWallet { GooglePay, Paypal, WeChatPay, MbWay, AliPay, AliPayHK, } #[derive(Clone, Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)] pub enum DummyConnectorUpiType { UpiCollect, } impl GetPaymentMethodDetails for DummyConnectorUpiType { fn get_name(&self) -> &'static str { match self { Self::UpiCollect => "UPI Collect", } } fn get_image_link(&self, base_url: &str) -> String { let image_name = match self { Self::UpiCollect => "UPI_COLLECT.svg", }; format!("{base_url}{image_name}") } } impl GetPaymentMethodDetails for DummyConnectorWallet { fn get_name(&self) -> &'static str { match self { Self::GooglePay => "Google Pay", Self::Paypal => "PayPal", Self::WeChatPay => "WeChat Pay", Self::MbWay => "Mb Way", Self::AliPay => "Alipay", Self::AliPayHK => "Alipay HK", } } fn get_image_link(&self, base_url: &str) -> String { let image_name = match self { Self::GooglePay => "GOOGLE_PAY.svg", Self::Paypal => "PAYPAL.svg", Self::WeChatPay => "WECHAT_PAY.svg", Self::MbWay => "MBWAY.svg", Self::AliPay => "ALIPAY.svg", Self::AliPayHK => "ALIPAY.svg", }; format!("{base_url}{image_name}") } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Eq, PartialEq)] pub enum DummyConnectorPayLater { Klarna, Affirm, AfterPayClearPay, } impl GetPaymentMethodDetails for DummyConnectorPayLater { fn get_name(&self) -> &'static str { match self { Self::Klarna => "Klarna", Self::Affirm => "Affirm", Self::AfterPayClearPay => "Afterpay Clearpay", } } fn get_image_link(&self, base_url: &str) -> String { let image_name = match self { Self::Klarna => "KLARNA.svg", Self::Affirm => "AFFIRM.svg", Self::AfterPayClearPay => "AFTERPAY.svg", }; format!("{base_url}{image_name}") } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)] pub struct DummyConnectorPaymentData { pub attempt_id: String, pub payment_id: common_utils::id_type::PaymentId, pub status: DummyConnectorStatus, pub amount: i64, pub eligible_amount: i64, pub currency: Currency, #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, pub payment_method_type: DummyConnectorPaymentMethodType, pub connector: DummyConnectors, pub next_action: Option<DummyConnectorNextAction>, pub return_url: Option<String>, } impl DummyConnectorPaymentData { pub fn is_eligible_for_refund(&self, refund_amount: i64) -> DummyConnectorResult<()> { if self.eligible_amount < refund_amount { return Err( report!(DummyConnectorErrors::RefundAmountExceedsPaymentAmount) .attach_printable("Eligible amount is lesser than refund amount"), ); } if self.status != DummyConnectorStatus::Succeeded { return Err(report!(DummyConnectorErrors::PaymentNotSuccessful) .attach_printable("Payment is not successful to process the refund")); } Ok(()) } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)] #[serde(rename_all = "snake_case")] pub enum DummyConnectorNextAction { RedirectToUrl(String), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct DummyConnectorPaymentResponse { pub status: DummyConnectorStatus, pub id: common_utils::id_type::PaymentId, pub amount: i64, pub currency: Currency, #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, pub payment_method_type: DummyConnectorPaymentMethodType, pub next_action: Option<DummyConnectorNextAction>, } impl From<DummyConnectorPaymentData> for DummyConnectorPaymentResponse { fn from(value: DummyConnectorPaymentData) -> Self { Self { status: value.status, id: value.payment_id, amount: value.amount, currency: value.currency, created: value.created, payment_method_type: value.payment_method_type, next_action: value.next_action, } } } #[derive(Default, Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct DummyConnectorPaymentRetrieveRequest { pub payment_id: String, } #[derive(Default, Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct DummyConnectorPaymentConfirmRequest { pub attempt_id: String, } #[derive(Default, Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct DummyConnectorPaymentCompleteRequest { pub attempt_id: String, pub confirm: bool, } #[derive(Default, Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct DummyConnectorPaymentCompleteBody { pub confirm: bool, } #[derive(Default, Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)] pub struct DummyConnectorRefundRequest { pub amount: i64, pub payment_id: Option<common_utils::id_type::PaymentId>, } #[derive(Clone, Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)] pub struct DummyConnectorRefundResponse { pub status: DummyConnectorStatus, pub id: String, pub currency: Currency, #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, pub payment_amount: i64, pub refund_amount: i64, } impl DummyConnectorRefundResponse { pub fn new( status: DummyConnectorStatus, id: String, currency: Currency, created: PrimitiveDateTime, payment_amount: i64, refund_amount: i64, ) -> Self { Self { status, id, currency, created, payment_amount, refund_amount, } } } #[derive(Default, Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct DummyConnectorRefundRetrieveRequest { pub refund_id: String, } pub type DummyConnectorResponse<T> = CustomResult<services::ApplicationResponse<T>, DummyConnectorErrors>; pub type DummyConnectorResult<T> = CustomResult<T, DummyConnectorErrors>; pub struct DummyConnectorUpiFlow { pub status: DummyConnectorStatus, pub error: Option<DummyConnectorErrors>, pub is_next_action_required: bool, }
crates/router/src/routes/dummy_connector/types.rs
router::src::routes::dummy_connector::types
3,096
true
// File: crates/router/src/routes/dummy_connector/errors.rs // Module: router::src::routes::dummy_connector::errors #[derive(Clone, Debug, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum ErrorType { ServerNotAvailable, ObjectNotFound, InvalidRequestError, } #[derive(Debug, Clone, router_derive::ApiError)] #[error(error_type_enum = ErrorType)] // TODO: Remove this line if InternalServerError is used anywhere #[allow(dead_code)] pub enum DummyConnectorErrors { #[error(error_type = ErrorType::ServerNotAvailable, code = "DC_00", message = "Something went wrong")] InternalServerError, #[error(error_type = ErrorType::ObjectNotFound, code = "DC_01", message = "Payment does not exist in our records")] PaymentNotFound, #[error(error_type = ErrorType::InvalidRequestError, code = "DC_02", message = "Missing required param: {field_name}")] MissingRequiredField { field_name: &'static str }, #[error(error_type = ErrorType::InvalidRequestError, code = "DC_03", message = "The refund amount exceeds the amount captured")] RefundAmountExceedsPaymentAmount, #[error(error_type = ErrorType::InvalidRequestError, code = "DC_04", message = "Card not supported. Please use test cards")] CardNotSupported, #[error(error_type = ErrorType::ObjectNotFound, code = "DC_05", message = "Refund does not exist in our records")] RefundNotFound, #[error(error_type = ErrorType::InvalidRequestError, code = "DC_06", message = "Payment is not successful")] PaymentNotSuccessful, #[error(error_type = ErrorType::ServerNotAvailable, code = "DC_07", message = "Error occurred while storing the payment")] PaymentStoringError, #[error(error_type = ErrorType::InvalidRequestError, code = "DC_08", message = "Payment declined: {message}")] PaymentDeclined { message: &'static str }, } impl core::fmt::Display for DummyConnectorErrors { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, r#"{{"error":{}}}"#, serde_json::to_string(self) .unwrap_or_else(|_| "Dummy connector error response".to_string()) ) } } impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for DummyConnectorErrors { fn switch(&self) -> api_models::errors::types::ApiErrorResponse { use api_models::errors::types::{ApiError, ApiErrorResponse as AER}; match self { Self::InternalServerError => { AER::InternalServerError(ApiError::new("DC", 0, self.error_message(), None)) } Self::PaymentNotFound => { AER::NotFound(ApiError::new("DC", 1, self.error_message(), None)) } Self::MissingRequiredField { field_name: _ } => { AER::BadRequest(ApiError::new("DC", 2, self.error_message(), None)) } Self::RefundAmountExceedsPaymentAmount => { AER::InternalServerError(ApiError::new("DC", 3, self.error_message(), None)) } Self::CardNotSupported => { AER::BadRequest(ApiError::new("DC", 4, self.error_message(), None)) } Self::RefundNotFound => { AER::NotFound(ApiError::new("DC", 5, self.error_message(), None)) } Self::PaymentNotSuccessful => { AER::BadRequest(ApiError::new("DC", 6, self.error_message(), None)) } Self::PaymentStoringError => { AER::InternalServerError(ApiError::new("DC", 7, self.error_message(), None)) } Self::PaymentDeclined { message: _ } => { AER::BadRequest(ApiError::new("DC", 8, self.error_message(), None)) } } } }
crates/router/src/routes/dummy_connector/errors.rs
router::src::routes::dummy_connector::errors
899
true
// File: crates/router/src/routes/dummy_connector/utils.rs // Module: router::src::routes::dummy_connector::utils use std::fmt::Debug; use common_utils::ext_traits::AsyncExt; use error_stack::{report, ResultExt}; use masking::PeekInterface; use maud::html; use rand::{distributions::Uniform, prelude::Distribution}; use tokio::time as tokio; use super::{ consts, errors, types::{self, GetPaymentMethodDetails}, }; use crate::{ configs::settings, routes::{dummy_connector::types::DummyConnectors, SessionState}, }; pub async fn tokio_mock_sleep(delay: u64, tolerance: u64) { let mut rng = rand::thread_rng(); // TODO: change this to `Uniform::try_from` // this would require changing the fn signature // to return a Result let effective_delay = Uniform::from((delay - tolerance)..(delay + tolerance)); tokio::sleep(tokio::Duration::from_millis( effective_delay.sample(&mut rng), )) .await } pub async fn store_data_in_redis( state: &SessionState, key: String, data: impl serde::Serialize + Debug, ttl: i64, ) -> types::DummyConnectorResult<()> { let redis_conn = state .store .get_redis_conn() .change_context(errors::DummyConnectorErrors::InternalServerError) .attach_printable("Failed to get redis connection")?; redis_conn .serialize_and_set_key_with_expiry(&key.into(), data, ttl) .await .change_context(errors::DummyConnectorErrors::PaymentStoringError) .attach_printable("Failed to add data in redis")?; Ok(()) } pub async fn get_payment_data_from_payment_id( state: &SessionState, payment_id: String, ) -> types::DummyConnectorResult<types::DummyConnectorPaymentData> { let redis_conn = state .store .get_redis_conn() .change_context(errors::DummyConnectorErrors::InternalServerError) .attach_printable("Failed to get redis connection")?; redis_conn .get_and_deserialize_key::<types::DummyConnectorPaymentData>( &payment_id.as_str().into(), "types DummyConnectorPaymentData", ) .await .change_context(errors::DummyConnectorErrors::PaymentNotFound) } pub async fn get_payment_data_by_attempt_id( state: &SessionState, attempt_id: String, ) -> types::DummyConnectorResult<types::DummyConnectorPaymentData> { let redis_conn = state .store .get_redis_conn() .change_context(errors::DummyConnectorErrors::InternalServerError) .attach_printable("Failed to get redis connection")?; redis_conn .get_and_deserialize_key::<String>(&attempt_id.as_str().into(), "String") .await .async_and_then(|payment_id| async move { redis_conn .get_and_deserialize_key::<types::DummyConnectorPaymentData>( &payment_id.as_str().into(), "DummyConnectorPaymentData", ) .await }) .await .change_context(errors::DummyConnectorErrors::PaymentNotFound) } pub fn get_authorize_page( payment_data: types::DummyConnectorPaymentData, return_url: String, dummy_connector_conf: &settings::DummyConnector, ) -> String { let mode = payment_data.payment_method_type.get_name(); let image = payment_data .payment_method_type .get_image_link(dummy_connector_conf.assets_base_url.as_str()); let connector_image = payment_data .connector .get_connector_image_link(dummy_connector_conf.assets_base_url.as_str()); let currency = payment_data.currency.to_string(); html! { head { title { "Authorize Payment" } style { (consts::THREE_DS_CSS) } link rel="icon" href=(connector_image) {} } body { div.heading { img.logo src="https://app.hyperswitch.io/assets/Dark/hyperswitchLogoIconWithText.svg" alt="Hyperswitch Logo" {} h1 { "Test Payment Page" } } div.container { div.payment_details { img src=(image) {} div.border_horizontal {} img src=(connector_image) {} } (maud::PreEscaped( format!(r#" <p class="disclaimer"> This is a test payment of <span id="amount"></span> {} using {} <script> document.getElementById("amount").innerHTML = ({} / 100).toFixed(2); </script> </p> "#, currency, mode, payment_data.amount) ) ) p { b { "Real money will not be debited for the payment." } " \ You can choose to simulate successful or failed payment while testing this payment." } div.user_action { button.authorize onclick=(format!("window.location.href='{}?confirm=true'", return_url)) { "Complete Payment" } button.reject onclick=(format!("window.location.href='{}?confirm=false'", return_url)) { "Reject Payment" } } } div.container { p.disclaimer { "What is this page?" } p { "This page is just a simulation for integration and testing purpose. \ In live mode, this page will not be displayed and the user will be taken to \ the Bank page (or) Google Pay cards popup (or) original payment method's page. \ Contact us for any queries." } div.contact { div.contact_item.hover_cursor onclick=(dummy_connector_conf.slack_invite_url) { img src="https://hyperswitch.io/logos/logo_slack.svg" alt="Slack Logo" {} } div.contact_item.hover_cursor onclick=(dummy_connector_conf.discord_invite_url) { img src="https://hyperswitch.io/logos/logo_discord.svg" alt="Discord Logo" {} } div.border_vertical {} div.contact_item.email { p { "Or email us at" } a href="mailto:hyperswitch@juspay.in" { "hyperswitch@juspay.in" } } } } } } .into_string() } pub fn get_expired_page(dummy_connector_conf: &settings::DummyConnector) -> String { html! { head { title { "Authorize Payment" } style { (consts::THREE_DS_CSS) } link rel="icon" href="https://app.hyperswitch.io/HyperswitchFavicon.png" {} } body { div.heading { img.logo src="https://app.hyperswitch.io/assets/Dark/hyperswitchLogoIconWithText.svg" alt="Hyperswitch Logo" {} h1 { "Test Payment Page" } } div.container { p.disclaimer { "This link is not valid or it is expired" } } div.container { p.disclaimer { "What is this page?" } p { "This page is just a simulation for integration and testing purpose.\ In live mode, this is not visible. Contact us for any queries." } div.contact { div.contact_item.hover_cursor onclick=(dummy_connector_conf.slack_invite_url) { img src="https://hyperswitch.io/logos/logo_slack.svg" alt="Slack Logo" {} } div.contact_item.hover_cursor onclick=(dummy_connector_conf.discord_invite_url) { img src="https://hyperswitch.io/logos/logo_discord.svg" alt="Discord Logo" {} } div.border_vertical {} div.contact_item.email { p { "Or email us at" } a href="mailto:hyperswitch@juspay.in" { "hyperswitch@juspay.in" } } } } } } .into_string() } pub trait ProcessPaymentAttempt { fn build_payment_data_from_payment_attempt( self, payment_attempt: types::DummyConnectorPaymentAttempt, redirect_url: String, ) -> types::DummyConnectorResult<types::DummyConnectorPaymentData>; } impl ProcessPaymentAttempt for types::DummyConnectorCard { fn build_payment_data_from_payment_attempt( self, payment_attempt: types::DummyConnectorPaymentAttempt, redirect_url: String, ) -> types::DummyConnectorResult<types::DummyConnectorPaymentData> { match self.get_flow_from_card_number(payment_attempt.payment_request.connector.clone())? { types::DummyConnectorCardFlow::NoThreeDS(status, error) => { if let Some(error) = error { Err(error)?; } Ok(payment_attempt.build_payment_data(status, None, None)) } types::DummyConnectorCardFlow::ThreeDS(_, _) => { Ok(payment_attempt.clone().build_payment_data( types::DummyConnectorStatus::Processing, Some(types::DummyConnectorNextAction::RedirectToUrl(redirect_url)), payment_attempt.payment_request.return_url, )) } } } } impl ProcessPaymentAttempt for types::DummyConnectorUpiCollect { fn build_payment_data_from_payment_attempt( self, payment_attempt: types::DummyConnectorPaymentAttempt, redirect_url: String, ) -> types::DummyConnectorResult<types::DummyConnectorPaymentData> { let upi_collect_response = self.get_flow_from_upi_collect()?; if let Some(error) = upi_collect_response.error { Err(error)?; } let next_action = upi_collect_response .is_next_action_required .then_some(types::DummyConnectorNextAction::RedirectToUrl(redirect_url)); let return_url = payment_attempt.payment_request.return_url.clone(); Ok( payment_attempt.build_payment_data( upi_collect_response.status, next_action, return_url, ), ) } } impl types::DummyConnectorUpiCollect { pub fn get_flow_from_upi_collect( self, ) -> types::DummyConnectorResult<types::DummyConnectorUpiFlow> { let vpa_id = self.vpa_id.peek(); match vpa_id.as_str() { consts::DUMMY_CONNECTOR_UPI_FAILURE_VPA_ID => Ok(types::DummyConnectorUpiFlow { status: types::DummyConnectorStatus::Failed, error: errors::DummyConnectorErrors::PaymentNotSuccessful.into(), is_next_action_required: false, }), consts::DUMMY_CONNECTOR_UPI_SUCCESS_VPA_ID => Ok(types::DummyConnectorUpiFlow { status: types::DummyConnectorStatus::Processing, error: None, is_next_action_required: true, }), _ => Ok(types::DummyConnectorUpiFlow { status: types::DummyConnectorStatus::Failed, error: Some(errors::DummyConnectorErrors::PaymentDeclined { message: "Invalid Upi id", }), is_next_action_required: false, }), } } } impl types::DummyConnectorCard { pub fn get_flow_from_card_number( self, connector: DummyConnectors, ) -> types::DummyConnectorResult<types::DummyConnectorCardFlow> { let card_number = self.number.peek(); match card_number.as_str() { "4111111111111111" | "4242424242424242" | "5555555555554444" | "38000000000006" | "378282246310005" | "6011111111111117" => { Ok(types::DummyConnectorCardFlow::NoThreeDS( types::DummyConnectorStatus::Succeeded, None, )) } "5105105105105100" | "4000000000000002" => { Ok(types::DummyConnectorCardFlow::NoThreeDS( types::DummyConnectorStatus::Failed, Some(errors::DummyConnectorErrors::PaymentDeclined { message: "Card declined", }), )) } "4000000000009995" => { if connector == DummyConnectors::StripeTest { Ok(types::DummyConnectorCardFlow::NoThreeDS( types::DummyConnectorStatus::Succeeded, None, )) } else { Ok(types::DummyConnectorCardFlow::NoThreeDS( types::DummyConnectorStatus::Failed, Some(errors::DummyConnectorErrors::PaymentDeclined { message: "Internal Server Error from Connector, Please try again later", }), )) } } "4000000000009987" => Ok(types::DummyConnectorCardFlow::NoThreeDS( types::DummyConnectorStatus::Failed, Some(errors::DummyConnectorErrors::PaymentDeclined { message: "Lost card", }), )), "4000000000009979" => Ok(types::DummyConnectorCardFlow::NoThreeDS( types::DummyConnectorStatus::Failed, Some(errors::DummyConnectorErrors::PaymentDeclined { message: "Stolen card", }), )), "4000003800000446" => Ok(types::DummyConnectorCardFlow::ThreeDS( types::DummyConnectorStatus::Succeeded, None, )), _ => Err(report!(errors::DummyConnectorErrors::CardNotSupported) .attach_printable("The card is not supported")), } } } impl ProcessPaymentAttempt for types::DummyConnectorWallet { fn build_payment_data_from_payment_attempt( self, payment_attempt: types::DummyConnectorPaymentAttempt, redirect_url: String, ) -> types::DummyConnectorResult<types::DummyConnectorPaymentData> { Ok(payment_attempt.clone().build_payment_data( types::DummyConnectorStatus::Processing, Some(types::DummyConnectorNextAction::RedirectToUrl(redirect_url)), payment_attempt.payment_request.return_url, )) } } impl ProcessPaymentAttempt for types::DummyConnectorPayLater { fn build_payment_data_from_payment_attempt( self, payment_attempt: types::DummyConnectorPaymentAttempt, redirect_url: String, ) -> types::DummyConnectorResult<types::DummyConnectorPaymentData> { Ok(payment_attempt.clone().build_payment_data( types::DummyConnectorStatus::Processing, Some(types::DummyConnectorNextAction::RedirectToUrl(redirect_url)), payment_attempt.payment_request.return_url, )) } } impl ProcessPaymentAttempt for types::DummyConnectorPaymentMethodData { fn build_payment_data_from_payment_attempt( self, payment_attempt: types::DummyConnectorPaymentAttempt, redirect_url: String, ) -> types::DummyConnectorResult<types::DummyConnectorPaymentData> { match self { Self::Card(card) => { card.build_payment_data_from_payment_attempt(payment_attempt, redirect_url) } Self::Upi(upi_data) => match upi_data { types::DummyConnectorUpi::UpiCollect(upi_collect) => upi_collect .build_payment_data_from_payment_attempt(payment_attempt, redirect_url), }, Self::Wallet(wallet) => { wallet.build_payment_data_from_payment_attempt(payment_attempt, redirect_url) } Self::PayLater(pay_later) => { pay_later.build_payment_data_from_payment_attempt(payment_attempt, redirect_url) } } } } impl types::DummyConnectorPaymentData { pub fn process_payment_attempt( state: &SessionState, payment_attempt: types::DummyConnectorPaymentAttempt, ) -> types::DummyConnectorResult<Self> { let redirect_url = format!( "{}/dummy-connector/authorize/{}", state.base_url, payment_attempt.attempt_id ); payment_attempt .clone() .payment_request .payment_method_data .build_payment_data_from_payment_attempt(payment_attempt, redirect_url) } }
crates/router/src/routes/dummy_connector/utils.rs
router::src::routes::dummy_connector::utils
3,501
true
// File: crates/router/src/routes/disputes/utils.rs // Module: router::src::routes::disputes::utils use actix_multipart::{Field, Multipart}; use actix_web::web::Bytes; use common_utils::{errors::CustomResult, ext_traits::StringExt, fp_utils}; use error_stack::ResultExt; use futures::{StreamExt, TryStreamExt}; use crate::{ core::{errors, files::helpers}, types::api::{disputes, files}, utils::OptionExt, }; pub async fn parse_evidence_type( field: &mut Field, ) -> CustomResult<Option<disputes::EvidenceType>, errors::ApiErrorResponse> { let purpose = helpers::read_string(field).await; match purpose { Some(evidence_type) => Ok(Some( evidence_type .parse_enum("Evidence Type") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error parsing evidence type")?, )), _ => Ok(None), } } pub async fn get_attach_evidence_request( mut payload: Multipart, ) -> CustomResult<disputes::AttachEvidenceRequest, errors::ApiErrorResponse> { let mut option_evidence_type: Option<disputes::EvidenceType> = None; let mut dispute_id: Option<String> = None; let mut file_name: Option<String> = None; let mut file_content: Option<Vec<Bytes>> = None; while let Ok(Some(mut field)) = payload.try_next().await { let content_disposition = field.content_disposition(); let field_name = content_disposition.get_name(); // Parse the different parameters expected in the multipart request match field_name { Some("file") => { file_name = content_disposition.get_filename().map(String::from); //Collect the file content and throw error if something fails let mut file_data = Vec::new(); let mut stream = field.into_stream(); while let Some(chunk) = stream.next().await { match chunk { Ok(bytes) => file_data.push(bytes), Err(err) => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| format!("File parsing error: {err}"))?, } } file_content = Some(file_data) } Some("dispute_id") => { dispute_id = helpers::read_string(&mut field).await; } Some("evidence_type") => { option_evidence_type = parse_evidence_type(&mut field).await?; } // Can ignore other params _ => (), } } let evidence_type = option_evidence_type.get_required_value("evidence_type")?; let file = file_content.get_required_value("file")?.concat().to_vec(); //Get and validate file size let file_size = i32::try_from(file.len()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("File size error")?; // Check if empty file and throw error fp_utils::when(file_size <= 0, || { Err(errors::ApiErrorResponse::MissingFile) .attach_printable("Missing / Invalid file in the request") })?; // Get file mime type using 'infer' let kind = infer::get(&file).ok_or(errors::ApiErrorResponse::MissingFileContentType)?; let file_type = kind .mime_type() .parse::<mime::Mime>() .change_context(errors::ApiErrorResponse::MissingFileContentType) .attach_printable("File content type error")?; let create_file_request = files::CreateFileRequest { file, file_name, file_size, file_type, purpose: files::FilePurpose::DisputeEvidence, dispute_id, }; Ok(disputes::AttachEvidenceRequest { evidence_type, create_file_request, }) }
crates/router/src/routes/disputes/utils.rs
router::src::routes::disputes::utils
832
true
// File: crates/router/src/routes/user/theme.rs // Module: router::src::routes::user::theme use actix_multipart::form::MultipartForm; use actix_web::{web, HttpRequest, HttpResponse}; use api_models::user::theme as theme_api; use common_utils::types::user::ThemeLineage; use masking::Secret; use router_env::Flow; use crate::{ core::{api_locking, user::theme as theme_core}, routes::AppState, services::{api, authentication as auth, authorization::permissions::Permission}, }; pub async fn get_theme_using_lineage( state: web::Data<AppState>, req: HttpRequest, query: web::Query<ThemeLineage>, ) -> HttpResponse { let flow = Flow::GetThemeUsingLineage; let lineage = query.into_inner(); Box::pin(api::server_wrap( flow, state, &req, lineage, |state, _, lineage, _| theme_core::get_theme_using_lineage(state, lineage), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } pub async fn get_theme_using_theme_id( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, ) -> HttpResponse { let flow = Flow::GetThemeUsingThemeId; let payload = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, _, payload, _| theme_core::get_theme_using_theme_id(state, payload), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } pub async fn upload_file_to_theme_storage( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, MultipartForm(payload): MultipartForm<theme_api::UploadFileAssetData>, ) -> HttpResponse { let flow = Flow::UploadFileToThemeStorage; let theme_id = path.into_inner(); let payload = theme_api::UploadFileRequest { asset_name: payload.asset_name.into_inner(), asset_data: Secret::new(payload.asset_data.data.to_vec()), }; Box::pin(api::server_wrap( flow, state, &req, payload, |state, _, payload, _| { theme_core::upload_file_to_theme_storage(state, theme_id.clone(), payload) }, &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } pub async fn create_theme( state: web::Data<AppState>, req: HttpRequest, payload: web::Json<theme_api::CreateThemeRequest>, ) -> HttpResponse { let flow = Flow::CreateTheme; let payload = payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, _, payload, _| theme_core::create_theme(state, payload), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } pub async fn update_theme( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, payload: web::Json<theme_api::UpdateThemeRequest>, ) -> HttpResponse { let flow = Flow::UpdateTheme; let theme_id = path.into_inner(); let payload = payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, _, payload, _| theme_core::update_theme(state, theme_id.clone(), payload), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } pub async fn delete_theme( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, ) -> HttpResponse { let flow = Flow::DeleteTheme; let theme_id = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, theme_id, |state, _, theme_id, _| theme_core::delete_theme(state, theme_id), &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } pub async fn create_user_theme( state: web::Data<AppState>, req: HttpRequest, payload: web::Json<theme_api::CreateUserThemeRequest>, ) -> HttpResponse { let flow = Flow::CreateUserTheme; let payload = payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, user: auth::UserFromToken, payload, _| { theme_core::create_user_theme(state, user, payload) }, &auth::JWTAuth { permission: Permission::OrganizationThemeWrite, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn get_user_theme_using_theme_id( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, ) -> HttpResponse { let flow = Flow::GetUserThemeUsingThemeId; let payload = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, user: auth::UserFromToken, payload, _| { theme_core::get_user_theme_using_theme_id(state, user, payload) }, &auth::JWTAuth { permission: Permission::OrganizationThemeRead, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn update_user_theme( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, payload: web::Json<theme_api::UpdateThemeRequest>, ) -> HttpResponse { let flow = Flow::UpdateUserTheme; let theme_id = path.into_inner(); let payload = payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, user: auth::UserFromToken, payload, _| { theme_core::update_user_theme(state, theme_id.clone(), user, payload) }, &auth::JWTAuth { permission: Permission::OrganizationThemeWrite, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn delete_user_theme( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, ) -> HttpResponse { let flow = Flow::DeleteUserTheme; let theme_id = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, theme_id, |state, user: auth::UserFromToken, theme_id, _| { theme_core::delete_user_theme(state, user, theme_id) }, &auth::JWTAuth { permission: Permission::OrganizationThemeWrite, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn upload_file_to_user_theme_storage( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, MultipartForm(payload): MultipartForm<theme_api::UploadFileAssetData>, ) -> HttpResponse { let flow = Flow::UploadFileToUserThemeStorage; let theme_id = path.into_inner(); let payload = theme_api::UploadFileRequest { asset_name: payload.asset_name.into_inner(), asset_data: Secret::new(payload.asset_data.data.to_vec()), }; Box::pin(api::server_wrap( flow, state, &req, payload, |state, user: auth::UserFromToken, payload, _| { theme_core::upload_file_to_user_theme_storage(state, theme_id.clone(), user, payload) }, &auth::JWTAuth { permission: Permission::OrganizationThemeWrite, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn list_all_themes_in_lineage( state: web::Data<AppState>, req: HttpRequest, query: web::Query<theme_api::EntityTypeQueryParam>, ) -> HttpResponse { let flow = Flow::ListAllThemesInLineage; let entity_type = query.into_inner().entity_type; Box::pin(api::server_wrap( flow, state, &req, (), |state, user: auth::UserFromToken, _payload, _| { theme_core::list_all_themes_in_lineage(state, user, entity_type) }, &auth::JWTAuth { permission: Permission::OrganizationThemeRead, }, api_locking::LockAction::NotApplicable, )) .await } pub async fn get_user_theme_using_lineage( state: web::Data<AppState>, req: HttpRequest, query: web::Query<theme_api::EntityTypeQueryParam>, ) -> HttpResponse { let flow = Flow::GetUserThemeUsingLineage; let entity_type = query.into_inner().entity_type; Box::pin(api::server_wrap( flow, state, &req, (), |state, user: auth::UserFromToken, _payload, _| { theme_core::get_user_theme_using_lineage(state, user, entity_type) }, &auth::JWTAuth { permission: Permission::OrganizationThemeRead, }, api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/user/theme.rs
router::src::routes::user::theme
2,083
true
// File: crates/router/src/routes/files/transformers.rs // Module: router::src::routes::files::transformers use actix_multipart::Multipart; use actix_web::web::Bytes; use common_utils::errors::CustomResult; use error_stack::ResultExt; use futures::{StreamExt, TryStreamExt}; use crate::{ core::{errors, files::helpers}, types::api::files::{self, CreateFileRequest}, utils::OptionExt, }; pub async fn get_create_file_request( mut payload: Multipart, ) -> CustomResult<CreateFileRequest, errors::ApiErrorResponse> { let mut option_purpose: Option<files::FilePurpose> = None; let mut dispute_id: Option<String> = None; let mut file_name: Option<String> = None; let mut file_content: Option<Vec<Bytes>> = None; while let Ok(Some(mut field)) = payload.try_next().await { let content_disposition = field.content_disposition(); let field_name = content_disposition.get_name(); // Parse the different parameters expected in the multipart request match field_name { Some("purpose") => { option_purpose = helpers::get_file_purpose(&mut field).await; } Some("file") => { file_name = content_disposition.get_filename().map(String::from); //Collect the file content and throw error if something fails let mut file_data = Vec::new(); let mut stream = field.into_stream(); while let Some(chunk) = stream.next().await { match chunk { Ok(bytes) => file_data.push(bytes), Err(err) => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable(format!("{}{}", "File parsing error: ", err))?, } } file_content = Some(file_data) } Some("dispute_id") => { dispute_id = helpers::read_string(&mut field).await; } // Can ignore other params _ => (), } } let purpose = option_purpose.get_required_value("purpose")?; let file = match file_content { Some(valid_file_content) => valid_file_content.concat().to_vec(), None => Err(errors::ApiErrorResponse::MissingFile) .attach_printable("Missing / Invalid file in the request")?, }; //Get and validate file size let file_size = i32::try_from(file.len()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("File size error")?; // Check if empty file and throw error if file_size <= 0 { Err(errors::ApiErrorResponse::MissingFile) .attach_printable("Missing / Invalid file in the request")? } // Get file mime type using 'infer' let kind = infer::get(&file).ok_or(errors::ApiErrorResponse::MissingFileContentType)?; let file_type = kind .mime_type() .parse::<mime::Mime>() .change_context(errors::ApiErrorResponse::MissingFileContentType) .attach_printable("File content type error")?; Ok(CreateFileRequest { file, file_name, file_size, file_type, purpose, dispute_id, }) }
crates/router/src/routes/files/transformers.rs
router::src::routes::files::transformers
696
true
// File: crates/router/src/consts/opensearch.rs // Module: router::src::consts::opensearch use api_models::analytics::search::SearchIndex; pub const fn get_search_indexes() -> [SearchIndex; 8] { [ SearchIndex::PaymentAttempts, SearchIndex::PaymentIntents, SearchIndex::Refunds, SearchIndex::Disputes, SearchIndex::SessionizerPaymentAttempts, SearchIndex::SessionizerPaymentIntents, SearchIndex::SessionizerRefunds, SearchIndex::SessionizerDisputes, ] } pub const SEARCH_INDEXES: [SearchIndex; 8] = get_search_indexes();
crates/router/src/consts/opensearch.rs
router::src::consts::opensearch
144
true
// File: crates/router/src/consts/user.rs // Module: router::src::consts::user use common_enums; use common_utils::consts::MAX_ALLOWED_MERCHANT_NAME_LENGTH; pub const MAX_NAME_LENGTH: usize = 70; /// The max length of company name and merchant should be same /// because we are deriving the merchant name from company name pub const MAX_COMPANY_NAME_LENGTH: usize = MAX_ALLOWED_MERCHANT_NAME_LENGTH; pub const RECOVERY_CODES_COUNT: usize = 8; pub const RECOVERY_CODE_LENGTH: usize = 8; // This is without counting the hyphen in between /// The number of digits composing the auth code. pub const TOTP_DIGITS: usize = 6; /// Duration in seconds of a step. pub const TOTP_VALIDITY_DURATION_IN_SECONDS: u64 = 30; /// Number of totps allowed as network delay. 1 would mean one totp before current totp and one totp after are valids. pub const TOTP_TOLERANCE: u8 = 1; /// Number of maximum attempts user has for totp pub const TOTP_MAX_ATTEMPTS: u8 = 4; /// Number of maximum attempts user has for recovery code pub const RECOVERY_CODE_MAX_ATTEMPTS: u8 = 4; /// The default number of organizations to fetch for a tenant-level user pub const ORG_LIST_LIMIT_FOR_TENANT: u32 = 20; pub const MAX_PASSWORD_LENGTH: usize = 70; pub const MIN_PASSWORD_LENGTH: usize = 8; pub const REDIS_TOTP_PREFIX: &str = "TOTP_"; pub const REDIS_RECOVERY_CODE_PREFIX: &str = "RC_"; pub const REDIS_TOTP_SECRET_PREFIX: &str = "TOTP_SEC_"; pub const REDIS_TOTP_SECRET_TTL_IN_SECS: i64 = 15 * 60; // 15 minutes pub const REDIS_TOTP_ATTEMPTS_PREFIX: &str = "TOTP_ATTEMPTS_"; pub const REDIS_RECOVERY_CODE_ATTEMPTS_PREFIX: &str = "RC_ATTEMPTS_"; pub const REDIS_TOTP_ATTEMPTS_TTL_IN_SECS: i64 = 5 * 60; // 5 mins pub const REDIS_RECOVERY_CODE_ATTEMPTS_TTL_IN_SECS: i64 = 10 * 60; // 10 mins pub const REDIS_SSO_PREFIX: &str = "SSO_"; pub const REDIS_SSO_TTL: i64 = 5 * 60; // 5 minutes pub const DEFAULT_PROFILE_NAME: &str = "default"; pub const DEFAULT_PRODUCT_TYPE: common_enums::MerchantProductType = common_enums::MerchantProductType::Orchestration;
crates/router/src/consts/user.rs
router::src::consts::user
599
true
// File: crates/router/src/consts/user_role.rs // Module: router::src::consts::user_role // User Roles pub const ROLE_ID_MERCHANT_ADMIN: &str = "merchant_admin"; pub const ROLE_ID_MERCHANT_VIEW_ONLY: &str = "merchant_view_only"; pub const ROLE_ID_MERCHANT_IAM_ADMIN: &str = "merchant_iam_admin"; pub const ROLE_ID_MERCHANT_DEVELOPER: &str = "merchant_developer"; pub const ROLE_ID_MERCHANT_OPERATOR: &str = "merchant_operator"; pub const ROLE_ID_MERCHANT_CUSTOMER_SUPPORT: &str = "merchant_customer_support"; pub const ROLE_ID_PROFILE_ADMIN: &str = "profile_admin"; pub const ROLE_ID_PROFILE_VIEW_ONLY: &str = "profile_view_only"; pub const ROLE_ID_PROFILE_IAM_ADMIN: &str = "profile_iam_admin"; pub const ROLE_ID_PROFILE_DEVELOPER: &str = "profile_developer"; pub const ROLE_ID_PROFILE_OPERATOR: &str = "profile_operator"; pub const ROLE_ID_PROFILE_CUSTOMER_SUPPORT: &str = "profile_customer_support"; pub const INTERNAL_USER_MERCHANT_ID: &str = "juspay000"; pub const MAX_ROLE_NAME_LENGTH: usize = 64;
crates/router/src/consts/user_role.rs
router::src::consts::user_role
256
true
// File: crates/router/src/services/logger.rs // Module: router::src::services::logger //! Logger of the system. pub use crate::logger::*;
crates/router/src/services/logger.rs
router::src::services::logger
33
true
// File: crates/router/src/services/openidconnect.rs // Module: router::src::services::openidconnect use common_utils::errors::ErrorSwitch; use error_stack::ResultExt; use external_services::http_client::client; use masking::{ExposeInterface, Secret}; use oidc::TokenResponse; use openidconnect::{self as oidc, core as oidc_core}; use redis_interface::RedisConnectionPool; use storage_impl::errors::ApiClientError; use crate::{ consts, core::errors::{UserErrors, UserResult}, routes::SessionState, types::domain::user::UserEmail, }; pub async fn get_authorization_url( state: SessionState, redirect_url: String, redirect_state: Secret<String>, base_url: Secret<String>, client_id: Secret<String>, ) -> UserResult<url::Url> { let discovery_document = get_discovery_document(base_url, &state).await?; let (auth_url, csrf_token, nonce) = get_oidc_core_client(discovery_document, client_id, None, redirect_url)? .authorize_url( oidc_core::CoreAuthenticationFlow::AuthorizationCode, || oidc::CsrfToken::new(redirect_state.expose()), oidc::Nonce::new_random, ) .add_scope(oidc::Scope::new("email".to_string())) .url(); // Save csrf & nonce as key value respectively let key = get_oidc_redis_key(csrf_token.secret()); get_redis_connection_for_global_tenant(&state)? .set_key_with_expiry(&key.into(), nonce.secret(), consts::user::REDIS_SSO_TTL) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to save csrf-nonce in redis")?; Ok(auth_url) } pub async fn get_user_email_from_oidc_provider( state: &SessionState, redirect_url: String, redirect_state: Secret<String>, base_url: Secret<String>, client_id: Secret<String>, authorization_code: Secret<String>, client_secret: Secret<String>, ) -> UserResult<UserEmail> { let nonce = get_nonce_from_redis(state, &redirect_state).await?; let discovery_document = get_discovery_document(base_url, state).await?; let client = get_oidc_core_client( discovery_document, client_id, Some(client_secret), redirect_url, )?; let nonce_clone = nonce.clone(); client .authorize_url( oidc_core::CoreAuthenticationFlow::AuthorizationCode, || oidc::CsrfToken::new(redirect_state.expose()), || nonce_clone, ) .add_scope(oidc::Scope::new("email".to_string())); // Send request to OpenId provider with authorization code let token_response = client .exchange_code(oidc::AuthorizationCode::new(authorization_code.expose())) .request_async(|req| get_oidc_reqwest_client(state, req)) .await .map_err(|e| match e { oidc::RequestTokenError::ServerResponse(resp) if resp.error() == &oidc_core::CoreErrorResponseType::InvalidGrant => { UserErrors::SSOFailed } _ => UserErrors::InternalServerError, }) .attach_printable("Failed to exchange code and fetch oidc token")?; // Fetch id token from response let id_token = token_response .id_token() .ok_or(UserErrors::InternalServerError) .attach_printable("Id Token not provided in token response")?; // Verify id token let id_token_claims = id_token .claims(&client.id_token_verifier(), &nonce) .change_context(UserErrors::InternalServerError) .attach_printable("Failed to verify id token")?; // Get email from token let email_from_token = id_token_claims .email() .map(|email| email.to_string()) .ok_or(UserErrors::InternalServerError) .attach_printable("OpenID Provider Didnt provide email")?; UserEmail::new(Secret::new(email_from_token)) .change_context(UserErrors::InternalServerError) .attach_printable("Failed to create email type") } // TODO: Cache Discovery Document async fn get_discovery_document( base_url: Secret<String>, state: &SessionState, ) -> UserResult<oidc_core::CoreProviderMetadata> { let issuer_url = oidc::IssuerUrl::new(base_url.expose()).change_context(UserErrors::InternalServerError)?; oidc_core::CoreProviderMetadata::discover_async(issuer_url, |req| { get_oidc_reqwest_client(state, req) }) .await .change_context(UserErrors::InternalServerError) } fn get_oidc_core_client( discovery_document: oidc_core::CoreProviderMetadata, client_id: Secret<String>, client_secret: Option<Secret<String>>, redirect_url: String, ) -> UserResult<oidc_core::CoreClient> { let client_id = oidc::ClientId::new(client_id.expose()); let client_secret = client_secret.map(|secret| oidc::ClientSecret::new(secret.expose())); let redirect_url = oidc::RedirectUrl::new(redirect_url) .change_context(UserErrors::InternalServerError) .attach_printable("Error creating redirect URL type")?; Ok( oidc_core::CoreClient::from_provider_metadata(discovery_document, client_id, client_secret) .set_redirect_uri(redirect_url), ) } async fn get_nonce_from_redis( state: &SessionState, redirect_state: &Secret<String>, ) -> UserResult<oidc::Nonce> { let redis_connection = get_redis_connection_for_global_tenant(state)?; let redirect_state = redirect_state.clone().expose(); let key = get_oidc_redis_key(&redirect_state); redis_connection .get_key::<Option<String>>(&key.into()) .await .change_context(UserErrors::InternalServerError) .attach_printable("Error Fetching CSRF from redis")? .map(oidc::Nonce::new) .ok_or(UserErrors::SSOFailed) .attach_printable("Cannot find csrf in redis. Csrf invalid or expired") } async fn get_oidc_reqwest_client( state: &SessionState, request: oidc::HttpRequest, ) -> Result<oidc::HttpResponse, ApiClientError> { let client = client::create_client(&state.conf.proxy, None, None, None) .map_err(|e| e.current_context().switch())?; let mut request_builder = client .request(request.method, request.url) .body(request.body); for (name, value) in &request.headers { request_builder = request_builder.header(name.as_str(), value.as_bytes()); } let request = request_builder .build() .map_err(|_| ApiClientError::ClientConstructionFailed)?; let response = client .execute(request) .await .map_err(|_| ApiClientError::RequestNotSent("OpenIDConnect".to_string()))?; Ok(oidc::HttpResponse { status_code: response.status(), headers: response.headers().to_owned(), body: response .bytes() .await .map_err(|_| ApiClientError::ResponseDecodingFailed)? .to_vec(), }) } fn get_oidc_redis_key(csrf: &str) -> String { format!("{}OIDC_{}", consts::user::REDIS_SSO_PREFIX, csrf) } fn get_redis_connection_for_global_tenant( state: &SessionState, ) -> UserResult<std::sync::Arc<RedisConnectionPool>> { state .global_store .get_redis_conn() .change_context(UserErrors::InternalServerError) .attach_printable("Failed to get redis connection") }
crates/router/src/services/openidconnect.rs
router::src::services::openidconnect
1,690
true
// File: crates/router/src/services/encryption.rs // Module: router::src::services::encryption use std::str; use error_stack::{report, ResultExt}; use josekit::{jwe, jws}; use serde::{Deserialize, Serialize}; use crate::{ core::errors::{self, CustomResult}, utils, }; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct JwsBody { pub header: String, pub payload: String, pub signature: String, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct JweBody { pub header: String, pub iv: String, pub encrypted_payload: String, pub tag: String, pub encrypted_key: String, } #[derive(Debug, Eq, PartialEq, Copy, Clone, strum::AsRefStr, strum::Display)] pub enum EncryptionAlgorithm { A128GCM, A256GCM, } pub async fn encrypt_jwe( payload: &[u8], public_key: impl AsRef<[u8]>, algorithm: EncryptionAlgorithm, key_id: Option<&str>, ) -> CustomResult<String, errors::EncryptionError> { let alg = jwe::RSA_OAEP_256; let mut src_header = jwe::JweHeader::new(); let enc_str = algorithm.as_ref(); src_header.set_content_encryption(enc_str); src_header.set_token_type("JWT"); if let Some(key_id) = key_id { src_header.set_key_id(key_id); } let encrypter = alg .encrypter_from_pem(public_key) .change_context(errors::EncryptionError) .attach_printable("Error getting JweEncryptor")?; jwe::serialize_compact(payload, &src_header, &encrypter) .change_context(errors::EncryptionError) .attach_printable("Error getting jwt string") } pub enum KeyIdCheck<'a> { RequestResponseKeyId((&'a str, &'a str)), SkipKeyIdCheck, } pub async fn decrypt_jwe( jwt: &str, key_ids: KeyIdCheck<'_>, private_key: impl AsRef<[u8]>, alg: jwe::alg::rsaes::RsaesJweAlgorithm, ) -> CustomResult<String, errors::EncryptionError> { if let KeyIdCheck::RequestResponseKeyId((req_key_id, resp_key_id)) = key_ids { utils::when(req_key_id.ne(resp_key_id), || { Err(report!(errors::EncryptionError) .attach_printable("key_id mismatch, Error authenticating response")) })?; } let decrypter = alg .decrypter_from_pem(private_key) .change_context(errors::EncryptionError) .attach_printable("Error getting JweDecryptor")?; let (dst_payload, _dst_header) = jwe::deserialize_compact(jwt, &decrypter) .change_context(errors::EncryptionError) .attach_printable("Error getting Decrypted jwe")?; String::from_utf8(dst_payload) .change_context(errors::EncryptionError) .attach_printable("Could not decode JWE payload from UTF-8") } pub async fn jws_sign_payload( payload: &[u8], kid: &str, private_key: impl AsRef<[u8]>, ) -> CustomResult<String, errors::EncryptionError> { let alg = jws::RS256; let mut src_header = jws::JwsHeader::new(); src_header.set_key_id(kid); let signer = alg .signer_from_pem(private_key) .change_context(errors::EncryptionError) .attach_printable("Error getting signer")?; let jwt = jws::serialize_compact(payload, &src_header, &signer) .change_context(errors::EncryptionError) .attach_printable("Error getting signed jwt string")?; Ok(jwt) } pub fn verify_sign( jws_body: String, key: impl AsRef<[u8]>, ) -> CustomResult<String, errors::EncryptionError> { let alg = jws::RS256; let input = jws_body.as_bytes(); let verifier = alg .verifier_from_pem(key) .change_context(errors::EncryptionError) .attach_printable("Error getting verifier")?; let (dst_payload, _dst_header) = jws::deserialize_compact(input, &verifier) .change_context(errors::EncryptionError) .attach_printable("Error getting Decrypted jws")?; let resp = String::from_utf8(dst_payload) .change_context(errors::EncryptionError) .attach_printable("Could not convert to UTF-8")?; Ok(resp) } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used, clippy::expect_used)] use super::*; // Keys used for tests // Can be generated using the following commands: // `openssl genrsa -out private_key.pem 2048` // `openssl rsa -in private_key.pem -pubout -out public_key.pem` const ENCRYPTION_KEY: &str = "\ -----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwa6siKaSYqD1o4J3AbHq Km8oVTvep7GoN/C45qY60C7DO72H1O7Ujt6ZsSiK83EyI0CaUg3ORPS3ayobFNmu zR366ckK8GIf3BG7sVI6u/9751z4OvBHZMM9JFWa7Bx/RCPQ8aeM+iJoqf9auuQm 3NCTlfaZJif45pShswR+xuZTR/bqnsOSP/MFROI9ch0NE7KRogy0tvrZe21lP24i Ro2LJJG+bYshxBddhxQf2ryJ85+/Trxdu16PunodGzCl6EMT3bvb4ZC41i15omqU aXXV1Z1wYUhlsO0jyd1bVvjyuE/KE1TbBS0gfR/RkacODmmE2zEdZ0EyyiXwqkmc oQIDAQAB -----END PUBLIC KEY----- "; const DECRYPTION_KEY: &str = "\ -----BEGIN RSA PRIVATE KEY----- MIIEowIBAAKCAQEAwa6siKaSYqD1o4J3AbHqKm8oVTvep7GoN/C45qY60C7DO72H 1O7Ujt6ZsSiK83EyI0CaUg3ORPS3ayobFNmuzR366ckK8GIf3BG7sVI6u/9751z4 OvBHZMM9JFWa7Bx/RCPQ8aeM+iJoqf9auuQm3NCTlfaZJif45pShswR+xuZTR/bq nsOSP/MFROI9ch0NE7KRogy0tvrZe21lP24iRo2LJJG+bYshxBddhxQf2ryJ85+/ Trxdu16PunodGzCl6EMT3bvb4ZC41i15omqUaXXV1Z1wYUhlsO0jyd1bVvjyuE/K E1TbBS0gfR/RkacODmmE2zEdZ0EyyiXwqkmcoQIDAQABAoIBAEavZwxgLmCMedl4 zdHyipF+C+w/c10kO05fLjwPQrujtWDiJOaTW0Pg/ZpoP33lO/UdqLR1kWgdH6ue rE+Jun/lhyM3WiSsyw/X8PYgGotuDFw90+I+uu+NSY0vKOEu7UuC/siS66KGWEhi h0xZ480G2jYKz43bXL1aVUEuTM5tsjtt0a/zm08DEluYwrmxaaTvHW2+8FOn3z8g UMClV2mN9X3rwlRhKAI1RVlymV95LmkTgzA4wW/M4j0kk108ouY8bo9vowoqidpo 0zKGfnqbQCIZP1QY6Xj8f3fqMY7IrFDdFHCEBXs29DnRz4oS8gYCAUXDx5iEVa1R KVxic5kCgYEA4vGWOANuv+RoxSnNQNnZjqHKjhd+9lXARnK6qVVXcJGTps72ILGJ CNrS/L6ndBePQGhtLtVyrvtS3ZvYhsAzJeMeeFUSZhQ2SOP5SCFWRnLJIBObJ5/x fFwrCbp38qsEBlqJXue4JQCOxqO4P6YYUmeE8fxLPmdVNWq5fNe2YtsCgYEA2nrl iMfttvNfQGX4pB3yEh/eWwqq4InFQdmWVDYPKJFG4TtUKJ48vzQXJqKfCBZ2q387 bH4KaKNWD7rYz4NBfE6z6lUc8We9w1tjVaqs5omBKUuovz8/8miUtxf2W5T2ta1/ zl9NyQ57duO423PeaCgPKKz3ftaxlz8G1CKYMTMCgYEAqkR7YhchNpOWD6cnOeq4 kYzNvgHe3c7EbZaSeY1wByMR1mscura4i44yEjKwzCcI8Vfn4uV+H86sA1xz/dWi CmD2cW3SWgf8GoAAfZ+VbVGdmJVdKUOVGKrGF4xxhf3NDT9MJYpQ3GIovNwE1qw1 P04vrqaNhYpdobAq7oGhc1UCgYAkimNzcgTHEYM/0Q453KxM7bmRvoH/1esA7XRg Fz6HyWxyZSrZNEXysLKiipZQkvk8C6aTqazx/Ud6kASNCGXedYdPzPZvRauOTe2a OVZ7pEnO71GE0v5N+8HLsZ1JieuNTTxP9s6aruplYwba5VEwWGrYob0vIJdJNYhd 2H9d0wKBgFzqGPvG8u1lVOLYDU9BjhA/3l00C97WHIG0Aal70PVyhFhm5ILNSHU1 Sau7H1Bhzy5G7rwt05LNpU6nFcAGVaZtzl4/+FYfYIulubYjuSEh72yuBHHyvi1/ 4Zql8DXhF5kkKx75cMcIxZ/ceiRiQyjzYv3LoTTADHHjzsiBEiQY -----END RSA PRIVATE KEY----- "; const SIGNATURE_VERIFICATION_KEY: &str = "\ -----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5Z/K0JWds8iHhWCa+rj0 rhOQX1nVs/ArQ1D0vh3UlSPR2vZUTrkdP7i3amv4d2XDC+3+5/YWExTkpxqnfl1T 9J37leN2guAARed6oYoTDEP/OoKtnUrKK2xk/+V5DNOWcRiSpcCrJOOIEoACOlPI rXQSg16KDZQb0QTMntnsiPIJDbsOGcdKytRAcNaokiKLnia1v13N3bk6dSplrj1Y zawslZfgqD0eov4FjzBMoA19yNtlVLLf6kOkLcFQjTKXJLP1tLflLUBPTg8fm9wg APK2BjMQ2AMkUxx0ubbtw/9CeJ+bFWrqGnEhlvfDMlyAV77sAiIdQ4mXs3TLcLb/ AQIDAQAB -----END PUBLIC KEY----- "; const SIGNING_KEY: &str = "\ -----BEGIN RSA PRIVATE KEY----- MIIEowIBAAKCAQEA5Z/K0JWds8iHhWCa+rj0rhOQX1nVs/ArQ1D0vh3UlSPR2vZU TrkdP7i3amv4d2XDC+3+5/YWExTkpxqnfl1T9J37leN2guAARed6oYoTDEP/OoKt nUrKK2xk/+V5DNOWcRiSpcCrJOOIEoACOlPIrXQSg16KDZQb0QTMntnsiPIJDbsO GcdKytRAcNaokiKLnia1v13N3bk6dSplrj1YzawslZfgqD0eov4FjzBMoA19yNtl VLLf6kOkLcFQjTKXJLP1tLflLUBPTg8fm9wgAPK2BjMQ2AMkUxx0ubbtw/9CeJ+b FWrqGnEhlvfDMlyAV77sAiIdQ4mXs3TLcLb/AQIDAQABAoIBAGNekD1N0e5AZG1S zh6cNb6zVrH8xV9WGtLJ0PAJJrrXwnQYT4m10DOIM0+Jo/+/ePXLq5kkRI9DZmPu Q/eKWc+tInfN9LZUS6n0r3wCrZWMQ4JFlO5RtEWwZdDbtFPZqOwObz/treKL2JHw 9YXaRijR50UUf3e61YLRqd9AfX0RNuuG8H+WgU3Gwuh5TwRnljM3JGaDPHsf7HLS tNkqJuByp26FEbOLTokZDbHN0sy7/6hufxnIS9AK4vp8y9mZAjghG26Rbg/H71mp Z+Q6P1y7xdgAKbhq7usG3/o4Y1e9wnghHvFS7DPwGekHQH2+LsYNEYOir1iRjXxH GUXOhfUCgYEA+cR9jONQFco8Zp6z0wdGlBeYoUHVMjThQWEblWL2j4RG/qQd/y0j uhVeU0/PmkYK2mgcjrh/pgDTtPymc+QuxBi+lexs89ppuJIAgMvLUiJT67SBHguP l4+oL9U78KGh7PfJpMKH+Pk5yc1xucAevk0wWmr5Tz2vKRDavFTPV+MCgYEA61qg Y7yN0cDtxtqlZdMC8BJPFCQ1+s3uB0wetAY3BEKjfYc2O/4sMbixXzt5PkZqZy96 QBUBxhcM/rIolpM3nrgN7h1nmJdk9ljCTjWoTJ6fDk8BUh8+0GrVhTbe7xZ+bFUN UioIqvfapr/q/k7Ah2mCBE04wTZFry9fndrH2ssCgYEAh1T2Cj6oiAX6UEgxe2h3 z4oxgz6efAO3AavSPFFQ81Zi+VqHflpA/3TQlSerfxXwj4LV5mcFkzbjfy9eKXE7 /bjCm41tQ3vWyNEjQKYr1qcO/aniRBtThHWsVa6eObX6fOGN+p4E+txfeX693j3A 6q/8QSGxUERGAmRFgMIbTq0CgYAmuTeQkXKII4U75be3BDwEgg6u0rJq/L0ASF74 4djlg41g1wFuZ4if+bJ9Z8ywGWfiaGZl6s7q59oEgg25kKljHQd1uTLVYXuEKOB3 e86gJK0o7ojaGTf9lMZi779IeVv9uRTDAxWAA93e987TXuPAo/R3frkq2SIoC9Rg paGidwKBgBqYd/iOJWsUZ8cWEhSE1Huu5rDEpjra8JPXHqQdILirxt1iCA5aEQou BdDGaDr8sepJbGtjwTyiG8gEaX1DD+KsF2+dQRQdQfcYC40n8fKkvpFwrKjDj1ac VuY3OeNxi+dC2r7HppP3O/MJ4gX/RJJfSrcaGP8/Ke1W5+jE97Qy -----END RSA PRIVATE KEY----- "; #[actix_rt::test] async fn test_jwe() { let jwt = encrypt_jwe( "request_payload".as_bytes(), ENCRYPTION_KEY, EncryptionAlgorithm::A256GCM, None, ) .await .unwrap(); let alg = jwe::RSA_OAEP_256; let payload = decrypt_jwe(&jwt, KeyIdCheck::SkipKeyIdCheck, DECRYPTION_KEY, alg) .await .unwrap(); assert_eq!("request_payload".to_string(), payload) } #[actix_rt::test] async fn test_jws() { let jwt = jws_sign_payload("jws payload".as_bytes(), "1", SIGNING_KEY) .await .unwrap(); let payload = verify_sign(jwt, SIGNATURE_VERIFICATION_KEY).unwrap(); assert_eq!("jws payload".to_string(), payload) } }
crates/router/src/services/encryption.rs
router::src::services::encryption
4,403
true
// File: crates/router/src/services/connector_integration_interface.rs // Module: router::src::services::connector_integration_interface pub use hyperswitch_interfaces::{ authentication::ExternalAuthenticationPayload, connector_integration_interface::*, connector_integration_v2::ConnectorIntegrationV2, webhooks::IncomingWebhookFlowError, };
crates/router/src/services/connector_integration_interface.rs
router::src::services::connector_integration_interface
65
true
// File: crates/router/src/services/jwt.rs // Module: router::src::services::jwt use common_utils::errors::CustomResult; use error_stack::ResultExt; use jsonwebtoken::{encode, EncodingKey, Header}; use masking::PeekInterface; use crate::{configs::Settings, core::errors::UserErrors}; pub fn generate_exp( exp_duration: std::time::Duration, ) -> CustomResult<std::time::Duration, UserErrors> { std::time::SystemTime::now() .checked_add(exp_duration) .ok_or(UserErrors::InternalServerError)? .duration_since(std::time::UNIX_EPOCH) .change_context(UserErrors::InternalServerError) } pub async fn generate_jwt<T>( claims_data: &T, settings: &Settings, ) -> CustomResult<String, UserErrors> where T: serde::ser::Serialize, { let jwt_secret = &settings.secrets.get_inner().jwt_secret; encode( &Header::default(), claims_data, &EncodingKey::from_secret(jwt_secret.peek().as_bytes()), ) .change_context(UserErrors::InternalServerError) }
crates/router/src/services/jwt.rs
router::src::services::jwt
243
true
// File: crates/router/src/services/card_testing_guard.rs // Module: router::src::services::card_testing_guard use std::sync::Arc; use error_stack::ResultExt; use redis_interface::RedisConnectionPool; use crate::{ core::errors::{ApiErrorResponse, RouterResult}, routes::app::SessionStateInfo, }; fn get_redis_connection<A: SessionStateInfo>(state: &A) -> RouterResult<Arc<RedisConnectionPool>> { state .store() .get_redis_conn() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection") } pub async fn set_blocked_count_in_cache<A>( state: &A, cache_key: &str, value: i32, expiry: i64, ) -> RouterResult<()> where A: SessionStateInfo + Sync, { let redis_conn = get_redis_connection(state)?; redis_conn .set_key_with_expiry(&cache_key.into(), value, expiry) .await .change_context(ApiErrorResponse::InternalServerError) } pub async fn get_blocked_count_from_cache<A>( state: &A, cache_key: &str, ) -> RouterResult<Option<i32>> where A: SessionStateInfo + Sync, { let redis_conn = get_redis_connection(state)?; let value: Option<i32> = redis_conn .get_key(&cache_key.into()) .await .change_context(ApiErrorResponse::InternalServerError)?; Ok(value) } pub async fn increment_blocked_count_in_cache<A>( state: &A, cache_key: &str, expiry: i64, ) -> RouterResult<()> where A: SessionStateInfo + Sync, { let redis_conn = get_redis_connection(state)?; let value: Option<i32> = redis_conn .get_key(&cache_key.into()) .await .change_context(ApiErrorResponse::InternalServerError)?; let mut incremented_blocked_count: i32 = 1; if let Some(actual_value) = value { incremented_blocked_count = actual_value + 1; } redis_conn .set_key_with_expiry(&cache_key.into(), incremented_blocked_count, expiry) .await .change_context(ApiErrorResponse::InternalServerError) }
crates/router/src/services/card_testing_guard.rs
router::src::services::card_testing_guard
489
true
// File: crates/router/src/services/kafka.rs // Module: router::src::services::kafka use std::{collections::HashMap, sync::Arc}; use common_utils::{errors::CustomResult, types::TenantConfig}; use error_stack::{report, ResultExt}; use events::{EventsError, Message, MessagingInterface}; use num_traits::ToPrimitive; use rdkafka::{ config::FromClientConfig, message::{Header, OwnedHeaders}, producer::{BaseRecord, DefaultProducerContext, Producer, ThreadedProducer}, }; use serde_json::Value; #[cfg(feature = "payouts")] pub mod payout; use diesel_models::fraud_check::FraudCheck; use crate::{events::EventType, services::kafka::fraud_check_event::KafkaFraudCheckEvent}; mod authentication; mod authentication_event; mod dispute; mod dispute_event; mod fraud_check; mod fraud_check_event; mod payment_attempt; mod payment_attempt_event; mod payment_intent; mod payment_intent_event; mod refund; mod refund_event; pub mod revenue_recovery; use diesel_models::{authentication::Authentication, refund::Refund}; use hyperswitch_domain_models::payments::{payment_attempt::PaymentAttempt, PaymentIntent}; use serde::Serialize; use time::{OffsetDateTime, PrimitiveDateTime}; #[cfg(feature = "payouts")] use self::payout::KafkaPayout; use self::{ authentication::KafkaAuthentication, authentication_event::KafkaAuthenticationEvent, dispute::KafkaDispute, dispute_event::KafkaDisputeEvent, payment_attempt::KafkaPaymentAttempt, payment_attempt_event::KafkaPaymentAttemptEvent, payment_intent::KafkaPaymentIntent, payment_intent_event::KafkaPaymentIntentEvent, refund::KafkaRefund, refund_event::KafkaRefundEvent, }; use crate::{services::kafka::fraud_check::KafkaFraudCheck, types::storage::Dispute}; // Using message queue result here to avoid confusion with Kafka result provided by library pub type MQResult<T> = CustomResult<T, KafkaError>; use crate::db::kafka_store::TenantID; pub trait KafkaMessage where Self: Serialize + std::fmt::Debug, { fn value(&self) -> MQResult<Vec<u8>> { // Add better error logging here serde_json::to_vec(&self).change_context(KafkaError::GenericError) } fn key(&self) -> String; fn event_type(&self) -> EventType; fn creation_timestamp(&self) -> Option<i64> { None } } #[derive(serde::Serialize, Debug)] struct KafkaEvent<'a, T: KafkaMessage> { #[serde(flatten)] event: &'a T, sign_flag: i32, tenant_id: TenantID, clickhouse_database: Option<String>, } impl<'a, T: KafkaMessage> KafkaEvent<'a, T> { fn new(event: &'a T, tenant_id: TenantID, clickhouse_database: Option<String>) -> Self { Self { event, sign_flag: 1, tenant_id, clickhouse_database, } } fn old(event: &'a T, tenant_id: TenantID, clickhouse_database: Option<String>) -> Self { Self { event, sign_flag: -1, tenant_id, clickhouse_database, } } } impl<T: KafkaMessage> KafkaMessage for KafkaEvent<'_, T> { fn key(&self) -> String { self.event.key() } fn event_type(&self) -> EventType { self.event.event_type() } fn creation_timestamp(&self) -> Option<i64> { self.event.creation_timestamp() } } #[derive(serde::Serialize, Debug)] struct KafkaConsolidatedLog<'a, T: KafkaMessage> { #[serde(flatten)] event: &'a T, tenant_id: TenantID, } #[derive(serde::Serialize, Debug)] struct KafkaConsolidatedEvent<'a, T: KafkaMessage> { log: KafkaConsolidatedLog<'a, T>, log_type: EventType, } impl<'a, T: KafkaMessage> KafkaConsolidatedEvent<'a, T> { fn new(event: &'a T, tenant_id: TenantID) -> Self { Self { log: KafkaConsolidatedLog { event, tenant_id }, log_type: event.event_type(), } } } impl<T: KafkaMessage> KafkaMessage for KafkaConsolidatedEvent<'_, T> { fn key(&self) -> String { self.log.event.key() } fn event_type(&self) -> EventType { EventType::Consolidated } fn creation_timestamp(&self) -> Option<i64> { self.log.event.creation_timestamp() } } #[derive(Debug, serde::Deserialize, Clone, Default)] #[serde(default)] pub struct KafkaSettings { brokers: Vec<String>, fraud_check_analytics_topic: String, intent_analytics_topic: String, attempt_analytics_topic: String, refund_analytics_topic: String, api_logs_topic: String, connector_logs_topic: String, outgoing_webhook_logs_topic: String, dispute_analytics_topic: String, audit_events_topic: String, #[cfg(feature = "payouts")] payout_analytics_topic: String, consolidated_events_topic: String, authentication_analytics_topic: String, routing_logs_topic: String, revenue_recovery_topic: String, } impl KafkaSettings { pub fn validate(&self) -> Result<(), crate::core::errors::ApplicationError> { use common_utils::ext_traits::ConfigExt; use crate::core::errors::ApplicationError; common_utils::fp_utils::when(self.brokers.is_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Kafka brokers must not be empty".into(), )) })?; common_utils::fp_utils::when(self.intent_analytics_topic.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Kafka Intent Analytics topic must not be empty".into(), )) })?; common_utils::fp_utils::when(self.attempt_analytics_topic.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Kafka Attempt Analytics topic must not be empty".into(), )) })?; common_utils::fp_utils::when(self.refund_analytics_topic.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Kafka Refund Analytics topic must not be empty".into(), )) })?; common_utils::fp_utils::when(self.api_logs_topic.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Kafka API event Analytics topic must not be empty".into(), )) })?; common_utils::fp_utils::when(self.connector_logs_topic.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Kafka Connector Logs topic must not be empty".into(), )) })?; common_utils::fp_utils::when( self.outgoing_webhook_logs_topic.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Kafka Outgoing Webhook Logs topic must not be empty".into(), )) }, )?; common_utils::fp_utils::when(self.dispute_analytics_topic.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Kafka Dispute Logs topic must not be empty".into(), )) })?; common_utils::fp_utils::when(self.audit_events_topic.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Kafka Audit Events topic must not be empty".into(), )) })?; #[cfg(feature = "payouts")] common_utils::fp_utils::when(self.payout_analytics_topic.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Kafka Payout Analytics topic must not be empty".into(), )) })?; common_utils::fp_utils::when(self.consolidated_events_topic.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Consolidated Events topic must not be empty".into(), )) })?; common_utils::fp_utils::when( self.authentication_analytics_topic.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Kafka Authentication Analytics topic must not be empty".into(), )) }, )?; common_utils::fp_utils::when(self.routing_logs_topic.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Kafka Routing Logs topic must not be empty".into(), )) })?; Ok(()) } } #[derive(Clone, Debug)] pub struct KafkaProducer { producer: Arc<RdKafkaProducer>, intent_analytics_topic: String, fraud_check_analytics_topic: String, attempt_analytics_topic: String, refund_analytics_topic: String, api_logs_topic: String, connector_logs_topic: String, outgoing_webhook_logs_topic: String, dispute_analytics_topic: String, audit_events_topic: String, #[cfg(feature = "payouts")] payout_analytics_topic: String, consolidated_events_topic: String, authentication_analytics_topic: String, ckh_database_name: Option<String>, routing_logs_topic: String, revenue_recovery_topic: String, } struct RdKafkaProducer(ThreadedProducer<DefaultProducerContext>); impl std::fmt::Debug for RdKafkaProducer { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("RdKafkaProducer") } } #[derive(Debug, Clone, thiserror::Error)] pub enum KafkaError { #[error("Generic Kafka Error")] GenericError, #[error("Kafka not implemented")] NotImplemented, #[error("Kafka Initialization Error")] InitializationError, } #[allow(unused)] impl KafkaProducer { pub fn set_tenancy(&mut self, tenant_config: &dyn TenantConfig) { self.ckh_database_name = Some(tenant_config.get_clickhouse_database().to_string()); } pub async fn create(conf: &KafkaSettings) -> MQResult<Self> { Ok(Self { producer: Arc::new(RdKafkaProducer( ThreadedProducer::from_config( rdkafka::ClientConfig::new().set("bootstrap.servers", conf.brokers.join(",")), ) .change_context(KafkaError::InitializationError)?, )), fraud_check_analytics_topic: conf.fraud_check_analytics_topic.clone(), intent_analytics_topic: conf.intent_analytics_topic.clone(), attempt_analytics_topic: conf.attempt_analytics_topic.clone(), refund_analytics_topic: conf.refund_analytics_topic.clone(), api_logs_topic: conf.api_logs_topic.clone(), connector_logs_topic: conf.connector_logs_topic.clone(), outgoing_webhook_logs_topic: conf.outgoing_webhook_logs_topic.clone(), dispute_analytics_topic: conf.dispute_analytics_topic.clone(), audit_events_topic: conf.audit_events_topic.clone(), #[cfg(feature = "payouts")] payout_analytics_topic: conf.payout_analytics_topic.clone(), consolidated_events_topic: conf.consolidated_events_topic.clone(), authentication_analytics_topic: conf.authentication_analytics_topic.clone(), ckh_database_name: None, routing_logs_topic: conf.routing_logs_topic.clone(), revenue_recovery_topic: conf.revenue_recovery_topic.clone(), }) } pub fn log_event<T: KafkaMessage>(&self, event: &T) -> MQResult<()> { router_env::logger::debug!("Logging Kafka Event {event:?}"); let topic = self.get_topic(event.event_type()); self.producer .0 .send( BaseRecord::to(topic) .key(&event.key()) .payload(&event.value()?) .timestamp(event.creation_timestamp().unwrap_or_else(|| { (OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000) .try_into() .unwrap_or_else(|_| { // kafka producer accepts milliseconds // try converting nanos to millis if that fails convert seconds to millis OffsetDateTime::now_utc().unix_timestamp() * 1_000 }) })), ) .map_err(|(error, record)| report!(error).attach_printable(format!("{record:?}"))) .change_context(KafkaError::GenericError) } pub async fn log_fraud_check( &self, attempt: &FraudCheck, old_attempt: Option<FraudCheck>, tenant_id: TenantID, ) -> MQResult<()> { if let Some(negative_event) = old_attempt { self.log_event(&KafkaEvent::old( &KafkaFraudCheck::from_storage(&negative_event), tenant_id.clone(), self.ckh_database_name.clone(), )) .attach_printable_lazy(|| { format!("Failed to add negative fraud check event {negative_event:?}") })?; }; self.log_event(&KafkaEvent::new( &KafkaFraudCheck::from_storage(attempt), tenant_id.clone(), self.ckh_database_name.clone(), )) .attach_printable_lazy(|| { format!("Failed to add positive fraud check event {attempt:?}") })?; self.log_event(&KafkaConsolidatedEvent::new( &KafkaFraudCheckEvent::from_storage(attempt), tenant_id.clone(), )) .attach_printable_lazy(|| { format!("Failed to add consolidated fraud check event {attempt:?}") }) } pub async fn log_payment_attempt( &self, attempt: &PaymentAttempt, old_attempt: Option<PaymentAttempt>, tenant_id: TenantID, ) -> MQResult<()> { if let Some(negative_event) = old_attempt { self.log_event(&KafkaEvent::old( &KafkaPaymentAttempt::from_storage(&negative_event), tenant_id.clone(), self.ckh_database_name.clone(), )) .attach_printable_lazy(|| { format!("Failed to add negative attempt event {negative_event:?}") })?; }; self.log_event(&KafkaEvent::new( &KafkaPaymentAttempt::from_storage(attempt), tenant_id.clone(), self.ckh_database_name.clone(), )) .attach_printable_lazy(|| format!("Failed to add positive attempt event {attempt:?}"))?; self.log_event(&KafkaConsolidatedEvent::new( &KafkaPaymentAttemptEvent::from_storage(attempt), tenant_id.clone(), )) .attach_printable_lazy(|| format!("Failed to add consolidated attempt event {attempt:?}")) } pub async fn log_payment_attempt_delete( &self, delete_old_attempt: &PaymentAttempt, tenant_id: TenantID, ) -> MQResult<()> { self.log_event(&KafkaEvent::old( &KafkaPaymentAttempt::from_storage(delete_old_attempt), tenant_id.clone(), self.ckh_database_name.clone(), )) .attach_printable_lazy(|| { format!("Failed to add negative attempt event {delete_old_attempt:?}") }) } pub async fn log_authentication( &self, authentication: &Authentication, old_authentication: Option<Authentication>, tenant_id: TenantID, ) -> MQResult<()> { if let Some(negative_event) = old_authentication { self.log_event(&KafkaEvent::old( &KafkaAuthentication::from_storage(&negative_event), tenant_id.clone(), self.ckh_database_name.clone(), )) .attach_printable_lazy(|| { format!("Failed to add negative authentication event {negative_event:?}") })?; }; self.log_event(&KafkaEvent::new( &KafkaAuthentication::from_storage(authentication), tenant_id.clone(), self.ckh_database_name.clone(), )) .attach_printable_lazy(|| { format!("Failed to add positive authentication event {authentication:?}") })?; self.log_event(&KafkaConsolidatedEvent::new( &KafkaAuthenticationEvent::from_storage(authentication), tenant_id.clone(), )) .attach_printable_lazy(|| { format!("Failed to add consolidated authentication event {authentication:?}") }) } pub async fn log_payment_intent( &self, intent: &PaymentIntent, old_intent: Option<PaymentIntent>, tenant_id: TenantID, infra_values: Option<Value>, ) -> MQResult<()> { if let Some(negative_event) = old_intent { self.log_event(&KafkaEvent::old( &KafkaPaymentIntent::from_storage(&negative_event, infra_values.clone()), tenant_id.clone(), self.ckh_database_name.clone(), )) .attach_printable_lazy(|| { format!("Failed to add negative intent event {negative_event:?}") })?; }; self.log_event(&KafkaEvent::new( &KafkaPaymentIntent::from_storage(intent, infra_values.clone()), tenant_id.clone(), self.ckh_database_name.clone(), )) .attach_printable_lazy(|| format!("Failed to add positive intent event {intent:?}"))?; self.log_event(&KafkaConsolidatedEvent::new( &KafkaPaymentIntentEvent::from_storage(intent, infra_values.clone()), tenant_id.clone(), )) .attach_printable_lazy(|| format!("Failed to add consolidated intent event {intent:?}")) } pub async fn log_payment_intent_delete( &self, delete_old_intent: &PaymentIntent, tenant_id: TenantID, infra_values: Option<Value>, ) -> MQResult<()> { self.log_event(&KafkaEvent::old( &KafkaPaymentIntent::from_storage(delete_old_intent, infra_values), tenant_id.clone(), self.ckh_database_name.clone(), )) .attach_printable_lazy(|| { format!("Failed to add negative intent event {delete_old_intent:?}") }) } pub async fn log_refund( &self, refund: &Refund, old_refund: Option<Refund>, tenant_id: TenantID, ) -> MQResult<()> { if let Some(negative_event) = old_refund { self.log_event(&KafkaEvent::old( &KafkaRefund::from_storage(&negative_event), tenant_id.clone(), self.ckh_database_name.clone(), )) .attach_printable_lazy(|| { format!("Failed to add negative refund event {negative_event:?}") })?; }; self.log_event(&KafkaEvent::new( &KafkaRefund::from_storage(refund), tenant_id.clone(), self.ckh_database_name.clone(), )) .attach_printable_lazy(|| format!("Failed to add positive refund event {refund:?}"))?; self.log_event(&KafkaConsolidatedEvent::new( &KafkaRefundEvent::from_storage(refund), tenant_id.clone(), )) .attach_printable_lazy(|| format!("Failed to add consolidated refund event {refund:?}")) } pub async fn log_refund_delete( &self, delete_old_refund: &Refund, tenant_id: TenantID, ) -> MQResult<()> { self.log_event(&KafkaEvent::old( &KafkaRefund::from_storage(delete_old_refund), tenant_id.clone(), self.ckh_database_name.clone(), )) .attach_printable_lazy(|| { format!("Failed to add negative refund event {delete_old_refund:?}") }) } pub async fn log_dispute( &self, dispute: &Dispute, old_dispute: Option<Dispute>, tenant_id: TenantID, ) -> MQResult<()> { if let Some(negative_event) = old_dispute { self.log_event(&KafkaEvent::old( &KafkaDispute::from_storage(&negative_event), tenant_id.clone(), self.ckh_database_name.clone(), )) .attach_printable_lazy(|| { format!("Failed to add negative dispute event {negative_event:?}") })?; }; self.log_event(&KafkaEvent::new( &KafkaDispute::from_storage(dispute), tenant_id.clone(), self.ckh_database_name.clone(), )) .attach_printable_lazy(|| format!("Failed to add positive dispute event {dispute:?}"))?; self.log_event(&KafkaConsolidatedEvent::new( &KafkaDisputeEvent::from_storage(dispute), tenant_id.clone(), )) .attach_printable_lazy(|| format!("Failed to add consolidated dispute event {dispute:?}")) } pub async fn log_dispute_delete( &self, delete_old_dispute: &Dispute, tenant_id: TenantID, ) -> MQResult<()> { self.log_event(&KafkaEvent::old( &KafkaDispute::from_storage(delete_old_dispute), tenant_id.clone(), self.ckh_database_name.clone(), )) .attach_printable_lazy(|| { format!("Failed to add negative dispute event {delete_old_dispute:?}") }) } #[cfg(feature = "payouts")] pub async fn log_payout( &self, payout: &KafkaPayout<'_>, old_payout: Option<KafkaPayout<'_>>, tenant_id: TenantID, ) -> MQResult<()> { if let Some(negative_event) = old_payout { self.log_event(&KafkaEvent::old( &negative_event, tenant_id.clone(), self.ckh_database_name.clone(), )) .attach_printable_lazy(|| { format!("Failed to add negative payout event {negative_event:?}") })?; }; self.log_event(&KafkaEvent::new( payout, tenant_id.clone(), self.ckh_database_name.clone(), )) .attach_printable_lazy(|| format!("Failed to add positive payout event {payout:?}")) } #[cfg(feature = "payouts")] pub async fn log_payout_delete( &self, delete_old_payout: &KafkaPayout<'_>, tenant_id: TenantID, ) -> MQResult<()> { self.log_event(&KafkaEvent::old( delete_old_payout, tenant_id.clone(), self.ckh_database_name.clone(), )) .attach_printable_lazy(|| { format!("Failed to add negative payout event {delete_old_payout:?}") }) } pub fn get_topic(&self, event: EventType) -> &str { match event { EventType::FraudCheck => &self.fraud_check_analytics_topic, EventType::ApiLogs => &self.api_logs_topic, EventType::PaymentAttempt => &self.attempt_analytics_topic, EventType::PaymentIntent => &self.intent_analytics_topic, EventType::Refund => &self.refund_analytics_topic, EventType::ConnectorApiLogs => &self.connector_logs_topic, EventType::OutgoingWebhookLogs => &self.outgoing_webhook_logs_topic, EventType::Dispute => &self.dispute_analytics_topic, EventType::AuditEvent => &self.audit_events_topic, #[cfg(feature = "payouts")] EventType::Payout => &self.payout_analytics_topic, EventType::Consolidated => &self.consolidated_events_topic, EventType::Authentication => &self.authentication_analytics_topic, EventType::RoutingApiLogs => &self.routing_logs_topic, EventType::RevenueRecovery => &self.revenue_recovery_topic, } } } impl Drop for RdKafkaProducer { fn drop(&mut self) { // Flush the producer to send any pending messages match self.0.flush(rdkafka::util::Timeout::After( std::time::Duration::from_secs(5), )) { Ok(_) => router_env::logger::info!("Kafka events flush Successful"), Err(error) => router_env::logger::error!("Failed to flush Kafka Events {error:?}"), } } } impl MessagingInterface for KafkaProducer { type MessageClass = EventType; fn send_message<T>( &self, data: T, metadata: HashMap<String, String>, timestamp: PrimitiveDateTime, ) -> error_stack::Result<(), EventsError> where T: Message<Class = Self::MessageClass> + masking::ErasedMaskSerialize, { let topic = self.get_topic(data.get_message_class()); let json_data = data .masked_serialize() .and_then(|mut value| { if let Value::Object(ref mut map) = value { if let Some(db_name) = self.ckh_database_name.clone() { map.insert("clickhouse_database".to_string(), Value::String(db_name)); } } serde_json::to_vec(&value) }) .change_context(EventsError::SerializationError)?; let mut headers = OwnedHeaders::new(); for (k, v) in metadata.iter() { headers = headers.insert(Header { key: k.as_str(), value: Some(v), }); } headers = headers.insert(Header { key: "clickhouse_database", value: self.ckh_database_name.as_ref(), }); self.producer .0 .send( BaseRecord::to(topic) .key(&data.identifier()) .payload(&json_data) .headers(headers) .timestamp( (timestamp.assume_utc().unix_timestamp_nanos() / 1_000_000) .to_i64() .unwrap_or_else(|| { // kafka producer accepts milliseconds // try converting nanos to millis if that fails convert seconds to millis timestamp.assume_utc().unix_timestamp() * 1_000 }), ), ) .map_err(|(error, record)| report!(error).attach_printable(format!("{record:?}"))) .change_context(KafkaError::GenericError) .change_context(EventsError::PublishError) } }
crates/router/src/services/kafka.rs
router::src::services::kafka
5,664
true
// File: crates/router/src/services/authentication.rs // Module: router::src::services::authentication use std::str::FromStr; use actix_web::http::header::HeaderMap; #[cfg(feature = "v2")] use api_models::payment_methods::PaymentMethodIntentConfirm; #[cfg(feature = "v1")] use api_models::payment_methods::{PaymentMethodCreate, PaymentMethodListRequest}; use api_models::payments; #[cfg(feature = "payouts")] use api_models::payouts; use async_trait::async_trait; use common_enums::TokenPurpose; use common_utils::{date_time, fp_utils, id_type}; #[cfg(feature = "v2")] use diesel_models::ephemeral_key; use error_stack::{report, ResultExt}; use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation}; #[cfg(feature = "v2")] use masking::ExposeInterface; use masking::PeekInterface; use router_env::logger; use serde::Serialize; use self::blacklist::BlackList; #[cfg(all(feature = "partial-auth", feature = "v1"))] use self::detached::ExtractedPayload; #[cfg(feature = "partial-auth")] use self::detached::GetAuthType; use super::authorization::{self, permissions::Permission}; #[cfg(feature = "olap")] use super::jwt; #[cfg(feature = "olap")] use crate::configs::Settings; #[cfg(feature = "olap")] use crate::consts; #[cfg(feature = "olap")] use crate::core::errors::UserResult; #[cfg(all(feature = "partial-auth", feature = "v1"))] use crate::core::metrics; use crate::{ configs::settings, core::{ api_keys, errors::{self, utils::StorageErrorExt, RouterResult}, }, headers, routes::app::SessionStateInfo, services::api, types::{domain, storage}, utils::OptionExt, }; pub mod blacklist; pub mod cookies; pub mod decision; #[cfg(feature = "partial-auth")] mod detached; #[cfg(feature = "v1")] #[derive(Clone, Debug)] pub struct AuthenticationData { pub merchant_account: domain::MerchantAccount, pub platform_merchant_account: Option<domain::MerchantAccount>, pub key_store: domain::MerchantKeyStore, pub profile_id: Option<id_type::ProfileId>, } #[cfg(feature = "v2")] #[derive(Clone, Debug)] pub struct AuthenticationData { pub merchant_account: domain::MerchantAccount, pub key_store: domain::MerchantKeyStore, pub profile: domain::Profile, pub platform_merchant_account: Option<domain::MerchantAccount>, } #[derive(Clone, Debug)] pub struct AuthenticationDataWithoutProfile { pub merchant_account: domain::MerchantAccount, pub key_store: domain::MerchantKeyStore, } #[derive(Clone, Debug)] pub struct AuthenticationDataWithMultipleProfiles { pub merchant_account: domain::MerchantAccount, pub key_store: domain::MerchantKeyStore, pub profile_id_list: Option<Vec<id_type::ProfileId>>, } #[derive(Clone, Debug)] pub struct AuthenticationDataWithUser { pub merchant_account: domain::MerchantAccount, pub key_store: domain::MerchantKeyStore, pub user: storage::User, pub profile_id: id_type::ProfileId, } #[derive(Clone, Debug)] pub struct AuthenticationDataWithOrg { pub organization_id: id_type::OrganizationId, } #[derive(Clone)] pub struct UserFromTokenWithRoleInfo { pub user: UserFromToken, pub role_info: authorization::roles::RoleInfo, } #[derive(Clone, Debug, Eq, PartialEq, Serialize)] #[serde( tag = "api_auth_type", content = "authentication_data", rename_all = "snake_case" )] pub enum AuthenticationType { ApiKey { merchant_id: id_type::MerchantId, key_id: id_type::ApiKeyId, }, AdminApiKey, AdminApiAuthWithMerchantId { merchant_id: id_type::MerchantId, }, OrganizationJwt { org_id: id_type::OrganizationId, user_id: String, }, MerchantJwt { merchant_id: id_type::MerchantId, user_id: Option<String>, }, MerchantJwtWithProfileId { merchant_id: id_type::MerchantId, profile_id: Option<id_type::ProfileId>, user_id: String, }, UserJwt { user_id: String, }, SinglePurposeJwt { user_id: String, purpose: TokenPurpose, }, SinglePurposeOrLoginJwt { user_id: String, purpose: Option<TokenPurpose>, role_id: Option<String>, }, MerchantId { merchant_id: id_type::MerchantId, }, PublishableKey { merchant_id: id_type::MerchantId, }, WebhookAuth { merchant_id: id_type::MerchantId, }, InternalMerchantIdProfileId { merchant_id: id_type::MerchantId, profile_id: Option<id_type::ProfileId>, }, NoAuth, } impl events::EventInfo for AuthenticationType { type Data = Self; fn data(&self) -> error_stack::Result<Self::Data, events::EventsError> { Ok(self.clone()) } fn key(&self) -> String { "auth_info".to_string() } } impl AuthenticationType { pub fn get_merchant_id(&self) -> Option<&id_type::MerchantId> { match self { Self::ApiKey { merchant_id, key_id: _, } | Self::AdminApiAuthWithMerchantId { merchant_id } | Self::MerchantId { merchant_id } | Self::PublishableKey { merchant_id } | Self::MerchantJwt { merchant_id, user_id: _, } | Self::MerchantJwtWithProfileId { merchant_id, .. } | Self::WebhookAuth { merchant_id } | Self::InternalMerchantIdProfileId { merchant_id, .. } => Some(merchant_id), Self::AdminApiKey | Self::OrganizationJwt { .. } | Self::UserJwt { .. } | Self::SinglePurposeJwt { .. } | Self::SinglePurposeOrLoginJwt { .. } | Self::NoAuth => None, } } } #[derive(Clone, Debug, Eq, PartialEq, Serialize, serde::Deserialize, strum::Display)] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ExternalServiceType { Hypersense, } #[cfg(feature = "olap")] #[derive(Clone, Debug)] pub struct UserFromSinglePurposeToken { pub user_id: String, pub origin: domain::Origin, pub path: Vec<TokenPurpose>, pub tenant_id: Option<id_type::TenantId>, } #[cfg(feature = "olap")] #[derive(serde::Serialize, serde::Deserialize)] pub struct SinglePurposeToken { pub user_id: String, pub purpose: TokenPurpose, pub origin: domain::Origin, pub path: Vec<TokenPurpose>, pub exp: u64, pub tenant_id: Option<id_type::TenantId>, } #[cfg(feature = "olap")] impl SinglePurposeToken { pub async fn new_token( user_id: String, purpose: TokenPurpose, origin: domain::Origin, settings: &Settings, path: Vec<TokenPurpose>, tenant_id: Option<id_type::TenantId>, ) -> UserResult<String> { let exp_duration = std::time::Duration::from_secs(consts::SINGLE_PURPOSE_TOKEN_TIME_IN_SECS); let exp = jwt::generate_exp(exp_duration)?.as_secs(); let token_payload = Self { user_id, purpose, origin, exp, path, tenant_id, }; jwt::generate_jwt(&token_payload, settings).await } } #[derive(serde::Serialize, serde::Deserialize)] pub struct AuthToken { pub user_id: String, pub merchant_id: id_type::MerchantId, pub role_id: String, pub exp: u64, pub org_id: id_type::OrganizationId, pub profile_id: id_type::ProfileId, pub tenant_id: Option<id_type::TenantId>, } #[cfg(feature = "olap")] impl AuthToken { pub async fn new_token( user_id: String, merchant_id: id_type::MerchantId, role_id: String, settings: &Settings, org_id: id_type::OrganizationId, profile_id: id_type::ProfileId, tenant_id: Option<id_type::TenantId>, ) -> UserResult<String> { let exp_duration = std::time::Duration::from_secs(consts::JWT_TOKEN_TIME_IN_SECS); let exp = jwt::generate_exp(exp_duration)?.as_secs(); let token_payload = Self { user_id, merchant_id, role_id, exp, org_id, profile_id, tenant_id, }; jwt::generate_jwt(&token_payload, settings).await } } #[derive(Clone)] pub struct UserFromToken { pub user_id: String, pub merchant_id: id_type::MerchantId, pub role_id: String, pub org_id: id_type::OrganizationId, pub profile_id: id_type::ProfileId, pub tenant_id: Option<id_type::TenantId>, } pub struct UserIdFromAuth { pub user_id: String, pub tenant_id: Option<id_type::TenantId>, } #[cfg(feature = "olap")] #[derive(serde::Serialize, serde::Deserialize)] pub struct SinglePurposeOrLoginToken { pub user_id: String, pub role_id: Option<String>, pub purpose: Option<TokenPurpose>, pub exp: u64, pub tenant_id: Option<id_type::TenantId>, } pub trait AuthInfo { fn get_merchant_id(&self) -> Option<&id_type::MerchantId>; } impl AuthInfo for () { fn get_merchant_id(&self) -> Option<&id_type::MerchantId> { None } } #[cfg(feature = "v1")] impl AuthInfo for AuthenticationData { fn get_merchant_id(&self) -> Option<&id_type::MerchantId> { Some(self.merchant_account.get_id()) } } #[cfg(feature = "v2")] impl AuthInfo for AuthenticationData { fn get_merchant_id(&self) -> Option<&id_type::MerchantId> { Some(self.merchant_account.get_id()) } } impl AuthInfo for AuthenticationDataWithMultipleProfiles { fn get_merchant_id(&self) -> Option<&id_type::MerchantId> { Some(self.merchant_account.get_id()) } } #[async_trait] pub trait AuthenticateAndFetch<T, A> where A: SessionStateInfo, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(T, AuthenticationType)>; } #[derive(Debug, Default)] pub struct ApiKeyAuth { pub is_connected_allowed: bool, pub is_platform_allowed: bool, } pub struct NoAuth; #[cfg(feature = "partial-auth")] impl GetAuthType for ApiKeyAuth { fn get_auth_type(&self) -> detached::PayloadType { detached::PayloadType::ApiKey } } // // # Header Auth // // Header Auth is a feature that allows you to authenticate requests using custom headers. This is // done by checking whether the request contains the specified headers. // - `x-merchant-id` header is used to authenticate the merchant. // // ## Checksum // - `x-auth-checksum` header is used to authenticate the request. The checksum is calculated using the // above mentioned headers is generated by hashing the headers mentioned above concatenated with `:` and then hashed with the detached authentication key. // // When the [`partial-auth`] feature is disabled the implementation for [`AuthenticateAndFetch`] // changes where the authentication is done by the [`I`] implementation. // pub struct HeaderAuth<I>(pub I); #[async_trait] impl<A> AuthenticateAndFetch<(), A> for NoAuth where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, _request_headers: &HeaderMap, _state: &A, ) -> RouterResult<((), AuthenticationType)> { Ok(((), AuthenticationType::NoAuth)) } } #[async_trait] impl<A, T> AuthenticateAndFetch<Option<T>, A> for NoAuth where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, _request_headers: &HeaderMap, _state: &A, ) -> RouterResult<(Option<T>, AuthenticationType)> { Ok((None, AuthenticationType::NoAuth)) } } #[cfg(feature = "v2")] #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationData, A> for ApiKeyAuth where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let api_key = get_api_key(request_headers) .change_context(errors::ApiErrorResponse::Unauthorized)? .trim(); if api_key.is_empty() { return Err(errors::ApiErrorResponse::Unauthorized) .attach_printable("API key is empty"); } let profile_id = HeaderMapStruct::new(request_headers) .get_id_type_from_header::<id_type::ProfileId>(headers::X_PROFILE_ID)?; let api_key = api_keys::PlaintextApiKey::from(api_key); let hash_key = { let config = state.conf(); config.api_keys.get_inner().get_hash_key()? }; let hashed_api_key = api_key.keyed_hash(hash_key.peek()); let stored_api_key = state .store() .find_api_key_by_hash_optional(hashed_api_key.into()) .await .change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed .attach_printable("Failed to retrieve API key")? .ok_or(report!(errors::ApiErrorResponse::Unauthorized)) // If retrieve returned `None` .attach_printable("Merchant not authenticated")?; if stored_api_key .expires_at .map(|expires_at| expires_at < date_time::now()) .unwrap_or(false) { return Err(report!(errors::ApiErrorResponse::Unauthorized)) .attach_printable("API key has expired"); } let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &stored_api_key.merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .change_context(errors::ApiErrorResponse::Unauthorized) .attach_printable("Failed to fetch merchant key store for the merchant id")?; let merchant = state .store() .find_merchant_account_by_merchant_id( key_manager_state, &stored_api_key.merchant_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; // Get connected merchant account if API call is done by Platform merchant account on behalf of connected merchant account let (merchant, platform_merchant_account) = if state.conf().platform.enabled { get_platform_merchant_account(state, request_headers, merchant).await? } else { (merchant, None) }; if platform_merchant_account.is_some() && !self.is_platform_allowed { return Err(report!( errors::ApiErrorResponse::PlatformAccountAuthNotSupported )) .attach_printable("Platform not authorized to access the resource"); } let key_store = if platform_merchant_account.is_some() { state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, merchant.get_id(), &state.store().get_master_key().to_vec().into(), ) .await .change_context(errors::ApiErrorResponse::Unauthorized) .attach_printable("Failed to fetch merchant key store for the merchant id")? } else { key_store }; let profile = state .store() .find_business_profile_by_profile_id(key_manager_state, &key_store, &profile_id) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let auth = AuthenticationData { merchant_account: merchant, platform_merchant_account, key_store, profile, }; Ok(( auth.clone(), AuthenticationType::ApiKey { merchant_id: auth.merchant_account.get_id().clone(), key_id: stored_api_key.key_id, }, )) } } #[cfg(feature = "v1")] #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationData, A> for ApiKeyAuth where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let api_key = get_api_key(request_headers) .change_context(errors::ApiErrorResponse::Unauthorized)? .trim(); if api_key.is_empty() { return Err(errors::ApiErrorResponse::Unauthorized) .attach_printable("API key is empty"); } let api_key = api_keys::PlaintextApiKey::from(api_key); let hash_key = { let config = state.conf(); config.api_keys.get_inner().get_hash_key()? }; let hashed_api_key = api_key.keyed_hash(hash_key.peek()); let stored_api_key = state .store() .find_api_key_by_hash_optional(hashed_api_key.into()) .await .change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed .attach_printable("Failed to retrieve API key")? .ok_or(report!(errors::ApiErrorResponse::Unauthorized)) // If retrieve returned `None` .attach_printable("Merchant not authenticated")?; if stored_api_key .expires_at .map(|expires_at| expires_at < date_time::now()) .unwrap_or(false) { return Err(report!(errors::ApiErrorResponse::Unauthorized)) .attach_printable("API key has expired"); } let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &stored_api_key.merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .change_context(errors::ApiErrorResponse::Unauthorized) .attach_printable("Failed to fetch merchant key store for the merchant id")?; let profile_id = get_header_value_by_key(headers::X_PROFILE_ID.to_string(), request_headers)? .map(id_type::ProfileId::from_str) .transpose() .change_context(errors::ValidationError::IncorrectValueProvided { field_name: "X-Profile-Id", }) .change_context(errors::ApiErrorResponse::Unauthorized)?; let merchant = state .store() .find_merchant_account_by_merchant_id( key_manager_state, &stored_api_key.merchant_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let (merchant, platform_merchant_account) = if state.conf().platform.enabled { get_platform_merchant_account(state, request_headers, merchant).await? } else { (merchant, None) }; if platform_merchant_account.is_some() && !self.is_platform_allowed { return Err(report!( errors::ApiErrorResponse::PlatformAccountAuthNotSupported )) .attach_printable("Platform not authorized to access the resource"); } let key_store = if platform_merchant_account.is_some() { state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, merchant.get_id(), &state.store().get_master_key().to_vec().into(), ) .await .change_context(errors::ApiErrorResponse::Unauthorized) .attach_printable("Failed to fetch merchant key store for the merchant id")? } else { key_store }; let auth = AuthenticationData { merchant_account: merchant, platform_merchant_account, key_store, profile_id, }; Ok(( auth.clone(), AuthenticationType::ApiKey { merchant_id: auth.merchant_account.get_id().clone(), key_id: stored_api_key.key_id, }, )) } } #[derive(Debug)] pub struct ApiKeyAuthWithMerchantIdFromRoute(pub id_type::MerchantId); #[cfg(feature = "partial-auth")] impl GetAuthType for ApiKeyAuthWithMerchantIdFromRoute { fn get_auth_type(&self) -> detached::PayloadType { detached::PayloadType::ApiKey } } #[cfg(feature = "v1")] #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationData, A> for ApiKeyAuthWithMerchantIdFromRoute where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let api_auth = ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }; let (auth_data, auth_type) = api_auth .authenticate_and_fetch(request_headers, state) .await?; let merchant_id_from_route = self.0.clone(); let merchant_id_from_api_key = auth_data.merchant_account.get_id(); if merchant_id_from_route != *merchant_id_from_api_key { return Err(report!(errors::ApiErrorResponse::Unauthorized)).attach_printable( "Merchant ID from route and Merchant ID from api-key in header do not match", ); } Ok((auth_data, auth_type)) } } #[derive(Debug, Default)] pub struct PlatformOrgAdminAuth { pub is_admin_auth_allowed: bool, pub organization_id: Option<id_type::OrganizationId>, } #[cfg(feature = "v1")] #[async_trait] impl<A> AuthenticateAndFetch<Option<AuthenticationDataWithOrg>, A> for PlatformOrgAdminAuth where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(Option<AuthenticationDataWithOrg>, AuthenticationType)> { // Step 1: Admin API Key and API Key Fallback (if allowed) if self.is_admin_auth_allowed { let admin_auth = AdminApiAuthWithApiKeyFallback { organization_id: self.organization_id.clone(), }; match admin_auth .authenticate_and_fetch(request_headers, state) .await { Ok((auth, auth_type)) => { return Ok((auth, auth_type)); } Err(e) => { logger::warn!("Admin API Auth failed: {:?}", e); } } } // Step 2: Try Platform Auth let api_key = get_api_key(request_headers) .change_context(errors::ApiErrorResponse::Unauthorized)? .trim(); if api_key.is_empty() { return Err(errors::ApiErrorResponse::Unauthorized) .attach_printable("API key is empty"); } let api_key_plaintext = api_keys::PlaintextApiKey::from(api_key); let hash_key = state.conf().api_keys.get_inner().get_hash_key()?; let hashed_api_key = api_key_plaintext.keyed_hash(hash_key.peek()); let stored_api_key = state .store() .find_api_key_by_hash_optional(hashed_api_key.into()) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to retrieve API key")? .ok_or_else(|| report!(errors::ApiErrorResponse::Unauthorized)) .attach_printable("Merchant not authenticated via API key")?; if stored_api_key .expires_at .map(|expires_at| expires_at < date_time::now()) .unwrap_or(false) { return Err(report!(errors::ApiErrorResponse::Unauthorized)) .attach_printable("API key has expired"); } let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &stored_api_key.merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .change_context(errors::ApiErrorResponse::Unauthorized) .attach_printable("Failed to fetch merchant key store for the merchant id")?; let merchant_account = state .store() .find_merchant_account_by_merchant_id( key_manager_state, &stored_api_key.merchant_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized) .attach_printable("Merchant account not found")?; if !(state.conf().platform.enabled && merchant_account.is_platform_account()) { return Err(report!(errors::ApiErrorResponse::Unauthorized) .attach_printable("Platform authentication check failed")); } if let Some(ref organization_id) = self.organization_id { if organization_id != merchant_account.get_org_id() { return Err(report!(errors::ApiErrorResponse::Unauthorized)) .attach_printable("Organization ID does not match"); } } Ok(( Some(AuthenticationDataWithOrg { organization_id: merchant_account.get_org_id().clone(), }), AuthenticationType::ApiKey { merchant_id: merchant_account.get_id().clone(), key_id: stored_api_key.key_id, }, )) } } #[cfg(feature = "v1")] #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationData, A> for PlatformOrgAdminAuth where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let api_key = get_api_key(request_headers) .change_context(errors::ApiErrorResponse::Unauthorized)? .trim(); if api_key.is_empty() { return Err(errors::ApiErrorResponse::Unauthorized) .attach_printable("API key is empty"); } let api_key_plaintext = api_keys::PlaintextApiKey::from(api_key); let hash_key = state.conf().api_keys.get_inner().get_hash_key()?; let hashed_api_key = api_key_plaintext.keyed_hash(hash_key.peek()); let stored_api_key = state .store() .find_api_key_by_hash_optional(hashed_api_key.into()) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to retrieve API key")? .ok_or_else(|| report!(errors::ApiErrorResponse::Unauthorized)) .attach_printable("Merchant not authenticated via API key")?; if stored_api_key .expires_at .map(|expires_at| expires_at < date_time::now()) .unwrap_or(false) { return Err(report!(errors::ApiErrorResponse::Unauthorized)) .attach_printable("API key has expired"); } let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &stored_api_key.merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .change_context(errors::ApiErrorResponse::Unauthorized) .attach_printable("Failed to fetch merchant key store for the merchant id")?; let merchant_account = state .store() .find_merchant_account_by_merchant_id( key_manager_state, &stored_api_key.merchant_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized) .attach_printable("Merchant account not found")?; if !(state.conf().platform.enabled && merchant_account.is_platform_account()) { return Err(report!(errors::ApiErrorResponse::Unauthorized) .attach_printable("Platform authentication check failed")); } if let Some(ref organization_id) = self.organization_id { if organization_id != merchant_account.get_org_id() { return Err(report!(errors::ApiErrorResponse::Unauthorized)) .attach_printable("Organization ID does not match"); } } let auth = AuthenticationData { merchant_account: merchant_account.clone(), platform_merchant_account: Some(merchant_account.clone()), key_store, profile_id: None, }; Ok(( auth.clone(), AuthenticationType::ApiKey { merchant_id: auth.merchant_account.get_id().clone(), key_id: stored_api_key.key_id, }, )) } } #[derive(Debug)] pub struct PlatformOrgAdminAuthWithMerchantIdFromRoute { pub merchant_id_from_route: id_type::MerchantId, pub is_admin_auth_allowed: bool, } #[cfg(feature = "v1")] impl PlatformOrgAdminAuthWithMerchantIdFromRoute { async fn fetch_key_store_and_account<A: SessionStateInfo + Sync>( merchant_id: &id_type::MerchantId, state: &A, ) -> RouterResult<(domain::MerchantKeyStore, domain::MerchantAccount)> { let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let merchant = state .store() .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; Ok((key_store, merchant)) } } #[cfg(feature = "v1")] #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationData, A> for PlatformOrgAdminAuthWithMerchantIdFromRoute where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let route_merchant_id = self.merchant_id_from_route.clone(); // Step 1: Admin API Key and API Key Fallback (if allowed) if self.is_admin_auth_allowed { let admin_auth = AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(route_merchant_id.clone()); match admin_auth .authenticate_and_fetch(request_headers, state) .await { Ok((auth_data, auth_type)) => return Ok((auth_data, auth_type)), Err(e) => { logger::warn!("Admin API Auth failed: {:?}", e); } } } // Step 2: Platform authentication let api_key = get_api_key(request_headers) .change_context(errors::ApiErrorResponse::Unauthorized)? .trim(); if api_key.is_empty() { return Err(errors::ApiErrorResponse::Unauthorized) .attach_printable("API key is empty"); } let api_key_plaintext = api_keys::PlaintextApiKey::from(api_key); let hash_key = { let config = state.conf(); config.api_keys.get_inner().get_hash_key()? }; let hashed_api_key = api_key_plaintext.keyed_hash(hash_key.peek()); let stored_api_key = state .store() .find_api_key_by_hash_optional(hashed_api_key.into()) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to retrieve API key")? .ok_or_else(|| report!(errors::ApiErrorResponse::Unauthorized)) .attach_printable("Merchant not authenticated via API key")?; if stored_api_key .expires_at .map(|expires_at| expires_at < date_time::now()) .unwrap_or(false) { return Err(report!(errors::ApiErrorResponse::Unauthorized)) .attach_printable("API key has expired"); } let (_, platform_merchant) = Self::fetch_key_store_and_account(&stored_api_key.merchant_id, state).await?; if !(state.conf().platform.enabled && platform_merchant.is_platform_account()) { return Err(report!(errors::ApiErrorResponse::Unauthorized)) .attach_printable("Platform authentication check failed"); } let (route_key_store, route_merchant) = Self::fetch_key_store_and_account(&route_merchant_id, state).await?; if platform_merchant.get_org_id() != route_merchant.get_org_id() { return Err(report!(errors::ApiErrorResponse::Unauthorized)) .attach_printable("Route merchant not under same org as platform merchant"); } let auth = AuthenticationData { merchant_account: route_merchant, platform_merchant_account: Some(platform_merchant.clone()), key_store: route_key_store, profile_id: None, }; Ok(( auth.clone(), AuthenticationType::ApiKey { merchant_id: platform_merchant.get_id().clone(), key_id: stored_api_key.key_id, }, )) } } #[cfg(not(feature = "partial-auth"))] #[async_trait] impl<A, I> AuthenticateAndFetch<AuthenticationData, A> for HeaderAuth<I> where A: SessionStateInfo + Send + Sync, I: AuthenticateAndFetch<AuthenticationData, A> + Sync + Send, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { self.0.authenticate_and_fetch(request_headers, state).await } } #[cfg(all(feature = "partial-auth", feature = "v1"))] #[async_trait] impl<A, I> AuthenticateAndFetch<AuthenticationData, A> for HeaderAuth<I> where A: SessionStateInfo + Sync, I: AuthenticateAndFetch<AuthenticationData, A> + GetAuthType + Sync + Send, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let enable_partial_auth = state.conf().api_keys.get_inner().enable_partial_auth; // This is a early return if partial auth is disabled // Preventing the need to go through the header extraction process if !enable_partial_auth { return self.0.authenticate_and_fetch(request_headers, state).await; } let report_failure = || { metrics::PARTIAL_AUTH_FAILURE.add(1, &[]); }; let profile_id = HeaderMapStruct::new(request_headers) .get_id_type_from_header_if_present::<id_type::ProfileId>(headers::X_PROFILE_ID) .change_context(errors::ValidationError::IncorrectValueProvided { field_name: "X-Profile-Id", }) .change_context(errors::ApiErrorResponse::Unauthorized)?; let payload = ExtractedPayload::from_headers(request_headers) .and_then(|value| { let (algo, secret) = state.get_detached_auth()?; Ok(value .verify_checksum(request_headers, algo, secret) .then_some(value)) }) .map(|inner_payload| { inner_payload.and_then(|inner| { (inner.payload_type == self.0.get_auth_type()).then_some(inner) }) }); match payload { Ok(Some(data)) => match data { ExtractedPayload { payload_type: detached::PayloadType::ApiKey, merchant_id: Some(merchant_id), key_id: Some(key_id), } => { let auth = construct_authentication_data( state, &merchant_id, request_headers, profile_id, ) .await?; Ok(( auth.clone(), AuthenticationType::ApiKey { merchant_id: auth.merchant_account.get_id().clone(), key_id, }, )) } ExtractedPayload { payload_type: detached::PayloadType::PublishableKey, merchant_id: Some(merchant_id), key_id: None, } => { let auth = construct_authentication_data( state, &merchant_id, request_headers, profile_id, ) .await?; Ok(( auth.clone(), AuthenticationType::PublishableKey { merchant_id: auth.merchant_account.get_id().clone(), }, )) } _ => { report_failure(); self.0.authenticate_and_fetch(request_headers, state).await } }, Ok(None) => { report_failure(); self.0.authenticate_and_fetch(request_headers, state).await } Err(error) => { logger::error!(%error, "Failed to extract payload from headers"); report_failure(); self.0.authenticate_and_fetch(request_headers, state).await } } } } #[cfg(all(feature = "partial-auth", feature = "v2"))] #[async_trait] impl<A, I> AuthenticateAndFetch<AuthenticationData, A> for HeaderAuth<I> where A: SessionStateInfo + Sync, I: AuthenticateAndFetch<AuthenticationData, A> + AuthenticateAndFetch<AuthenticationData, A> + GetAuthType + Sync + Send, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let (auth_data, auth_type): (AuthenticationData, AuthenticationType) = self .0 .authenticate_and_fetch(request_headers, state) .await?; let profile_id = HeaderMapStruct::new(request_headers) .get_id_type_from_header::<id_type::ProfileId>(headers::X_PROFILE_ID)?; let key_manager_state = &(&state.session_state()).into(); let profile = state .store() .find_business_profile_by_profile_id( key_manager_state, &auth_data.key_store, &profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let auth_data_v2 = AuthenticationData { merchant_account: auth_data.merchant_account, platform_merchant_account: auth_data.platform_merchant_account, key_store: auth_data.key_store, profile, }; Ok((auth_data_v2, auth_type)) } } #[cfg(all(feature = "partial-auth", feature = "v1"))] async fn construct_authentication_data<A>( state: &A, merchant_id: &id_type::MerchantId, request_headers: &HeaderMap, profile_id: Option<id_type::ProfileId>, ) -> RouterResult<AuthenticationData> where A: SessionStateInfo + Sync, { let key_store = state .store() .get_merchant_key_store_by_merchant_id( &(&state.session_state()).into(), merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .change_context(errors::ApiErrorResponse::Unauthorized) .attach_printable("Failed to fetch merchant key store for the merchant id")?; let merchant = state .store() .find_merchant_account_by_merchant_id( &(&state.session_state()).into(), merchant_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; // Get connected merchant account if API call is done by Platform merchant account on behalf of connected merchant account let (merchant, platform_merchant_account) = if state.conf().platform.enabled { get_platform_merchant_account(state, request_headers, merchant).await? } else { (merchant, None) }; let key_store = if platform_merchant_account.is_some() { state .store() .get_merchant_key_store_by_merchant_id( &(&state.session_state()).into(), merchant.get_id(), &state.store().get_master_key().to_vec().into(), ) .await .change_context(errors::ApiErrorResponse::Unauthorized) .attach_printable("Failed to fetch merchant key store for the merchant id")? } else { key_store }; let auth = AuthenticationData { merchant_account: merchant, platform_merchant_account, key_store, profile_id, }; Ok(auth) } #[cfg(feature = "olap")] #[derive(Debug)] pub(crate) struct SinglePurposeJWTAuth(pub TokenPurpose); #[cfg(feature = "olap")] #[async_trait] impl<A> AuthenticateAndFetch<UserFromSinglePurposeToken, A> for SinglePurposeJWTAuth where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(UserFromSinglePurposeToken, AuthenticationType)> { let payload = parse_jwt_payload::<A, SinglePurposeToken>(request_headers, state).await?; if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } authorization::check_tenant( payload.tenant_id.clone(), &state.session_state().tenant.tenant_id, )?; if self.0 != payload.purpose { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } Ok(( UserFromSinglePurposeToken { user_id: payload.user_id.clone(), origin: payload.origin.clone(), path: payload.path, tenant_id: payload.tenant_id, }, AuthenticationType::SinglePurposeJwt { user_id: payload.user_id, purpose: payload.purpose, }, )) } } #[cfg(feature = "olap")] #[async_trait] impl<A> AuthenticateAndFetch<Option<UserFromSinglePurposeToken>, A> for SinglePurposeJWTAuth where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(Option<UserFromSinglePurposeToken>, AuthenticationType)> { let payload = parse_jwt_payload::<A, SinglePurposeToken>(request_headers, state).await?; if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } authorization::check_tenant( payload.tenant_id.clone(), &state.session_state().tenant.tenant_id, )?; if self.0 != payload.purpose { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } Ok(( Some(UserFromSinglePurposeToken { user_id: payload.user_id.clone(), origin: payload.origin.clone(), path: payload.path, tenant_id: payload.tenant_id, }), AuthenticationType::SinglePurposeJwt { user_id: payload.user_id, purpose: payload.purpose, }, )) } } #[cfg(feature = "olap")] #[derive(Debug)] pub struct SinglePurposeOrLoginTokenAuth(pub TokenPurpose); #[cfg(feature = "olap")] #[async_trait] impl<A> AuthenticateAndFetch<UserIdFromAuth, A> for SinglePurposeOrLoginTokenAuth where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(UserIdFromAuth, AuthenticationType)> { let payload = parse_jwt_payload::<A, SinglePurposeOrLoginToken>(request_headers, state).await?; if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } authorization::check_tenant( payload.tenant_id.clone(), &state.session_state().tenant.tenant_id, )?; let is_purpose_equal = payload .purpose .as_ref() .is_some_and(|purpose| purpose == &self.0); let purpose_exists = payload.purpose.is_some(); let role_id_exists = payload.role_id.is_some(); if is_purpose_equal && !role_id_exists || role_id_exists && !purpose_exists { Ok(( UserIdFromAuth { user_id: payload.user_id.clone(), tenant_id: payload.tenant_id, }, AuthenticationType::SinglePurposeOrLoginJwt { user_id: payload.user_id, purpose: payload.purpose, role_id: payload.role_id, }, )) } else { Err(errors::ApiErrorResponse::InvalidJwtToken.into()) } } } #[cfg(feature = "olap")] #[derive(Debug)] pub struct AnyPurposeOrLoginTokenAuth; #[cfg(feature = "olap")] #[async_trait] impl<A> AuthenticateAndFetch<UserIdFromAuth, A> for AnyPurposeOrLoginTokenAuth where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(UserIdFromAuth, AuthenticationType)> { let payload = parse_jwt_payload::<A, SinglePurposeOrLoginToken>(request_headers, state).await?; if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } let purpose_exists = payload.purpose.is_some(); let role_id_exists = payload.role_id.is_some(); if purpose_exists ^ role_id_exists { Ok(( UserIdFromAuth { user_id: payload.user_id.clone(), tenant_id: payload.tenant_id, }, AuthenticationType::SinglePurposeOrLoginJwt { user_id: payload.user_id, purpose: payload.purpose, role_id: payload.role_id, }, )) } else { Err(errors::ApiErrorResponse::InvalidJwtToken.into()) } } } #[derive(Debug, Default)] pub struct AdminApiAuth; #[async_trait] impl<A> AuthenticateAndFetch<(), A> for AdminApiAuth where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<((), AuthenticationType)> { let request_admin_api_key = get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?; let conf = state.conf(); let admin_api_key = &conf.secrets.get_inner().admin_api_key; if request_admin_api_key != admin_api_key.peek() { Err(report!(errors::ApiErrorResponse::Unauthorized) .attach_printable("Admin Authentication Failure"))?; } Ok(((), AuthenticationType::AdminApiKey)) } } #[derive(Debug, Default)] pub struct V2AdminApiAuth; #[async_trait] impl<A> AuthenticateAndFetch<(), A> for V2AdminApiAuth where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<((), AuthenticationType)> { let header_map_struct = HeaderMapStruct::new(request_headers); let auth_string = header_map_struct.get_auth_string_from_header()?; let request_admin_api_key = auth_string .split(',') .find_map(|part| part.trim().strip_prefix("admin-api-key=")) .ok_or_else(|| { report!(errors::ApiErrorResponse::Unauthorized) .attach_printable("Unable to parse admin_api_key") })?; if request_admin_api_key.is_empty() { return Err(errors::ApiErrorResponse::Unauthorized) .attach_printable("Admin Api key is empty"); } let conf = state.conf(); let admin_api_key = &conf.secrets.get_inner().admin_api_key; if request_admin_api_key != admin_api_key.peek() { Err(report!(errors::ApiErrorResponse::Unauthorized) .attach_printable("Admin Authentication Failure"))?; } Ok(((), AuthenticationType::AdminApiKey)) } } #[derive(Debug)] pub struct AdminApiAuthWithMerchantIdFromRoute(pub id_type::MerchantId); #[cfg(feature = "v1")] #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationData, A> for AdminApiAuthWithMerchantIdFromRoute where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { AdminApiAuth .authenticate_and_fetch(request_headers, state) .await?; let merchant_id = self.0.clone(); let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let merchant = state .store() .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let auth = AuthenticationData { merchant_account: merchant, platform_merchant_account: None, key_store, profile_id: None, }; Ok(( auth, AuthenticationType::AdminApiAuthWithMerchantId { merchant_id }, )) } } #[cfg(feature = "v2")] #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationData, A> for AdminApiAuthWithMerchantIdFromRoute where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { if state.conf().platform.enabled { throw_error_if_platform_merchant_authentication_required(request_headers)?; } V2AdminApiAuth .authenticate_and_fetch(request_headers, state) .await?; let merchant_id = self.0.clone(); let profile_id = get_id_type_by_key_from_headers(headers::X_PROFILE_ID.to_string(), request_headers)? .get_required_value(headers::X_PROFILE_ID)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let profile = state .store() .find_business_profile_by_merchant_id_profile_id( key_manager_state, &key_store, &merchant_id, &profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let merchant = state .store() .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let auth = AuthenticationData { merchant_account: merchant, key_store, profile, platform_merchant_account: None, }; Ok(( auth, AuthenticationType::AdminApiAuthWithMerchantId { merchant_id }, )) } } #[cfg(feature = "v2")] #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationDataWithoutProfile, A> for AdminApiAuthWithMerchantIdFromRoute where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationDataWithoutProfile, AuthenticationType)> { if state.conf().platform.enabled { throw_error_if_platform_merchant_authentication_required(request_headers)?; } V2AdminApiAuth .authenticate_and_fetch(request_headers, state) .await?; let merchant_id = self.0.clone(); let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let merchant = state .store() .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let auth = AuthenticationDataWithoutProfile { merchant_account: merchant, key_store, }; Ok(( auth, AuthenticationType::AdminApiAuthWithMerchantId { merchant_id }, )) } } #[derive(Debug, Default)] pub struct AdminApiAuthWithApiKeyFallback { pub organization_id: Option<id_type::OrganizationId>, } #[cfg(feature = "v1")] #[async_trait] impl<A> AuthenticateAndFetch<Option<AuthenticationDataWithOrg>, A> for AdminApiAuthWithApiKeyFallback where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(Option<AuthenticationDataWithOrg>, AuthenticationType)> { let request_api_key = get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?; let conf = state.conf(); let admin_api_key = &conf.secrets.get_inner().admin_api_key; if request_api_key == admin_api_key.peek() { return Ok((None, AuthenticationType::AdminApiKey)); } let Some(fallback_merchant_ids) = conf.fallback_merchant_ids_api_key_auth.as_ref() else { return Err(report!(errors::ApiErrorResponse::Unauthorized)).attach_printable( "Api Key Authentication Failure: fallback merchant set not configured", ); }; let api_key = api_keys::PlaintextApiKey::from(request_api_key); let hash_key = conf.api_keys.get_inner().get_hash_key()?; let hashed_api_key = api_key.keyed_hash(hash_key.peek()); let stored_api_key = state .store() .find_api_key_by_hash_optional(hashed_api_key.into()) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to retrieve API key")? .ok_or(report!(errors::ApiErrorResponse::Unauthorized)) .attach_printable("Merchant not authenticated")?; if stored_api_key .expires_at .map(|expires_at| expires_at < date_time::now()) .unwrap_or(false) { return Err(report!(errors::ApiErrorResponse::Unauthorized)) .attach_printable("API key has expired"); } let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &stored_api_key.merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .change_context(errors::ApiErrorResponse::Unauthorized) .attach_printable("Failed to fetch merchant key store for the merchant id")?; let merchant = state .store() .find_merchant_account_by_merchant_id( key_manager_state, &stored_api_key.merchant_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; if let Some(ref organization_id) = self.organization_id { if organization_id != merchant.get_org_id() { return Err( report!(errors::ApiErrorResponse::Unauthorized).attach_printable( "Organization ID from request and merchant account does not match", ), ); } } if fallback_merchant_ids .merchant_ids .contains(&stored_api_key.merchant_id) { return Ok(( Some(AuthenticationDataWithOrg { organization_id: merchant.organization_id, }), AuthenticationType::ApiKey { merchant_id: stored_api_key.merchant_id, key_id: stored_api_key.key_id, }, )); } Err(report!(errors::ApiErrorResponse::Unauthorized) .attach_printable("Admin Authentication Failure")) } } #[derive(Debug, Default)] pub struct AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(pub id_type::MerchantId); #[cfg(feature = "v1")] impl AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute { async fn fetch_merchant_key_store_and_account<A: SessionStateInfo + Sync>( merchant_id: &id_type::MerchantId, state: &A, ) -> RouterResult<(domain::MerchantKeyStore, domain::MerchantAccount)> { let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let merchant = state .store() .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; Ok((key_store, merchant)) } } #[cfg(feature = "v1")] #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationData, A> for AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let merchant_id_from_route: id_type::MerchantId = self.0.clone(); let request_api_key = get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?; let conf = state.conf(); let admin_api_key: &masking::Secret<String> = &conf.secrets.get_inner().admin_api_key; if request_api_key == admin_api_key.peek() { let (key_store, merchant) = Self::fetch_merchant_key_store_and_account(&merchant_id_from_route, state).await?; let auth = AuthenticationData { merchant_account: merchant, platform_merchant_account: None, key_store, profile_id: None, }; return Ok(( auth, AuthenticationType::AdminApiAuthWithMerchantId { merchant_id: merchant_id_from_route.clone(), }, )); } let Some(fallback_merchant_ids) = conf.fallback_merchant_ids_api_key_auth.as_ref() else { return Err(report!(errors::ApiErrorResponse::Unauthorized)).attach_printable( "Api Key Authentication Failure: fallback merchant set not configured", ); }; let api_key = api_keys::PlaintextApiKey::from(request_api_key); let hash_key = conf.api_keys.get_inner().get_hash_key()?; let hashed_api_key = api_key.keyed_hash(hash_key.peek()); let stored_api_key = state .store() .find_api_key_by_hash_optional(hashed_api_key.into()) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to retrieve API key")? .ok_or(report!(errors::ApiErrorResponse::Unauthorized)) .attach_printable("Merchant not authenticated")?; if stored_api_key .expires_at .map(|expires_at| expires_at < date_time::now()) .unwrap_or(false) { return Err(report!(errors::ApiErrorResponse::Unauthorized)) .attach_printable("API key has expired"); } if fallback_merchant_ids .merchant_ids .contains(&stored_api_key.merchant_id) { let (_, api_key_merchant) = Self::fetch_merchant_key_store_and_account(&stored_api_key.merchant_id, state) .await?; let (route_key_store, route_merchant) = Self::fetch_merchant_key_store_and_account(&merchant_id_from_route, state).await?; if api_key_merchant.get_org_id() == route_merchant.get_org_id() { let auth = AuthenticationData { merchant_account: route_merchant, platform_merchant_account: None, key_store: route_key_store, profile_id: None, }; return Ok(( auth.clone(), AuthenticationType::MerchantId { merchant_id: auth.merchant_account.get_id().clone(), }, )); } } Err(report!(errors::ApiErrorResponse::Unauthorized) .attach_printable("Admin Authentication Failure")) } } /// A helper struct to extract headers from the request pub(crate) struct HeaderMapStruct<'a> { headers: &'a HeaderMap, } impl<'a> HeaderMapStruct<'a> { pub fn new(headers: &'a HeaderMap) -> Self { HeaderMapStruct { headers } } fn get_mandatory_header_value_by_key( &self, key: &str, ) -> Result<&str, error_stack::Report<errors::ApiErrorResponse>> { self.headers .get(key) .ok_or(errors::ApiErrorResponse::InvalidRequestData { message: format!("Missing header key: `{key}`"), }) .attach_printable(format!("Failed to find header key: {key}"))? .to_str() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "`{key}` in headers", }) .attach_printable(format!( "Failed to convert header value to string for header key: {key}", )) } /// Get the id type from the header /// This can be used to extract lineage ids from the headers pub fn get_id_type_from_header< T: TryFrom< std::borrow::Cow<'static, str>, Error = error_stack::Report<errors::ValidationError>, >, >( &self, key: &str, ) -> RouterResult<T> { self.get_mandatory_header_value_by_key(key) .map(|val| val.to_owned()) .and_then(|header_value| { T::try_from(std::borrow::Cow::Owned(header_value)).change_context( errors::ApiErrorResponse::InvalidRequestData { message: format!("`{key}` header is invalid"), }, ) }) } #[cfg(feature = "v2")] pub fn get_organization_id_from_header(&self) -> RouterResult<id_type::OrganizationId> { self.get_mandatory_header_value_by_key(headers::X_ORGANIZATION_ID) .map(|val| val.to_owned()) .and_then(|organization_id| { id_type::OrganizationId::try_from_string(organization_id).change_context( errors::ApiErrorResponse::InvalidRequestData { message: format!("`{}` header is invalid", headers::X_ORGANIZATION_ID), }, ) }) } pub fn get_header_value_by_key(&self, key: &str) -> Option<&str> { self.headers.get(key).and_then(|value| value.to_str().ok()) } pub fn get_auth_string_from_header(&self) -> RouterResult<&str> { self.headers .get(headers::AUTHORIZATION) .get_required_value(headers::AUTHORIZATION)? .to_str() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: headers::AUTHORIZATION, }) .attach_printable("Failed to convert authorization header to string") } pub fn get_id_type_from_header_if_present<T>(&self, key: &str) -> RouterResult<Option<T>> where T: TryFrom< std::borrow::Cow<'static, str>, Error = error_stack::Report<errors::ValidationError>, >, { self.headers .get(key) .map(|value| value.to_str()) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "`{key}` in headers", }) .attach_printable(format!( "Failed to convert header value to string for header key: {key}", ))? .map(|value| { T::try_from(std::borrow::Cow::Owned(value.to_owned())).change_context( errors::ApiErrorResponse::InvalidRequestData { message: format!("`{key}` header is invalid"), }, ) }) .transpose() } } /// Get the merchant-id from `x-merchant-id` header #[derive(Debug)] pub struct AdminApiAuthWithMerchantIdFromHeader; #[cfg(feature = "v1")] #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationData, A> for AdminApiAuthWithMerchantIdFromHeader where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { AdminApiAuth .authenticate_and_fetch(request_headers, state) .await?; let merchant_id = HeaderMapStruct::new(request_headers) .get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let merchant = state .store() .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let auth = AuthenticationData { merchant_account: merchant, platform_merchant_account: None, key_store, profile_id: None, }; Ok(( auth, AuthenticationType::AdminApiAuthWithMerchantId { merchant_id }, )) } } #[cfg(feature = "v2")] #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationData, A> for AdminApiAuthWithMerchantIdFromHeader where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { if state.conf().platform.enabled { throw_error_if_platform_merchant_authentication_required(request_headers)?; } V2AdminApiAuth .authenticate_and_fetch(request_headers, state) .await?; let merchant_id = HeaderMapStruct::new(request_headers) .get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?; let profile_id = get_id_type_by_key_from_headers(headers::X_PROFILE_ID.to_string(), request_headers)? .get_required_value(headers::X_PROFILE_ID)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let profile = state .store() .find_business_profile_by_merchant_id_profile_id( key_manager_state, &key_store, &merchant_id, &profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let merchant = state .store() .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let auth = AuthenticationData { merchant_account: merchant, key_store, profile, platform_merchant_account: None, }; Ok(( auth, AuthenticationType::AdminApiAuthWithMerchantId { merchant_id }, )) } } #[cfg(feature = "v2")] #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationDataWithoutProfile, A> for AdminApiAuthWithMerchantIdFromHeader where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationDataWithoutProfile, AuthenticationType)> { if state.conf().platform.enabled { throw_error_if_platform_merchant_authentication_required(request_headers)?; } V2AdminApiAuth .authenticate_and_fetch(request_headers, state) .await?; let merchant_id = HeaderMapStruct::new(request_headers) .get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let merchant = state .store() .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let auth = AuthenticationDataWithoutProfile { merchant_account: merchant, key_store, }; Ok(( auth, AuthenticationType::AdminApiAuthWithMerchantId { merchant_id }, )) } } #[derive(Debug)] pub struct EphemeralKeyAuth; #[cfg(feature = "v1")] #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationData, A> for EphemeralKeyAuth where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let api_key = get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?; let ephemeral_key = state .store() .get_ephemeral_key(api_key) .await .change_context(errors::ApiErrorResponse::Unauthorized)?; MerchantIdAuth(ephemeral_key.merchant_id) .authenticate_and_fetch(request_headers, state) .await } } #[derive(Debug)] #[cfg(feature = "v1")] pub struct MerchantIdAuth(pub id_type::MerchantId); #[cfg(feature = "v1")] #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationData, A> for MerchantIdAuth where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { if state.conf().platform.enabled { throw_error_if_platform_merchant_authentication_required(request_headers)?; } let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &self.0, &state.store().get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let merchant = state .store() .find_merchant_account_by_merchant_id(key_manager_state, &self.0, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let auth = AuthenticationData { merchant_account: merchant, platform_merchant_account: None, key_store, profile_id: None, }; Ok(( auth.clone(), AuthenticationType::MerchantId { merchant_id: auth.merchant_account.get_id().clone(), }, )) } } #[derive(Debug)] #[cfg(feature = "v2")] pub struct MerchantIdAuth; #[cfg(feature = "v2")] #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationData, A> for MerchantIdAuth where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { if state.conf().platform.enabled { throw_error_if_platform_merchant_authentication_required(request_headers)?; } let key_manager_state = &(&state.session_state()).into(); let merchant_id = HeaderMapStruct::new(request_headers) .get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?; let profile_id = get_id_type_by_key_from_headers(headers::X_PROFILE_ID.to_string(), request_headers)? .get_required_value(headers::X_PROFILE_ID)?; let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let profile = state .store() .find_business_profile_by_merchant_id_profile_id( key_manager_state, &key_store, &merchant_id, &profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let merchant = state .store() .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let auth = AuthenticationData { merchant_account: merchant, key_store, profile, platform_merchant_account: None, }; Ok(( auth.clone(), AuthenticationType::MerchantId { merchant_id: auth.merchant_account.get_id().clone(), }, )) } } /// InternalMerchantIdProfileIdAuth authentication which first tries to authenticate using `X-Internal-API-Key`, /// `X-Merchant-Id` and `X-Profile-Id` headers. If any of these headers are missing, /// it falls back to the provided authentication mechanism. #[cfg(feature = "v1")] pub struct InternalMerchantIdProfileIdAuth<F>(pub F); #[cfg(feature = "v1")] #[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 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(|s| s.to_string()); let 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) { let config = state.conf(); if internal_api_key != *config .internal_merchant_id_profile_id_auth .internal_api_key .peek() { return Err(errors::ApiErrorResponse::Unauthorized) .attach_printable("Internal API key authentication failed"); } let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let _profile = state .store() .find_business_profile_by_merchant_id_profile_id( key_manager_state, &key_store, &merchant_id, &profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let merchant = state .store() .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let auth = AuthenticationData { merchant_account: merchant, key_store, profile_id: Some(profile_id.clone()), platform_merchant_account: None, }; Ok(( auth.clone(), AuthenticationType::InternalMerchantIdProfileId { merchant_id, profile_id: Some(profile_id), }, )) } else { Ok(self .0 .authenticate_and_fetch(request_headers, state) .await?) } } } #[derive(Debug)] #[cfg(feature = "v2")] pub struct MerchantIdAndProfileIdAuth { pub merchant_id: id_type::MerchantId, pub profile_id: id_type::ProfileId, } #[cfg(feature = "v2")] #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationData, A> for MerchantIdAndProfileIdAuth where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { if state.conf().platform.enabled { throw_error_if_platform_merchant_authentication_required(request_headers)?; } let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &self.merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let profile = state .store() .find_business_profile_by_merchant_id_profile_id( key_manager_state, &key_store, &self.merchant_id, &self.profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let merchant = state .store() .find_merchant_account_by_merchant_id(key_manager_state, &self.merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let auth = AuthenticationData { merchant_account: merchant, key_store, profile, platform_merchant_account: None, }; Ok(( auth.clone(), AuthenticationType::MerchantId { merchant_id: auth.merchant_account.get_id().clone(), }, )) } } #[derive(Debug)] #[cfg(feature = "v2")] pub struct PublishableKeyAndProfileIdAuth { pub publishable_key: String, pub profile_id: id_type::ProfileId, } #[async_trait] #[cfg(feature = "v2")] impl<A> AuthenticateAndFetch<AuthenticationData, A> for PublishableKeyAndProfileIdAuth where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, _request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let key_manager_state = &(&state.session_state()).into(); let (merchant_account, key_store) = state .store() .find_merchant_account_by_publishable_key( key_manager_state, self.publishable_key.as_str(), ) .await .map_err(|e| { if e.current_context().is_db_not_found() { e.change_context(errors::ApiErrorResponse::Unauthorized) } else { e.change_context(errors::ApiErrorResponse::InternalServerError) } })?; let profile = state .store() .find_business_profile_by_profile_id(key_manager_state, &key_store, &self.profile_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: self.profile_id.get_string_repr().to_owned(), })?; let merchant_id = merchant_account.get_id().clone(); Ok(( AuthenticationData { merchant_account, key_store, profile, platform_merchant_account: None, }, AuthenticationType::PublishableKey { merchant_id }, )) } } /// Take api-key from `Authorization` header #[cfg(feature = "v2")] #[derive(Debug)] pub struct V2ApiKeyAuth { pub is_connected_allowed: bool, pub is_platform_allowed: bool, } #[cfg(feature = "v2")] #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationData, A> for V2ApiKeyAuth where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let header_map_struct = HeaderMapStruct::new(request_headers); let auth_string = header_map_struct.get_auth_string_from_header()?; let api_key = auth_string .split(',') .find_map(|part| part.trim().strip_prefix("api-key=")) .ok_or_else(|| { report!(errors::ApiErrorResponse::Unauthorized) .attach_printable("Unable to parse api_key") })?; if api_key.is_empty() { return Err(errors::ApiErrorResponse::Unauthorized) .attach_printable("API key is empty"); } let profile_id = HeaderMapStruct::new(request_headers) .get_id_type_from_header::<id_type::ProfileId>(headers::X_PROFILE_ID)?; let api_key = api_keys::PlaintextApiKey::from(api_key); let hash_key = { let config = state.conf(); config.api_keys.get_inner().get_hash_key()? }; let hashed_api_key = api_key.keyed_hash(hash_key.peek()); let stored_api_key = state .store() .find_api_key_by_hash_optional(hashed_api_key.into()) .await .change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed .attach_printable("Failed to retrieve API key")? .ok_or(report!(errors::ApiErrorResponse::Unauthorized)) // If retrieve returned `None` .attach_printable("Merchant not authenticated")?; if stored_api_key .expires_at .map(|expires_at| expires_at < date_time::now()) .unwrap_or(false) { return Err(report!(errors::ApiErrorResponse::Unauthorized)) .attach_printable("API key has expired"); } let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &stored_api_key.merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .change_context(errors::ApiErrorResponse::Unauthorized) .attach_printable("Failed to fetch merchant key store for the merchant id")?; let merchant = state .store() .find_merchant_account_by_merchant_id( key_manager_state, &stored_api_key.merchant_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; // Get connected merchant account if API call is done by Platform merchant account on behalf of connected merchant account let (merchant, platform_merchant_account) = if state.conf().platform.enabled { get_platform_merchant_account(state, request_headers, merchant).await? } else { (merchant, None) }; if platform_merchant_account.is_some() && !self.is_platform_allowed { return Err(report!( errors::ApiErrorResponse::PlatformAccountAuthNotSupported )) .attach_printable("Platform not authorized to access the resource"); } let key_store = if platform_merchant_account.is_some() { state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, merchant.get_id(), &state.store().get_master_key().to_vec().into(), ) .await .change_context(errors::ApiErrorResponse::Unauthorized) .attach_printable("Failed to fetch merchant key store for the merchant id")? } else { key_store }; let profile = state .store() .find_business_profile_by_profile_id(key_manager_state, &key_store, &profile_id) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let auth = AuthenticationData { merchant_account: merchant, platform_merchant_account, key_store, profile, }; Ok(( auth.clone(), AuthenticationType::ApiKey { merchant_id: auth.merchant_account.get_id().clone(), key_id: stored_api_key.key_id, }, )) } } #[cfg(feature = "v2")] #[derive(Debug)] pub struct V2ClientAuth(pub common_utils::types::authentication::ResourceId); #[cfg(feature = "v2")] #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationData, A> for V2ClientAuth where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let header_map_struct = HeaderMapStruct::new(request_headers); let auth_string = header_map_struct.get_auth_string_from_header()?; let publishable_key = auth_string .split(',') .find_map(|part| part.trim().strip_prefix("publishable-key=")) .ok_or_else(|| { report!(errors::ApiErrorResponse::Unauthorized) .attach_printable("Unable to parse publishable_key") })?; let client_secret = auth_string .split(',') .find_map(|part| part.trim().strip_prefix("client-secret=")) .ok_or_else(|| { report!(errors::ApiErrorResponse::Unauthorized) .attach_printable("Unable to parse client_secret") })?; let key_manager_state: &common_utils::types::keymanager::KeyManagerState = &(&state.session_state()).into(); let db_client_secret: diesel_models::ClientSecretType = state .store() .get_client_secret(client_secret) .await .change_context(errors::ApiErrorResponse::Unauthorized) .attach_printable("Invalid ephemeral_key")?; let profile_id = get_id_type_by_key_from_headers(headers::X_PROFILE_ID.to_string(), request_headers)? .get_required_value(headers::X_PROFILE_ID)?; match (&self.0, &db_client_secret.resource_id) { ( common_utils::types::authentication::ResourceId::Payment(self_id), common_utils::types::authentication::ResourceId::Payment(db_id), ) => { fp_utils::when(self_id != db_id, || { Err::<(), errors::ApiErrorResponse>(errors::ApiErrorResponse::Unauthorized) }); } ( common_utils::types::authentication::ResourceId::Customer(self_id), common_utils::types::authentication::ResourceId::Customer(db_id), ) => { fp_utils::when(self_id != db_id, || { Err::<(), errors::ApiErrorResponse>(errors::ApiErrorResponse::Unauthorized) }); } ( common_utils::types::authentication::ResourceId::PaymentMethodSession(self_id), common_utils::types::authentication::ResourceId::PaymentMethodSession(db_id), ) => { fp_utils::when(self_id != db_id, || { Err::<(), errors::ApiErrorResponse>(errors::ApiErrorResponse::Unauthorized) }); } _ => { return Err(errors::ApiErrorResponse::Unauthorized.into()); } } let (merchant_account, key_store) = state .store() .find_merchant_account_by_publishable_key(key_manager_state, publishable_key) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let merchant_id = merchant_account.get_id().clone(); if db_client_secret.merchant_id != merchant_id { return Err(errors::ApiErrorResponse::Unauthorized.into()); } let profile = state .store() .find_business_profile_by_merchant_id_profile_id( key_manager_state, &key_store, &merchant_id, &profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; Ok(( AuthenticationData { merchant_account, key_store, profile, platform_merchant_account: None, }, AuthenticationType::PublishableKey { merchant_id }, )) } } #[cfg(feature = "v2")] pub fn api_or_client_auth<'a, T, A>( api_auth: &'a dyn AuthenticateAndFetch<T, A>, client_auth: &'a dyn AuthenticateAndFetch<T, A>, headers: &HeaderMap, ) -> &'a dyn AuthenticateAndFetch<T, A> where { if let Ok(val) = HeaderMapStruct::new(headers).get_auth_string_from_header() { if val.trim().starts_with("api-key=") { api_auth } else { client_auth } } else { api_auth } } #[cfg(feature = "v2")] pub fn api_or_client_or_jwt_auth<'a, T, A>( api_auth: &'a dyn AuthenticateAndFetch<T, A>, client_auth: &'a dyn AuthenticateAndFetch<T, A>, jwt_auth: &'a dyn AuthenticateAndFetch<T, A>, headers: &HeaderMap, ) -> &'a dyn AuthenticateAndFetch<T, A> where { if let Ok(val) = HeaderMapStruct::new(headers).get_auth_string_from_header() { if val.trim().starts_with("api-key=") { api_auth } else if is_jwt_auth(headers) { jwt_auth } else { client_auth } } else { api_auth } } #[derive(Debug)] pub struct PublishableKeyAuth; #[cfg(feature = "partial-auth")] impl GetAuthType for PublishableKeyAuth { fn get_auth_type(&self) -> detached::PayloadType { detached::PayloadType::PublishableKey } } #[cfg(feature = "v1")] #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationData, A> for PublishableKeyAuth where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { if state.conf().platform.enabled { throw_error_if_platform_merchant_authentication_required(request_headers)?; } let publishable_key = get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?; let key_manager_state = &(&state.session_state()).into(); state .store() .find_merchant_account_by_publishable_key(key_manager_state, publishable_key) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized) .map(|(merchant_account, key_store)| { let merchant_id = merchant_account.get_id().clone(); ( AuthenticationData { merchant_account, platform_merchant_account: None, key_store, profile_id: None, }, AuthenticationType::PublishableKey { merchant_id }, ) }) } } #[cfg(feature = "v2")] #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationData, A> for PublishableKeyAuth where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let publishable_key = get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?; let key_manager_state = &(&state.session_state()).into(); let profile_id = get_id_type_by_key_from_headers(headers::X_PROFILE_ID.to_string(), request_headers)? .get_required_value(headers::X_PROFILE_ID)?; let (merchant_account, key_store) = state .store() .find_merchant_account_by_publishable_key(key_manager_state, publishable_key) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let merchant_id = merchant_account.get_id().clone(); let profile = state .store() .find_business_profile_by_merchant_id_profile_id( key_manager_state, &key_store, &merchant_id, &profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; Ok(( AuthenticationData { merchant_account, key_store, profile, platform_merchant_account: None, }, AuthenticationType::PublishableKey { merchant_id }, )) } } #[derive(Debug)] pub(crate) struct JWTAuth { pub permission: Permission, } #[async_trait] impl<A> AuthenticateAndFetch<(), A> for JWTAuth where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<((), AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } authorization::check_tenant( payload.tenant_id.clone(), &state.session_state().tenant.tenant_id, )?; let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(self.permission, &role_info)?; Ok(( (), AuthenticationType::MerchantJwt { merchant_id: payload.merchant_id, user_id: Some(payload.user_id), }, )) } } #[cfg(feature = "olap")] #[async_trait] impl<A> AuthenticateAndFetch<UserFromToken, A> for JWTAuth where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(UserFromToken, AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } authorization::check_tenant( payload.tenant_id.clone(), &state.session_state().tenant.tenant_id, )?; let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(self.permission, &role_info)?; Ok(( UserFromToken { user_id: payload.user_id.clone(), merchant_id: payload.merchant_id.clone(), org_id: payload.org_id, role_id: payload.role_id, profile_id: payload.profile_id, tenant_id: payload.tenant_id, }, AuthenticationType::MerchantJwt { merchant_id: payload.merchant_id, user_id: Some(payload.user_id), }, )) } } #[cfg(feature = "olap")] #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationDataWithMultipleProfiles, A> for JWTAuth where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationDataWithMultipleProfiles, AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } authorization::check_tenant( payload.tenant_id.clone(), &state.session_state().tenant.tenant_id, )?; let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(self.permission, &role_info)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &payload.merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .change_context(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant key store for the merchant id")?; let merchant = state .store() .find_merchant_account_by_merchant_id( key_manager_state, &payload.merchant_id, &key_store, ) .await .change_context(errors::ApiErrorResponse::InvalidJwtToken)?; Ok(( AuthenticationDataWithMultipleProfiles { key_store, merchant_account: merchant, profile_id_list: None, }, AuthenticationType::MerchantJwt { merchant_id: payload.merchant_id, user_id: Some(payload.user_id), }, )) } } pub struct JWTAuthOrganizationFromRoute { pub organization_id: id_type::OrganizationId, pub required_permission: Permission, } #[cfg(feature = "v1")] #[async_trait] impl<A> AuthenticateAndFetch<Option<AuthenticationDataWithOrg>, A> for JWTAuthOrganizationFromRoute where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(Option<AuthenticationDataWithOrg>, AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } authorization::check_tenant( payload.tenant_id.clone(), &state.session_state().tenant.tenant_id, )?; let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(self.required_permission, &role_info)?; // Check if token has access to Organization that has been requested in the route if payload.org_id != self.organization_id { return Err(report!(errors::ApiErrorResponse::InvalidJwtToken)); } Ok(( Some(AuthenticationDataWithOrg { organization_id: payload.org_id.clone(), }), AuthenticationType::OrganizationJwt { org_id: payload.org_id, user_id: payload.user_id, }, )) } } #[cfg(feature = "v2")] #[async_trait] impl<A> AuthenticateAndFetch<(), A> for JWTAuthOrganizationFromRoute where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<((), AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } authorization::check_tenant( payload.tenant_id.clone(), &state.session_state().tenant.tenant_id, )?; let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(self.required_permission, &role_info)?; // Check if token has access to Organization that has been requested in the route if payload.org_id != self.organization_id { return Err(report!(errors::ApiErrorResponse::InvalidJwtToken)); } Ok(( (), AuthenticationType::OrganizationJwt { org_id: payload.org_id, user_id: payload.user_id, }, )) } } pub struct JWTAuthMerchantFromRoute { pub merchant_id: id_type::MerchantId, pub required_permission: Permission, } pub struct JWTAuthMerchantFromHeader { pub required_permission: Permission, } #[async_trait] impl<A> AuthenticateAndFetch<(), A> for JWTAuthMerchantFromHeader where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<((), AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } authorization::check_tenant( payload.tenant_id.clone(), &state.session_state().tenant.tenant_id, )?; let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(self.required_permission, &role_info)?; let merchant_id_from_header = HeaderMapStruct::new(request_headers) .get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?; // Check if token has access to MerchantId that has been requested through headers if payload.merchant_id != merchant_id_from_header { return Err(report!(errors::ApiErrorResponse::InvalidJwtToken)); } Ok(( (), AuthenticationType::MerchantJwt { merchant_id: payload.merchant_id, user_id: Some(payload.user_id), }, )) } } #[cfg(feature = "v1")] #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationData, A> for JWTAuthMerchantFromHeader where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } authorization::check_tenant( payload.tenant_id.clone(), &state.session_state().tenant.tenant_id, )?; let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(self.required_permission, &role_info)?; let merchant_id_from_header = HeaderMapStruct::new(request_headers) .get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?; // Check if token has access to MerchantId that has been requested through headers if payload.merchant_id != merchant_id_from_header { return Err(report!(errors::ApiErrorResponse::InvalidJwtToken)); } let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &payload.merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant key store for the merchant id")?; let merchant = state .store() .find_merchant_account_by_merchant_id( key_manager_state, &payload.merchant_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant account for the merchant id")?; let auth = AuthenticationData { merchant_account: merchant, platform_merchant_account: None, key_store, profile_id: Some(payload.profile_id), }; Ok(( auth, AuthenticationType::MerchantJwt { merchant_id: payload.merchant_id, user_id: Some(payload.user_id), }, )) } } #[cfg(feature = "v1")] #[async_trait] impl<A> AuthenticateAndFetch<Option<AuthenticationDataWithOrg>, A> for JWTAuthMerchantFromHeader where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(Option<AuthenticationDataWithOrg>, AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } authorization::check_tenant( payload.tenant_id.clone(), &state.session_state().tenant.tenant_id, )?; let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(self.required_permission, &role_info)?; let merchant_id_from_header = HeaderMapStruct::new(request_headers) .get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?; // Check if token has access to MerchantId that has been requested through headers if payload.merchant_id != merchant_id_from_header { return Err(report!(errors::ApiErrorResponse::InvalidJwtToken)); } let auth = Some(AuthenticationDataWithOrg { organization_id: payload.org_id, }); Ok(( auth, AuthenticationType::MerchantJwt { merchant_id: payload.merchant_id, user_id: Some(payload.user_id), }, )) } } #[cfg(feature = "v2")] #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationData, A> for JWTAuthMerchantFromHeader where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } let profile_id = get_id_type_by_key_from_headers(headers::X_PROFILE_ID.to_string(), request_headers)? .get_required_value(headers::X_PROFILE_ID)?; let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(self.required_permission, &role_info)?; let merchant_id_from_header = HeaderMapStruct::new(request_headers) .get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?; // Check if token has access to MerchantId that has been requested through headers if payload.merchant_id != merchant_id_from_header { return Err(report!(errors::ApiErrorResponse::InvalidJwtToken)); } let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &payload.merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant key store for the merchant id")?; let profile = state .store() .find_business_profile_by_merchant_id_profile_id( key_manager_state, &key_store, &payload.merchant_id, &profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let merchant = state .store() .find_merchant_account_by_merchant_id( key_manager_state, &payload.merchant_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant account for the merchant id")?; let auth = AuthenticationData { merchant_account: merchant, key_store, profile, platform_merchant_account: None, }; Ok(( auth, AuthenticationType::MerchantJwt { merchant_id: payload.merchant_id, user_id: Some(payload.user_id), }, )) } } #[cfg(feature = "v2")] #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationDataWithoutProfile, A> for JWTAuthMerchantFromHeader where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationDataWithoutProfile, AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(self.required_permission, &role_info)?; let merchant_id_from_header = HeaderMapStruct::new(request_headers) .get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?; // Check if token has access to MerchantId that has been requested through headers if payload.merchant_id != merchant_id_from_header { return Err(report!(errors::ApiErrorResponse::InvalidJwtToken)); } let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &payload.merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant key store for the merchant id")?; let merchant = state .store() .find_merchant_account_by_merchant_id( key_manager_state, &payload.merchant_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant account for the merchant id")?; let auth = AuthenticationDataWithoutProfile { merchant_account: merchant, key_store, }; Ok(( auth, AuthenticationType::MerchantJwt { merchant_id: payload.merchant_id, user_id: Some(payload.user_id), }, )) } } #[async_trait] impl<A> AuthenticateAndFetch<(), A> for JWTAuthMerchantFromRoute where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<((), AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } authorization::check_tenant( payload.tenant_id.clone(), &state.session_state().tenant.tenant_id, )?; let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(self.required_permission, &role_info)?; // Check if token has access to MerchantId that has been requested through query param if payload.merchant_id != self.merchant_id { return Err(report!(errors::ApiErrorResponse::InvalidJwtToken)); } Ok(( (), AuthenticationType::MerchantJwt { merchant_id: payload.merchant_id, user_id: Some(payload.user_id), }, )) } } #[cfg(feature = "v1")] #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationData, A> for JWTAuthMerchantFromRoute where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } authorization::check_tenant( payload.tenant_id.clone(), &state.session_state().tenant.tenant_id, )?; if payload.merchant_id != self.merchant_id { return Err(report!(errors::ApiErrorResponse::InvalidJwtToken)); } let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(self.required_permission, &role_info)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &payload.merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant key store for the merchant id")?; let merchant = state .store() .find_merchant_account_by_merchant_id( key_manager_state, &payload.merchant_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant account for the merchant id")?; let auth = AuthenticationData { merchant_account: merchant, platform_merchant_account: None, key_store, profile_id: Some(payload.profile_id), }; Ok(( auth.clone(), AuthenticationType::MerchantJwt { merchant_id: auth.merchant_account.get_id().clone(), user_id: Some(payload.user_id), }, )) } } #[cfg(feature = "v2")] #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationData, A> for JWTAuthMerchantFromRoute where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; let profile_id = get_id_type_by_key_from_headers(headers::X_PROFILE_ID.to_string(), request_headers)? .get_required_value(headers::X_PROFILE_ID)?; if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } if payload.merchant_id != self.merchant_id { return Err(report!(errors::ApiErrorResponse::InvalidJwtToken)); } let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(self.required_permission, &role_info)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &payload.merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant key store for the merchant id")?; let profile = state .store() .find_business_profile_by_merchant_id_profile_id( key_manager_state, &key_store, &payload.merchant_id, &profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let merchant = state .store() .find_merchant_account_by_merchant_id( key_manager_state, &payload.merchant_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant account for the merchant id")?; let auth = AuthenticationData { merchant_account: merchant, key_store, profile, platform_merchant_account: None, }; Ok(( auth.clone(), AuthenticationType::MerchantJwt { merchant_id: auth.merchant_account.get_id().clone(), user_id: Some(payload.user_id), }, )) } } #[cfg(feature = "v2")] #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationDataWithoutProfile, A> for JWTAuthMerchantFromRoute where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationDataWithoutProfile, AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } if payload.merchant_id != self.merchant_id { return Err(report!(errors::ApiErrorResponse::InvalidJwtToken)); } let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(self.required_permission, &role_info)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &payload.merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant key store for the merchant id")?; let merchant = state .store() .find_merchant_account_by_merchant_id( key_manager_state, &payload.merchant_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant account for the merchant id")?; let auth = AuthenticationDataWithoutProfile { merchant_account: merchant, key_store, }; Ok(( auth.clone(), AuthenticationType::MerchantJwt { merchant_id: auth.merchant_account.get_id().clone(), user_id: Some(payload.user_id), }, )) } } pub struct JWTAuthMerchantAndProfileFromRoute { pub merchant_id: id_type::MerchantId, pub profile_id: id_type::ProfileId, pub required_permission: Permission, } #[cfg(feature = "v1")] #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationData, A> for JWTAuthMerchantAndProfileFromRoute where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } authorization::check_tenant( payload.tenant_id.clone(), &state.session_state().tenant.tenant_id, )?; if payload.merchant_id != self.merchant_id { return Err(report!(errors::ApiErrorResponse::InvalidJwtToken)); } if payload.profile_id != self.profile_id { return Err(report!(errors::ApiErrorResponse::InvalidJwtToken)); } let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(self.required_permission, &role_info)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &payload.merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant key store for the merchant id")?; let merchant = state .store() .find_merchant_account_by_merchant_id( key_manager_state, &payload.merchant_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant account for the merchant id")?; let auth = AuthenticationData { merchant_account: merchant, platform_merchant_account: None, key_store, profile_id: Some(payload.profile_id), }; Ok(( auth.clone(), AuthenticationType::MerchantJwtWithProfileId { merchant_id: auth.merchant_account.get_id().clone(), profile_id: auth.profile_id.clone(), user_id: payload.user_id, }, )) } } pub struct JWTAuthProfileFromRoute { pub profile_id: id_type::ProfileId, pub required_permission: Permission, } #[cfg(feature = "v1")] #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationData, A> for JWTAuthProfileFromRoute where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } authorization::check_tenant( payload.tenant_id.clone(), &state.session_state().tenant.tenant_id, )?; let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(self.required_permission, &role_info)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &payload.merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant key store for the merchant id")?; let merchant = state .store() .find_merchant_account_by_merchant_id( key_manager_state, &payload.merchant_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant account for the merchant id")?; if payload.profile_id != self.profile_id { return Err(report!(errors::ApiErrorResponse::InvalidJwtToken)); } else { // if both of them are same then proceed with the profile id present in the request let auth = AuthenticationData { merchant_account: merchant, platform_merchant_account: None, key_store, profile_id: Some(self.profile_id.clone()), }; Ok(( auth.clone(), AuthenticationType::MerchantJwt { merchant_id: auth.merchant_account.get_id().clone(), user_id: Some(payload.user_id), }, )) } } } #[cfg(feature = "v2")] #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationData, A> for JWTAuthProfileFromRoute where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } let profile_id = get_id_type_by_key_from_headers(headers::X_PROFILE_ID.to_string(), request_headers)? .get_required_value(headers::X_PROFILE_ID)?; let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(self.required_permission, &role_info)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &payload.merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant key store for the merchant id")?; let profile = state .store() .find_business_profile_by_merchant_id_profile_id( key_manager_state, &key_store, &payload.merchant_id, &profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let merchant = state .store() .find_merchant_account_by_merchant_id( key_manager_state, &payload.merchant_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant account for the merchant id")?; let auth = AuthenticationData { merchant_account: merchant, key_store, profile, platform_merchant_account: None, }; Ok(( auth.clone(), AuthenticationType::MerchantJwt { merchant_id: auth.merchant_account.get_id().clone(), user_id: Some(payload.user_id), }, )) } } pub async fn parse_jwt_payload<A, T>(headers: &HeaderMap, state: &A) -> RouterResult<T> where T: serde::de::DeserializeOwned, A: SessionStateInfo + Sync, { let cookie_token_result = get_cookie_from_header(headers).and_then(cookies::get_jwt_from_cookies); let auth_header_token_result = get_jwt_from_authorization_header(headers); let force_cookie = state.conf().user.force_cookies; logger::info!( user_agent = ?headers.get(headers::USER_AGENT), header_names = ?headers.keys().collect::<Vec<_>>(), is_token_equal = auth_header_token_result.as_deref().ok() == cookie_token_result.as_deref().ok(), cookie_error = ?cookie_token_result.as_ref().err(), token_error = ?auth_header_token_result.as_ref().err(), force_cookie, ); let final_token = if force_cookie { cookie_token_result? } else { auth_header_token_result?.to_owned() }; decode_jwt(&final_token, state).await } #[cfg(feature = "v1")] #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationData, A> for JWTAuth where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } authorization::check_tenant( payload.tenant_id.clone(), &state.session_state().tenant.tenant_id, )?; let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(self.permission, &role_info)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &payload.merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant key store for the merchant id")?; let merchant = state .store() .find_merchant_account_by_merchant_id( key_manager_state, &payload.merchant_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant account for the merchant id")?; let merchant_id = merchant.get_id().clone(); let auth = AuthenticationData { merchant_account: merchant, platform_merchant_account: None, key_store, profile_id: Some(payload.profile_id), }; Ok(( auth, AuthenticationType::MerchantJwt { merchant_id, user_id: Some(payload.user_id), }, )) } } #[cfg(feature = "v2")] #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationData, A> for JWTAuth where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } authorization::check_tenant( payload.tenant_id.clone(), &state.session_state().tenant.tenant_id, )?; let profile_id = HeaderMapStruct::new(request_headers) .get_id_type_from_header::<id_type::ProfileId>(headers::X_PROFILE_ID)?; let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(self.permission, &role_info)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &payload.merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant key store for the merchant id")?; let profile = state .store() .find_business_profile_by_merchant_id_profile_id( key_manager_state, &key_store, &payload.merchant_id, &profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let merchant = state .store() .find_merchant_account_by_merchant_id( key_manager_state, &payload.merchant_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant account for the merchant id")?; let merchant_id = merchant.get_id().clone(); let auth = AuthenticationData { merchant_account: merchant, key_store, profile, platform_merchant_account: None, }; Ok(( auth, AuthenticationType::MerchantJwt { merchant_id, user_id: Some(payload.user_id), }, )) } } pub type AuthenticationDataWithUserId = (AuthenticationData, String); #[cfg(feature = "v1")] #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationDataWithUserId, A> for JWTAuth where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationDataWithUserId, AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } authorization::check_tenant( payload.tenant_id.clone(), &state.session_state().tenant.tenant_id, )?; let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(self.permission, &role_info)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &payload.merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .change_context(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant key store for the merchant id")?; let merchant = state .store() .find_merchant_account_by_merchant_id( key_manager_state, &payload.merchant_id, &key_store, ) .await .change_context(errors::ApiErrorResponse::InvalidJwtToken)?; let auth = AuthenticationData { merchant_account: merchant, platform_merchant_account: None, key_store, profile_id: Some(payload.profile_id), }; Ok(( (auth.clone(), payload.user_id.clone()), AuthenticationType::MerchantJwt { merchant_id: auth.merchant_account.get_id().clone(), user_id: None, }, )) } } pub struct DashboardNoPermissionAuth; #[cfg(feature = "olap")] #[async_trait] impl<A> AuthenticateAndFetch<UserFromToken, A> for DashboardNoPermissionAuth where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(UserFromToken, AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } authorization::check_tenant( payload.tenant_id.clone(), &state.session_state().tenant.tenant_id, )?; Ok(( UserFromToken { user_id: payload.user_id.clone(), merchant_id: payload.merchant_id.clone(), org_id: payload.org_id, role_id: payload.role_id, profile_id: payload.profile_id, tenant_id: payload.tenant_id, }, AuthenticationType::MerchantJwt { merchant_id: payload.merchant_id, user_id: Some(payload.user_id), }, )) } } #[cfg(feature = "olap")] #[async_trait] impl<A> AuthenticateAndFetch<(), A> for DashboardNoPermissionAuth where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<((), AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } authorization::check_tenant( payload.tenant_id.clone(), &state.session_state().tenant.tenant_id, )?; Ok(((), AuthenticationType::NoAuth)) } } #[cfg(feature = "v1")] #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationData, A> for DashboardNoPermissionAuth where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; authorization::check_tenant( payload.tenant_id.clone(), &state.session_state().tenant.tenant_id, )?; let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &payload.merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .change_context(errors::ApiErrorResponse::Unauthorized) .attach_printable("Failed to fetch merchant key store for the merchant id")?; let merchant = state .store() .find_merchant_account_by_merchant_id( key_manager_state, &payload.merchant_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let auth = AuthenticationData { merchant_account: merchant, platform_merchant_account: None, key_store, profile_id: Some(payload.profile_id), }; Ok(( auth.clone(), AuthenticationType::MerchantJwt { merchant_id: auth.merchant_account.get_id().clone(), user_id: Some(payload.user_id), }, )) } } pub trait ClientSecretFetch { fn get_client_secret(&self) -> Option<&String>; } #[cfg(feature = "payouts")] impl ClientSecretFetch for payouts::PayoutCreateRequest { fn get_client_secret(&self) -> Option<&String> { self.client_secret.as_ref() } } #[cfg(feature = "v1")] impl ClientSecretFetch for payments::PaymentsRequest { fn get_client_secret(&self) -> Option<&String> { self.client_secret.as_ref() } } #[cfg(feature = "v1")] impl ClientSecretFetch for payments::PaymentsEligibilityRequest { fn get_client_secret(&self) -> Option<&String> { self.client_secret .as_ref() .map(|client_secret| client_secret.peek()) } } #[cfg(feature = "v1")] impl ClientSecretFetch for api_models::blocklist::ListBlocklistQuery { fn get_client_secret(&self) -> Option<&String> { self.client_secret.as_ref() } } #[cfg(feature = "v1")] impl ClientSecretFetch for payments::PaymentsRetrieveRequest { fn get_client_secret(&self) -> Option<&String> { self.client_secret.as_ref() } } #[cfg(feature = "v1")] impl ClientSecretFetch for PaymentMethodListRequest { fn get_client_secret(&self) -> Option<&String> { self.client_secret.as_ref() } } impl ClientSecretFetch for payments::PaymentsPostSessionTokensRequest { fn get_client_secret(&self) -> Option<&String> { Some(self.client_secret.peek()) } } #[cfg(feature = "v1")] impl ClientSecretFetch for PaymentMethodCreate { fn get_client_secret(&self) -> Option<&String> { self.client_secret.as_ref() } } impl ClientSecretFetch for api_models::cards_info::CardsInfoRequest { fn get_client_secret(&self) -> Option<&String> { self.client_secret.as_ref() } } impl ClientSecretFetch for payments::RetrievePaymentLinkRequest { fn get_client_secret(&self) -> Option<&String> { self.client_secret.as_ref() } } impl ClientSecretFetch for api_models::pm_auth::LinkTokenCreateRequest { fn get_client_secret(&self) -> Option<&String> { self.client_secret.as_ref() } } impl ClientSecretFetch for api_models::pm_auth::ExchangeTokenCreateRequest { fn get_client_secret(&self) -> Option<&String> { self.client_secret.as_ref() } } #[cfg(feature = "v1")] impl ClientSecretFetch for api_models::payment_methods::PaymentMethodUpdate { fn get_client_secret(&self) -> Option<&String> { self.client_secret.as_ref() } } #[cfg(feature = "v1")] impl ClientSecretFetch for api_models::subscription::ConfirmSubscriptionRequest { fn get_client_secret(&self) -> Option<&String> { self.client_secret.as_ref().map(|s| s.as_string()) } } #[cfg(feature = "v1")] impl ClientSecretFetch for api_models::subscription::GetPlansQuery { fn get_client_secret(&self) -> Option<&String> { self.client_secret.as_ref().map(|s| s.as_string()) } } #[cfg(feature = "v1")] impl ClientSecretFetch for api_models::authentication::AuthenticationEligibilityRequest { fn get_client_secret(&self) -> Option<&String> { self.client_secret .as_ref() .map(|client_secret| client_secret.peek()) } } impl ClientSecretFetch for api_models::authentication::AuthenticationAuthenticateRequest { fn get_client_secret(&self) -> Option<&String> { self.client_secret .as_ref() .map(|client_secret| client_secret.peek()) } } impl ClientSecretFetch for api_models::authentication::AuthenticationSyncRequest { fn get_client_secret(&self) -> Option<&String> { self.client_secret .as_ref() .map(|client_secret| client_secret.peek()) } } pub fn get_auth_type_and_flow<A: SessionStateInfo + Sync + Send>( headers: &HeaderMap, api_auth: ApiKeyAuth, ) -> RouterResult<( Box<dyn AuthenticateAndFetch<AuthenticationData, A>>, api::AuthFlow, )> { let api_key = get_api_key(headers)?; if api_key.starts_with("pk_") { return Ok(( Box::new(HeaderAuth(PublishableKeyAuth)), api::AuthFlow::Client, )); } Ok((Box::new(HeaderAuth(api_auth)), api::AuthFlow::Merchant)) } pub fn check_client_secret_and_get_auth<T>( headers: &HeaderMap, payload: &impl ClientSecretFetch, api_auth: ApiKeyAuth, ) -> RouterResult<( Box<dyn AuthenticateAndFetch<AuthenticationData, T>>, api::AuthFlow, )> where T: SessionStateInfo + Sync + Send, ApiKeyAuth: AuthenticateAndFetch<AuthenticationData, T>, PublishableKeyAuth: AuthenticateAndFetch<AuthenticationData, T>, { let api_key = get_api_key(headers)?; if api_key.starts_with("pk_") { payload .get_client_secret() .check_value_present("client_secret") .map_err(|_| errors::ApiErrorResponse::MissingRequiredField { field_name: "client_secret", })?; return Ok(( Box::new(HeaderAuth(PublishableKeyAuth)), api::AuthFlow::Client, )); } if payload.get_client_secret().is_some() { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "client_secret is not a valid parameter".to_owned(), } .into()); } Ok((Box::new(HeaderAuth(api_auth)), api::AuthFlow::Merchant)) } pub async fn get_ephemeral_or_other_auth<T>( headers: &HeaderMap, is_merchant_flow: bool, payload: Option<&impl ClientSecretFetch>, api_auth: ApiKeyAuth, ) -> RouterResult<( Box<dyn AuthenticateAndFetch<AuthenticationData, T>>, api::AuthFlow, bool, )> where T: SessionStateInfo + Sync + Send, ApiKeyAuth: AuthenticateAndFetch<AuthenticationData, T>, PublishableKeyAuth: AuthenticateAndFetch<AuthenticationData, T>, EphemeralKeyAuth: AuthenticateAndFetch<AuthenticationData, T>, { let api_key = get_api_key(headers)?; if api_key.starts_with("epk") { Ok((Box::new(EphemeralKeyAuth), api::AuthFlow::Client, true)) } else if is_merchant_flow { Ok(( Box::new(HeaderAuth(api_auth)), api::AuthFlow::Merchant, false, )) } else { let payload = payload.get_required_value("ClientSecretFetch")?; let (auth, auth_flow) = check_client_secret_and_get_auth(headers, payload, api_auth)?; Ok((auth, auth_flow, false)) } } #[cfg(feature = "v1")] pub fn is_ephemeral_auth<A: SessionStateInfo + Sync + Send>( headers: &HeaderMap, api_auth: ApiKeyAuth, ) -> RouterResult<Box<dyn AuthenticateAndFetch<AuthenticationData, A>>> { let api_key = get_api_key(headers)?; if !api_key.starts_with("epk") { Ok(Box::new(HeaderAuth(api_auth))) } else { Ok(Box::new(EphemeralKeyAuth)) } } pub fn is_jwt_auth(headers: &HeaderMap) -> bool { let header_map_struct = HeaderMapStruct::new(headers); match header_map_struct.get_auth_string_from_header() { Ok(auth_str) => auth_str.starts_with("Bearer"), Err(_) => get_cookie_from_header(headers) .and_then(cookies::get_jwt_from_cookies) .is_ok(), } } pub fn is_internal_api_key_merchant_id_profile_id_auth( headers: &HeaderMap, internal_api_key_auth: settings::InternalMerchantIdProfileIdAuthSettings, ) -> bool { internal_api_key_auth.enabled && headers.contains_key(headers::X_INTERNAL_API_KEY) && headers.contains_key(headers::X_MERCHANT_ID) && headers.contains_key(headers::X_PROFILE_ID) } #[cfg(feature = "v1")] pub fn check_internal_api_key_auth<T>( headers: &HeaderMap, payload: &impl ClientSecretFetch, api_auth: ApiKeyAuth, internal_api_key_auth: settings::InternalMerchantIdProfileIdAuthSettings, ) -> RouterResult<( Box<dyn AuthenticateAndFetch<AuthenticationData, T>>, api::AuthFlow, )> where T: SessionStateInfo + Sync + Send, ApiKeyAuth: AuthenticateAndFetch<AuthenticationData, T>, { if is_internal_api_key_merchant_id_profile_id_auth(headers, internal_api_key_auth) { Ok(( // HeaderAuth(api_auth) will never be called in this case as the internal auth will be checked first Box::new(InternalMerchantIdProfileIdAuth(HeaderAuth(api_auth))), api::AuthFlow::Merchant, )) } else { check_client_secret_and_get_auth(headers, payload, api_auth) } } #[cfg(feature = "v1")] pub fn check_internal_api_key_auth_no_client_secret<T>( headers: &HeaderMap, api_auth: ApiKeyAuth, internal_api_key_auth: settings::InternalMerchantIdProfileIdAuthSettings, ) -> RouterResult<( Box<dyn AuthenticateAndFetch<AuthenticationData, T>>, api::AuthFlow, )> where T: SessionStateInfo + Sync + Send, ApiKeyAuth: AuthenticateAndFetch<AuthenticationData, T>, { if is_internal_api_key_merchant_id_profile_id_auth(headers, internal_api_key_auth) { Ok(( // HeaderAuth(api_auth) will never be called in this case as the internal auth will be checked first Box::new(InternalMerchantIdProfileIdAuth(HeaderAuth(api_auth))), api::AuthFlow::Merchant, )) } else { let (auth, auth_flow) = get_auth_type_and_flow(headers, api_auth)?; Ok((auth, auth_flow)) } } pub async fn decode_jwt<T>(token: &str, state: &impl SessionStateInfo) -> RouterResult<T> where T: serde::de::DeserializeOwned, { let conf = state.conf(); let secret = conf.secrets.get_inner().jwt_secret.peek().as_bytes(); let key = DecodingKey::from_secret(secret); decode::<T>(token, &key, &Validation::new(Algorithm::HS256)) .map(|decoded| decoded.claims) .change_context(errors::ApiErrorResponse::InvalidJwtToken) } pub fn get_api_key(headers: &HeaderMap) -> RouterResult<&str> { get_header_value_by_key("api-key".into(), headers)?.get_required_value("api_key") } pub fn get_header_value_by_key(key: String, headers: &HeaderMap) -> RouterResult<Option<&str>> { headers .get(&key) .map(|source_str| { source_str .to_str() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable(format!( "Failed to convert header value to string for header key: {key}", )) }) .transpose() } pub fn get_id_type_by_key_from_headers<T: FromStr>( key: String, headers: &HeaderMap, ) -> RouterResult<Option<T>> { get_header_value_by_key(key.clone(), headers)? .map(|str_value| T::from_str(str_value)) .transpose() .map_err(|_err| { error_stack::report!(errors::ApiErrorResponse::InvalidDataFormat { field_name: key, expected_format: "Valid Id String".to_string(), }) }) } pub fn get_jwt_from_authorization_header(headers: &HeaderMap) -> RouterResult<&str> { headers .get(headers::AUTHORIZATION) .get_required_value(headers::AUTHORIZATION)? .to_str() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to convert JWT token to string")? .strip_prefix("Bearer ") .ok_or(errors::ApiErrorResponse::InvalidJwtToken.into()) } pub fn get_cookie_from_header(headers: &HeaderMap) -> RouterResult<&str> { let cookie = headers .get(cookies::get_cookie_header()) .ok_or(report!(errors::ApiErrorResponse::CookieNotFound))?; cookie .to_str() .change_context(errors::ApiErrorResponse::InvalidCookie) } pub fn strip_jwt_token(token: &str) -> RouterResult<&str> { token .strip_prefix("Bearer ") .ok_or_else(|| errors::ApiErrorResponse::InvalidJwtToken.into()) } pub fn auth_type<'a, T, A>( default_auth: &'a dyn AuthenticateAndFetch<T, A>, jwt_auth_type: &'a dyn AuthenticateAndFetch<T, A>, headers: &HeaderMap, ) -> &'a dyn AuthenticateAndFetch<T, A> where { if is_jwt_auth(headers) { return jwt_auth_type; } default_auth } #[cfg(feature = "recon")] #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationDataWithUser, A> for JWTAuth where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationDataWithUser, AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } authorization::check_tenant( payload.tenant_id.clone(), &state.session_state().tenant.tenant_id, )?; let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(self.permission, &role_info)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &payload.merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant key store for the merchant id")?; let merchant = state .store() .find_merchant_account_by_merchant_id( key_manager_state, &payload.merchant_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant account for the merchant id")?; let user_id = payload.user_id; let user = state .session_state() .global_store .find_user_by_id(&user_id) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch user for the user id")?; let auth = AuthenticationDataWithUser { merchant_account: merchant, key_store, profile_id: payload.profile_id.clone(), user, }; let auth_type = AuthenticationType::MerchantJwt { merchant_id: auth.merchant_account.get_id().clone(), user_id: Some(user_id), }; Ok((auth, auth_type)) } } async fn get_connected_merchant_account<A>( state: &A, connected_merchant_id: id_type::MerchantId, platform_org_id: id_type::OrganizationId, ) -> RouterResult<domain::MerchantAccount> where A: SessionStateInfo + Sync, { let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &connected_merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidPlatformOperation) .attach_printable("Failed to fetch merchant key store for the merchant id")?; let connected_merchant_account = state .store() .find_merchant_account_by_merchant_id(key_manager_state, &connected_merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::InvalidPlatformOperation) .attach_printable("Failed to fetch merchant account for the merchant id")?; if platform_org_id != connected_merchant_account.organization_id { return Err(errors::ApiErrorResponse::InvalidPlatformOperation) .attach_printable("Access for merchant id Unauthorized"); } Ok(connected_merchant_account) } async fn get_platform_merchant_account<A>( state: &A, request_headers: &HeaderMap, merchant_account: domain::MerchantAccount, ) -> RouterResult<(domain::MerchantAccount, Option<domain::MerchantAccount>)> where A: SessionStateInfo + Sync, { let connected_merchant_id = get_and_validate_connected_merchant_id(request_headers, &merchant_account)?; match connected_merchant_id { Some(merchant_id) => { let connected_merchant_account = get_connected_merchant_account( state, merchant_id, merchant_account.organization_id.clone(), ) .await?; Ok((connected_merchant_account, Some(merchant_account))) } None => Ok((merchant_account, None)), } } fn get_and_validate_connected_merchant_id( request_headers: &HeaderMap, merchant_account: &domain::MerchantAccount, ) -> RouterResult<Option<id_type::MerchantId>> { HeaderMapStruct::new(request_headers) .get_id_type_from_header_if_present::<id_type::MerchantId>( headers::X_CONNECTED_MERCHANT_ID, )? .map(|merchant_id| { (merchant_account.is_platform_account()) .then_some(merchant_id) .ok_or(errors::ApiErrorResponse::InvalidPlatformOperation) }) .transpose() .attach_printable("Non platform_merchant_account using X_CONNECTED_MERCHANT_ID header") } fn throw_error_if_platform_merchant_authentication_required( request_headers: &HeaderMap, ) -> RouterResult<()> { HeaderMapStruct::new(request_headers) .get_id_type_from_header_if_present::<id_type::MerchantId>( headers::X_CONNECTED_MERCHANT_ID, )? .map_or(Ok(()), |_| { Err(errors::ApiErrorResponse::PlatformAccountAuthNotSupported.into()) }) } #[cfg(feature = "recon")] #[async_trait] impl<A> AuthenticateAndFetch<UserFromTokenWithRoleInfo, A> for JWTAuth where A: SessionStateInfo + Sync, { async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(UserFromTokenWithRoleInfo, AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } authorization::check_tenant( payload.tenant_id.clone(), &state.session_state().tenant.tenant_id, )?; let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(self.permission, &role_info)?; let user = UserFromToken { user_id: payload.user_id.clone(), merchant_id: payload.merchant_id.clone(), org_id: payload.org_id, role_id: payload.role_id, profile_id: payload.profile_id, tenant_id: payload.tenant_id, }; Ok(( UserFromTokenWithRoleInfo { user, role_info }, AuthenticationType::MerchantJwt { merchant_id: payload.merchant_id, user_id: Some(payload.user_id), }, )) } } #[cfg(feature = "recon")] #[derive(serde::Serialize, serde::Deserialize)] pub struct ReconToken { pub user_id: String, pub merchant_id: id_type::MerchantId, pub role_id: String, pub exp: u64, pub org_id: id_type::OrganizationId, pub profile_id: id_type::ProfileId, pub tenant_id: Option<id_type::TenantId>, #[serde(skip_serializing_if = "Option::is_none")] pub acl: Option<String>, } #[cfg(all(feature = "olap", feature = "recon"))] impl ReconToken { pub async fn new_token( user_id: String, merchant_id: id_type::MerchantId, settings: &Settings, org_id: id_type::OrganizationId, profile_id: id_type::ProfileId, tenant_id: Option<id_type::TenantId>, role_info: authorization::roles::RoleInfo, ) -> UserResult<String> { let exp_duration = std::time::Duration::from_secs(consts::JWT_TOKEN_TIME_IN_SECS); let exp = jwt::generate_exp(exp_duration)?.as_secs(); let acl = role_info.get_recon_acl(); let optional_acl_str = serde_json::to_string(&acl) .inspect_err(|err| logger::error!("Failed to serialize acl to string: {}", err)) .change_context(errors::UserErrors::InternalServerError) .attach_printable("Failed to serialize acl to string. Using empty ACL") .ok(); let token_payload = Self { user_id, merchant_id, role_id: role_info.get_role_id().to_string(), exp, org_id, profile_id, tenant_id, acl: optional_acl_str, }; jwt::generate_jwt(&token_payload, settings).await } } #[derive(serde::Serialize, serde::Deserialize)] pub struct ExternalToken { pub user_id: String, pub merchant_id: id_type::MerchantId, pub exp: u64, pub external_service_type: ExternalServiceType, } impl ExternalToken { pub async fn new_token( user_id: String, merchant_id: id_type::MerchantId, settings: &Settings, external_service_type: ExternalServiceType, ) -> UserResult<String> { let exp_duration = std::time::Duration::from_secs(consts::JWT_TOKEN_TIME_IN_SECS); let exp = jwt::generate_exp(exp_duration)?.as_secs(); let token_payload = Self { user_id, merchant_id, exp, external_service_type, }; jwt::generate_jwt(&token_payload, settings).await } pub fn check_service_type( &self, required_service_type: &ExternalServiceType, ) -> RouterResult<()> { Ok(fp_utils::when( &self.external_service_type != required_service_type, || { Err(errors::ApiErrorResponse::AccessForbidden { resource: required_service_type.to_string(), }) }, )?) } }
crates/router/src/services/authentication.rs
router::src::services::authentication
34,755
true
// File: crates/router/src/services/email.rs // Module: router::src::services::email pub mod types;
crates/router/src/services/email.rs
router::src::services::email
25
true
// File: crates/router/src/services/api.rs // Module: router::src::services::api pub mod client; pub mod generic_link_response; pub mod request; use std::{ collections::{HashMap, HashSet}, fmt::Debug, future::Future, str, sync::Arc, time::{Duration, Instant}, }; use actix_http::header::HeaderMap; use actix_web::{ body, http::header::{HeaderName, HeaderValue}, web, FromRequest, HttpRequest, HttpResponse, Responder, ResponseError, }; pub use client::{ApiClient, MockApiClient, ProxyClient}; pub use common_enums::enums::PaymentAction; pub use common_utils::request::{ContentType, Method, Request, RequestBuilder}; use common_utils::{ consts::{DEFAULT_TENANT, TENANT_HEADER, X_HS_LATENCY}, errors::{ErrorSwitch, ReportSwitchExt}, }; use error_stack::{report, Report, ResultExt}; use hyperswitch_domain_models::router_data_v2::flow_common_types as common_types; pub use hyperswitch_domain_models::{ api::{ ApplicationResponse, GenericExpiredLinkData, GenericLinkFormData, GenericLinkStatusData, GenericLinks, PaymentLinkAction, PaymentLinkFormData, PaymentLinkStatusData, RedirectionFormData, }, payment_method_data::PaymentMethodData, router_response_types::RedirectForm, }; pub use hyperswitch_interfaces::{ api::{ BoxedConnectorIntegration, CaptureSyncMethod, ConnectorIntegration, ConnectorIntegrationAny, ConnectorRedirectResponse, ConnectorSpecifications, ConnectorValidation, }, api_client::{ call_connector_api, execute_connector_processing_step, handle_response, handle_ucs_response, store_raw_connector_response_if_required, }, connector_integration_v2::{ BoxedConnectorIntegrationV2, ConnectorIntegrationAnyV2, ConnectorIntegrationV2, }, }; use masking::{Maskable, PeekInterface}; use router_env::{instrument, tracing, tracing_actix_web::RequestId, Tag}; use serde::Serialize; use tera::{Context, Error as TeraError, Tera}; use super::{ authentication::AuthenticateAndFetch, connector_integration_interface::BoxedConnectorIntegrationInterface, }; use crate::{ configs::Settings, core::{ api_locking, errors::{self, CustomResult}, }, events::api_logs::{ApiEvent, ApiEventMetric, ApiEventsType}, headers, logger, routes::{ app::{AppStateInfo, ReqState, SessionStateInfo}, metrics, AppState, SessionState, }, services::generic_link_response::build_generic_link_html, types::api, utils, }; pub type BoxedPaymentConnectorIntegrationInterface<T, Req, Resp> = BoxedConnectorIntegrationInterface<T, common_types::PaymentFlowData, Req, Resp>; pub type BoxedRefundConnectorIntegrationInterface<T, Req, Resp> = BoxedConnectorIntegrationInterface<T, common_types::RefundFlowData, Req, Resp>; #[cfg(feature = "frm")] pub type BoxedFrmConnectorIntegrationInterface<T, Req, Resp> = BoxedConnectorIntegrationInterface<T, common_types::FrmFlowData, Req, Resp>; pub type BoxedDisputeConnectorIntegrationInterface<T, Req, Resp> = BoxedConnectorIntegrationInterface<T, common_types::DisputesFlowData, Req, Resp>; pub type BoxedMandateRevokeConnectorIntegrationInterface<T, Req, Resp> = BoxedConnectorIntegrationInterface<T, common_types::MandateRevokeFlowData, Req, Resp>; #[cfg(feature = "payouts")] pub type BoxedPayoutConnectorIntegrationInterface<T, Req, Resp> = BoxedConnectorIntegrationInterface<T, common_types::PayoutFlowData, Req, Resp>; pub type BoxedWebhookSourceVerificationConnectorIntegrationInterface<T, Req, Resp> = BoxedConnectorIntegrationInterface<T, common_types::WebhookSourceVerifyData, Req, Resp>; pub type BoxedExternalAuthenticationConnectorIntegrationInterface<T, Req, Resp> = BoxedConnectorIntegrationInterface<T, common_types::ExternalAuthenticationFlowData, Req, Resp>; pub type BoxedAuthenticationTokenConnectorIntegrationInterface<T, Req, Resp> = BoxedConnectorIntegrationInterface<T, common_types::AuthenticationTokenFlowData, Req, Resp>; pub type BoxedAccessTokenConnectorIntegrationInterface<T, Req, Resp> = BoxedConnectorIntegrationInterface<T, common_types::AccessTokenFlowData, Req, Resp>; pub type BoxedFilesConnectorIntegrationInterface<T, Req, Resp> = BoxedConnectorIntegrationInterface<T, common_types::FilesFlowData, Req, Resp>; pub type BoxedRevenueRecoveryRecordBackInterface<T, Req, Res> = BoxedConnectorIntegrationInterface<T, common_types::InvoiceRecordBackData, Req, Res>; pub type BoxedGetSubscriptionPlansInterface<T, Req, Res> = BoxedConnectorIntegrationInterface<T, common_types::GetSubscriptionPlansData, Req, Res>; pub type BoxedGetSubscriptionPlanPricesInterface<T, Req, Res> = BoxedConnectorIntegrationInterface<T, common_types::GetSubscriptionPlanPricesData, Req, Res>; pub type BoxedGetSubscriptionEstimateInterface<T, Req, Res> = BoxedConnectorIntegrationInterface<T, common_types::GetSubscriptionEstimateData, Req, Res>; pub type BoxedBillingConnectorInvoiceSyncIntegrationInterface<T, Req, Res> = BoxedConnectorIntegrationInterface< T, common_types::BillingConnectorInvoiceSyncFlowData, Req, Res, >; pub type BoxedUnifiedAuthenticationServiceInterface<T, Req, Resp> = BoxedConnectorIntegrationInterface<T, common_types::UasFlowData, Req, Resp>; pub type BoxedBillingConnectorPaymentsSyncIntegrationInterface<T, Req, Res> = BoxedConnectorIntegrationInterface< T, common_types::BillingConnectorPaymentsSyncFlowData, Req, Res, >; pub type BoxedVaultConnectorIntegrationInterface<T, Req, Res> = BoxedConnectorIntegrationInterface<T, common_types::VaultConnectorFlowData, Req, Res>; pub type BoxedGiftCardBalanceCheckIntegrationInterface<T, Req, Res> = BoxedConnectorIntegrationInterface<T, common_types::GiftCardBalanceCheckFlowData, Req, Res>; pub type BoxedSubscriptionConnectorIntegrationInterface<T, Req, Res> = BoxedConnectorIntegrationInterface<T, common_types::SubscriptionCreateData, Req, Res>; #[derive(Debug, Eq, PartialEq, Serialize)] pub struct ApplicationRedirectResponse { pub url: String, } #[derive(Clone, Copy, PartialEq, Eq)] pub enum AuthFlow { Client, Merchant, } #[allow(clippy::too_many_arguments)] #[instrument( skip(request, payload, state, func, api_auth, incoming_request_header), fields(merchant_id) )] pub async fn server_wrap_util<'a, 'b, U, T, Q, F, Fut, E, OErr>( flow: &'a impl router_env::types::FlowMetric, state: web::Data<AppState>, incoming_request_header: &HeaderMap, request: &'a HttpRequest, payload: T, func: F, api_auth: &dyn AuthenticateAndFetch<U, SessionState>, lock_action: api_locking::LockAction, ) -> CustomResult<ApplicationResponse<Q>, OErr> where F: Fn(SessionState, U, T, ReqState) -> Fut, 'b: 'a, Fut: Future<Output = CustomResult<ApplicationResponse<Q>, E>>, Q: Serialize + Debug + 'a + ApiEventMetric, T: Debug + Serialize + ApiEventMetric, E: ErrorSwitch<OErr> + error_stack::Context, OErr: ResponseError + error_stack::Context + Serialize, errors::ApiErrorResponse: ErrorSwitch<OErr>, { let request_id = RequestId::extract(request) .await .attach_printable("Unable to extract request id from request") .change_context(errors::ApiErrorResponse::InternalServerError.switch())?; let mut app_state = state.get_ref().clone(); let start_instant = Instant::now(); let serialized_request = masking::masked_serialize(&payload) .attach_printable("Failed to serialize json request") .change_context(errors::ApiErrorResponse::InternalServerError.switch())?; let mut event_type = payload.get_api_event_type(); let tenant_id = if !state.conf.multitenancy.enabled { common_utils::id_type::TenantId::try_from_string(DEFAULT_TENANT.to_owned()) .attach_printable("Unable to get default tenant id") .change_context(errors::ApiErrorResponse::InternalServerError.switch())? } else { let request_tenant_id = incoming_request_header .get(TENANT_HEADER) .and_then(|value| value.to_str().ok()) .ok_or_else(|| errors::ApiErrorResponse::MissingTenantId.switch()) .and_then(|header_value| { common_utils::id_type::TenantId::try_from_string(header_value.to_string()).map_err( |_| { errors::ApiErrorResponse::InvalidRequestData { message: format!("`{}` header is invalid", headers::X_TENANT_ID), } .switch() }, ) })?; state .conf .multitenancy .get_tenant(&request_tenant_id) .map(|tenant| tenant.tenant_id.clone()) .ok_or( errors::ApiErrorResponse::InvalidTenant { tenant_id: request_tenant_id.get_string_repr().to_string(), } .switch(), )? }; let locale = utils::get_locale_from_header(&incoming_request_header.clone()); let mut session_state = Arc::new(app_state.clone()).get_session_state(&tenant_id, Some(locale), || { errors::ApiErrorResponse::InvalidTenant { tenant_id: tenant_id.get_string_repr().to_string(), } .switch() })?; session_state.add_request_id(request_id); let mut request_state = session_state.get_req_state(); request_state.event_context.record_info(request_id); request_state .event_context .record_info(("flow".to_string(), flow.to_string())); request_state.event_context.record_info(( "tenant_id".to_string(), tenant_id.get_string_repr().to_string(), )); // Currently auth failures are not recorded as API events let (auth_out, auth_type) = api_auth .authenticate_and_fetch(request.headers(), &session_state) .await .switch()?; request_state.event_context.record_info(auth_type.clone()); let merchant_id = auth_type .get_merchant_id() .cloned() .unwrap_or(common_utils::id_type::MerchantId::get_merchant_id_not_found()); app_state.add_flow_name(flow.to_string()); tracing::Span::current().record("merchant_id", merchant_id.get_string_repr().to_owned()); let output = { lock_action .clone() .perform_locking_action(&session_state, merchant_id.to_owned()) .await .switch()?; let res = func(session_state.clone(), auth_out, payload, request_state) .await .switch(); lock_action .free_lock_action(&session_state, merchant_id.to_owned()) .await .switch()?; res }; let request_duration = Instant::now() .saturating_duration_since(start_instant) .as_millis(); let mut serialized_response = None; let mut error = None; let mut overhead_latency = None; let status_code = match output.as_ref() { Ok(res) => { if let ApplicationResponse::Json(data) = res { serialized_response.replace( masking::masked_serialize(&data) .attach_printable("Failed to serialize json response") .change_context(errors::ApiErrorResponse::InternalServerError.switch())?, ); } else if let ApplicationResponse::JsonWithHeaders((data, headers)) = res { serialized_response.replace( masking::masked_serialize(&data) .attach_printable("Failed to serialize json response") .change_context(errors::ApiErrorResponse::InternalServerError.switch())?, ); if let Some((_, value)) = headers.iter().find(|(key, _)| key == X_HS_LATENCY) { if let Ok(external_latency) = value.clone().into_inner().parse::<u128>() { overhead_latency.replace(external_latency); } } } event_type = res.get_api_event_type().or(event_type); metrics::request::track_response_status_code(res) } Err(err) => { error.replace( serde_json::to_value(err.current_context()) .attach_printable("Failed to serialize json response") .change_context(errors::ApiErrorResponse::InternalServerError.switch()) .ok() .into(), ); err.current_context().status_code().as_u16().into() } }; let infra = extract_mapped_fields( &serialized_request, state.enhancement.as_ref(), state.infra_components.as_ref(), ); let api_event = ApiEvent::new( tenant_id, Some(merchant_id.clone()), flow, &request_id, request_duration, status_code, serialized_request, serialized_response, overhead_latency, auth_type, error, event_type.unwrap_or(ApiEventsType::Miscellaneous), request, request.method(), infra.clone(), ); state.event_handler().log_event(&api_event); output } #[instrument( skip(request, state, func, api_auth, payload), fields(request_method, request_url_path, status_code) )] pub async fn server_wrap<'a, T, U, Q, F, Fut, E>( flow: impl router_env::types::FlowMetric, state: web::Data<AppState>, request: &'a HttpRequest, payload: T, func: F, api_auth: &dyn AuthenticateAndFetch<U, SessionState>, lock_action: api_locking::LockAction, ) -> HttpResponse where F: Fn(SessionState, U, T, ReqState) -> Fut, Fut: Future<Output = CustomResult<ApplicationResponse<Q>, E>>, Q: Serialize + Debug + ApiEventMetric + 'a, T: Debug + Serialize + ApiEventMetric, ApplicationResponse<Q>: Debug, E: ErrorSwitch<api_models::errors::types::ApiErrorResponse> + error_stack::Context, { let request_method = request.method().as_str(); let url_path = request.path(); let unmasked_incoming_header_keys = state.conf().unmasked_headers.keys; let incoming_request_header = request.headers(); let incoming_header_to_log: HashMap<String, HeaderValue> = incoming_request_header .iter() .fold(HashMap::new(), |mut acc, (key, value)| { let key = key.to_string(); if unmasked_incoming_header_keys.contains(&key.as_str().to_lowercase()) { acc.insert(key.clone(), value.clone()); } else { acc.insert(key.clone(), HeaderValue::from_static("**MASKED**")); } acc }); tracing::Span::current().record("request_method", request_method); tracing::Span::current().record("request_url_path", url_path); let start_instant = Instant::now(); logger::info!( tag = ?Tag::BeginRequest, payload = ?payload, headers = ?incoming_header_to_log); let server_wrap_util_res = server_wrap_util( &flow, state.clone(), incoming_request_header, request, payload, func, api_auth, lock_action, ) .await .map(|response| { logger::info!(api_response =? response); response }); let res = match server_wrap_util_res { Ok(ApplicationResponse::Json(response)) => match serde_json::to_string(&response) { Ok(res) => http_response_json(res), Err(_) => http_response_err( r#"{ "error": { "message": "Error serializing response from connector" } }"#, ), }, Ok(ApplicationResponse::StatusOk) => http_response_ok(), Ok(ApplicationResponse::TextPlain(text)) => http_response_plaintext(text), Ok(ApplicationResponse::FileData((file_data, content_type))) => { http_response_file_data(file_data, content_type) } Ok(ApplicationResponse::JsonForRedirection(response)) => { match serde_json::to_string(&response) { Ok(res) => http_redirect_response(res, response), Err(_) => http_response_err( r#"{ "error": { "message": "Error serializing response from connector" } }"#, ), } } Ok(ApplicationResponse::Form(redirection_data)) => { let config = state.conf(); build_redirection_form( &redirection_data.redirect_form, redirection_data.payment_method_data, redirection_data.amount, redirection_data.currency, config, ) .respond_to(request) .map_into_boxed_body() } Ok(ApplicationResponse::GenericLinkForm(boxed_generic_link_data)) => { let link_type = boxed_generic_link_data.data.to_string(); match build_generic_link_html( boxed_generic_link_data.data, boxed_generic_link_data.locale, ) { Ok(rendered_html) => { let headers = if !boxed_generic_link_data.allowed_domains.is_empty() { let domains_str = boxed_generic_link_data .allowed_domains .into_iter() .collect::<Vec<String>>() .join(" "); let csp_header = format!("frame-ancestors 'self' {domains_str};"); Some(HashSet::from([("content-security-policy", csp_header)])) } else { None }; http_response_html_data(rendered_html, headers) } Err(_) => http_response_err(format!("Error while rendering {link_type} HTML page")), } } Ok(ApplicationResponse::PaymentLinkForm(boxed_payment_link_data)) => { match *boxed_payment_link_data { PaymentLinkAction::PaymentLinkFormData(payment_link_data) => { match build_payment_link_html(payment_link_data) { Ok(rendered_html) => http_response_html_data(rendered_html, None), Err(_) => http_response_err( r#"{ "error": { "message": "Error while rendering payment link html page" } }"#, ), } } PaymentLinkAction::PaymentLinkStatus(payment_link_data) => { match get_payment_link_status(payment_link_data) { Ok(rendered_html) => http_response_html_data(rendered_html, None), Err(_) => http_response_err( r#"{ "error": { "message": "Error while rendering payment link status page" } }"#, ), } } } } Ok(ApplicationResponse::JsonWithHeaders((response, headers))) => { let request_elapsed_time = request.headers().get(X_HS_LATENCY).and_then(|value| { if value == "true" { Some(start_instant.elapsed()) } else { None } }); let proxy_connector_http_status_code = if state .conf .proxy_status_mapping .proxy_connector_http_status_code { headers .iter() .find(|(key, _)| key == headers::X_CONNECTOR_HTTP_STATUS_CODE) .and_then(|(_, value)| { match value.clone().into_inner().parse::<u16>() { Ok(code) => match http::StatusCode::from_u16(code) { Ok(status_code) => Some(status_code), Err(err) => { logger::error!( "Invalid HTTP status code parsed from connector_http_status_code: {:?}", err ); None } }, Err(err) => { logger::error!( "Failed to parse connector_http_status_code from header: {:?}", err ); None } } }) } else { None }; match serde_json::to_string(&response) { Ok(res) => http_response_json_with_headers( res, headers, request_elapsed_time, proxy_connector_http_status_code, ), Err(_) => http_response_err( r#"{ "error": { "message": "Error serializing response from connector" } }"#, ), } } Err(error) => log_and_return_error_response(error), }; let response_code = res.status().as_u16(); tracing::Span::current().record("status_code", response_code); let end_instant = Instant::now(); let request_duration = end_instant.saturating_duration_since(start_instant); logger::info!( tag = ?Tag::EndRequest, time_taken_ms = request_duration.as_millis(), ); res } pub fn log_and_return_error_response<T>(error: Report<T>) -> HttpResponse where T: error_stack::Context + Clone + ResponseError, Report<T>: EmbedError, { logger::error!(?error); HttpResponse::from_error(error.embed().current_context().clone()) } pub trait EmbedError: Sized { fn embed(self) -> Self { self } } impl EmbedError for Report<api_models::errors::types::ApiErrorResponse> { fn embed(self) -> Self { #[cfg(feature = "detailed_errors")] { let mut report = self; let error_trace = serde_json::to_value(&report).ok().and_then(|inner| { serde_json::from_value::<Vec<errors::NestedErrorStack<'_>>>(inner) .ok() .map(Into::<errors::VecLinearErrorStack<'_>>::into) .map(serde_json::to_value) .transpose() .ok() .flatten() }); match report.downcast_mut::<api_models::errors::types::ApiErrorResponse>() { None => {} Some(inner) => { inner.get_internal_error_mut().stacktrace = error_trace; } } report } #[cfg(not(feature = "detailed_errors"))] self } } impl EmbedError for Report<hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse> { } pub fn http_response_json<T: body::MessageBody + 'static>(response: T) -> HttpResponse { HttpResponse::Ok() .content_type(mime::APPLICATION_JSON) .body(response) } pub fn http_server_error_json_response<T: body::MessageBody + 'static>( response: T, ) -> HttpResponse { HttpResponse::InternalServerError() .content_type(mime::APPLICATION_JSON) .body(response) } pub fn http_response_json_with_headers<T: body::MessageBody + 'static>( response: T, headers: Vec<(String, Maskable<String>)>, request_duration: Option<Duration>, status_code: Option<http::StatusCode>, ) -> HttpResponse { let mut response_builder = HttpResponse::build(status_code.unwrap_or(http::StatusCode::OK)); for (header_name, header_value) in headers { let is_sensitive_header = header_value.is_masked(); let mut header_value = header_value.into_inner(); if header_name == X_HS_LATENCY { if let Some(request_duration) = request_duration { if let Ok(external_latency) = header_value.parse::<u128>() { let updated_duration = request_duration.as_millis() - external_latency; header_value = updated_duration.to_string(); } } } let mut header_value = match HeaderValue::from_str(header_value.as_str()) { Ok(header_value) => header_value, Err(error) => { logger::error!(?error); return http_server_error_json_response("Something Went Wrong"); } }; if is_sensitive_header { header_value.set_sensitive(true); } response_builder.append_header((header_name, header_value)); } response_builder .content_type(mime::APPLICATION_JSON) .body(response) } pub fn http_response_plaintext<T: body::MessageBody + 'static>(res: T) -> HttpResponse { HttpResponse::Ok().content_type(mime::TEXT_PLAIN).body(res) } pub fn http_response_file_data<T: body::MessageBody + 'static>( res: T, content_type: mime::Mime, ) -> HttpResponse { HttpResponse::Ok().content_type(content_type).body(res) } pub fn http_response_html_data<T: body::MessageBody + 'static>( res: T, optional_headers: Option<HashSet<(&'static str, String)>>, ) -> HttpResponse { let mut res_builder = HttpResponse::Ok(); res_builder.content_type(mime::TEXT_HTML); if let Some(headers) = optional_headers { for (key, value) in headers { if let Ok(header_val) = HeaderValue::try_from(value) { res_builder.insert_header((HeaderName::from_static(key), header_val)); } } } res_builder.body(res) } pub fn http_response_ok() -> HttpResponse { HttpResponse::Ok().finish() } pub fn http_redirect_response<T: body::MessageBody + 'static>( response: T, redirection_response: api::RedirectionResponse, ) -> HttpResponse { HttpResponse::Ok() .content_type(mime::APPLICATION_JSON) .append_header(( "Location", redirection_response.return_url_with_query_params, )) .status(http::StatusCode::FOUND) .body(response) } pub fn http_response_err<T: body::MessageBody + 'static>(response: T) -> HttpResponse { HttpResponse::BadRequest() .content_type(mime::APPLICATION_JSON) .body(response) } pub trait Authenticate { fn get_client_secret(&self) -> Option<&String> { None } fn should_return_raw_response(&self) -> Option<bool> { None } } #[cfg(feature = "v2")] impl Authenticate for api_models::payments::PaymentsConfirmIntentRequest { fn should_return_raw_response(&self) -> Option<bool> { self.return_raw_connector_response } } #[cfg(feature = "v2")] impl Authenticate for api_models::payments::ProxyPaymentsRequest {} #[cfg(feature = "v2")] impl Authenticate for api_models::payments::ExternalVaultProxyPaymentsRequest {} #[cfg(feature = "v1")] impl Authenticate for api_models::payments::PaymentsRequest { fn get_client_secret(&self) -> Option<&String> { self.client_secret.as_ref() } fn should_return_raw_response(&self) -> Option<bool> { // In v1, this maps to `all_keys_required` to retain backward compatibility. // The equivalent field in v2 is `return_raw_connector_response`. self.all_keys_required } } #[cfg(feature = "v1")] impl Authenticate for api_models::payment_methods::PaymentMethodListRequest { fn get_client_secret(&self) -> Option<&String> { self.client_secret.as_ref() } } #[cfg(feature = "v1")] impl Authenticate for api_models::payments::PaymentsSessionRequest { fn get_client_secret(&self) -> Option<&String> { Some(&self.client_secret) } } impl Authenticate for api_models::payments::PaymentsDynamicTaxCalculationRequest { fn get_client_secret(&self) -> Option<&String> { Some(self.client_secret.peek()) } } impl Authenticate for api_models::payments::PaymentsPostSessionTokensRequest { fn get_client_secret(&self) -> Option<&String> { Some(self.client_secret.peek()) } } impl Authenticate for api_models::payments::PaymentsUpdateMetadataRequest {} impl Authenticate for api_models::payments::PaymentsRetrieveRequest { #[cfg(feature = "v2")] fn should_return_raw_response(&self) -> Option<bool> { self.return_raw_connector_response } #[cfg(feature = "v1")] fn should_return_raw_response(&self) -> Option<bool> { // In v1, this maps to `all_keys_required` to retain backward compatibility. // The equivalent field in v2 is `return_raw_connector_response`. self.all_keys_required } } impl Authenticate for api_models::payments::PaymentsCancelRequest {} impl Authenticate for api_models::payments::PaymentsCancelPostCaptureRequest {} impl Authenticate for api_models::payments::PaymentsCaptureRequest {} impl Authenticate for api_models::payments::PaymentsIncrementalAuthorizationRequest {} impl Authenticate for api_models::payments::PaymentsExtendAuthorizationRequest {} impl Authenticate for api_models::payments::PaymentsStartRequest {} // impl Authenticate for api_models::payments::PaymentsApproveRequest {} impl Authenticate for api_models::payments::PaymentsRejectRequest {} // #[cfg(feature = "v2")] // impl Authenticate for api_models::payments::PaymentsIntentResponse {} pub fn build_redirection_form( form: &RedirectForm, payment_method_data: Option<PaymentMethodData>, amount: String, currency: String, config: Settings, ) -> maud::Markup { use maud::PreEscaped; let logging_template = include_str!("redirection/assets/redirect_error_logs_push.js").to_string(); match form { RedirectForm::Form { endpoint, method, form_fields, } => maud::html! { (maud::DOCTYPE) html { meta name="viewport" content="width=device-width, initial-scale=1"; head { style { r##" "## } (PreEscaped(r##" <style> #loader1 { width: 500px, } @media (max-width: 600px) { #loader1 { width: 200px } } </style> "##)) } body style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" { div id="loader1" class="lottie" style="height: 150px; display: block; position: relative; margin-left: auto; margin-right: auto;" { "" } (PreEscaped(r#"<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.7.4/lottie.min.js"></script>"#)) (PreEscaped(r#" <script> var anime = bodymovin.loadAnimation({ container: document.getElementById('loader1'), renderer: 'svg', loop: true, autoplay: true, name: 'hyperswitch loader', animationData: {"v":"4.8.0","meta":{"g":"LottieFiles AE 3.1.1","a":"","k":"","d":"","tc":""},"fr":29.9700012207031,"ip":0,"op":31.0000012626559,"w":400,"h":250,"nm":"loader_shape","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":1,"ty":4,"nm":"circle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[278.25,202.671,0],"ix":2},"a":{"a":0,"k":[23.72,23.72,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[12.935,0],[0,-12.936],[-12.935,0],[0,12.935]],"o":[[-12.952,0],[0,12.935],[12.935,0],[0,-12.936]],"v":[[0,-23.471],[-23.47,0.001],[0,23.471],[23.47,0.001]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":10,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":19.99,"s":[100]},{"t":29.9800012211104,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[23.72,23.721],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"square 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[196.25,201.271,0],"ix":2},"a":{"a":0,"k":[22.028,22.03,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[1.914,0],[0,0],[0,-1.914],[0,0],[-1.914,0],[0,0],[0,1.914],[0,0]],"o":[[0,0],[-1.914,0],[0,0],[0,1.914],[0,0],[1.914,0],[0,0],[0,-1.914]],"v":[[18.313,-21.779],[-18.312,-21.779],[-21.779,-18.313],[-21.779,18.314],[-18.312,21.779],[18.313,21.779],[21.779,18.314],[21.779,-18.313]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":5,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":14.99,"s":[100]},{"t":24.9800010174563,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[22.028,22.029],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":47.0000019143492,"st":0,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"Triangle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[116.25,200.703,0],"ix":2},"a":{"a":0,"k":[27.11,21.243,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0.558,-0.879],[0,0],[-1.133,0],[0,0],[0.609,0.947],[0,0]],"o":[[-0.558,-0.879],[0,0],[-0.609,0.947],[0,0],[1.133,0],[0,0],[0,0]],"v":[[1.209,-20.114],[-1.192,-20.114],[-26.251,18.795],[-25.051,20.993],[25.051,20.993],[26.251,18.795],[1.192,-20.114]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":9.99,"s":[100]},{"t":19.9800008138021,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[27.11,21.243],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0}],"markers":[]} }) </script> "#)) h3 style="text-align: center;" { "Please wait while we process your payment..." } form action=(PreEscaped(endpoint)) method=(method.to_string()) #payment_form { @for (field, value) in form_fields { input type="hidden" name=(field) value=(value); } } (PreEscaped(format!(r#" <script type="text/javascript"> {logging_template} var frm = document.getElementById("payment_form"); var formFields = frm.querySelectorAll("input"); if (frm.method.toUpperCase() === "GET" && formFields.length === 0) {{ window.setTimeout(function () {{ window.location.href = frm.action; }}, 300); }} else {{ window.setTimeout(function () {{ frm.submit(); }}, 300); }} </script> "#))) } } }, RedirectForm::Html { html_data } => { PreEscaped(format!("{html_data} <script>{logging_template}</script>")) } RedirectForm::BarclaycardAuthSetup { access_token, ddc_url, reference_id, } => { maud::html! { (maud::DOCTYPE) html { head { meta name="viewport" content="width=device-width, initial-scale=1"; } body style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" { div id="loader1" class="lottie" style="height: 150px; display: block; position: relative; margin-top: 150px; margin-left: auto; margin-right: auto;" { "" } (PreEscaped(r#"<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.7.4/lottie.min.js"></script>"#)) (PreEscaped(r#" <script> var anime = bodymovin.loadAnimation({ container: document.getElementById('loader1'), renderer: 'svg', loop: true, autoplay: true, name: 'hyperswitch loader', animationData: {"v":"4.8.0","meta":{"g":"LottieFiles AE 3.1.1","a":"","k":"","d":"","tc":""},"fr":29.9700012207031,"ip":0,"op":31.0000012626559,"w":400,"h":250,"nm":"loader_shape","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":1,"ty":4,"nm":"circle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[278.25,202.671,0],"ix":2},"a":{"a":0,"k":[23.72,23.72,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[12.935,0],[0,-12.936],[-12.935,0],[0,12.935]],"o":[[-12.952,0],[0,12.935],[12.935,0],[0,-12.936]],"v":[[0,-23.471],[-23.47,0.001],[0,23.471],[23.47,0.001]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":10,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":19.99,"s":[100]},{"t":29.9800012211104,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[23.72,23.721],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"square 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[196.25,201.271,0],"ix":2},"a":{"a":0,"k":[22.028,22.03,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[1.914,0],[0,0],[0,-1.914],[0,0],[-1.914,0],[0,0],[0,1.914],[0,0]],"o":[[0,0],[-1.914,0],[0,0],[0,1.914],[0,0],[1.914,0],[0,0],[0,-1.914]],"v":[[18.313,-21.779],[-18.312,-21.779],[-21.779,-18.313],[-21.779,18.314],[-18.312,21.779],[18.313,21.779],[21.779,18.314],[21.779,-18.313]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":5,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":14.99,"s":[100]},{"t":24.9800010174563,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[22.028,22.029],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":47.0000019143492,"st":0,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"Triangle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[116.25,200.703,0],"ix":2},"a":{"a":0,"k":[27.11,21.243,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0.558,-0.879],[0,0],[-1.133,0],[0,0],[0.609,0.947],[0,0]],"o":[[-0.558,-0.879],[0,0],[-0.609,0.947],[0,0],[1.133,0],[0,0],[0,0]],"v":[[1.209,-20.114],[-1.192,-20.114],[-26.251,18.795],[-25.051,20.993],[25.051,20.993],[26.251,18.795],[1.192,-20.114]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":9.99,"s":[100]},{"t":19.9800008138021,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[27.11,21.243],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0}],"markers":[]} }) </script> "#)) h3 style="text-align: center;" { "Please wait while we process your payment..." } } (PreEscaped(r#"<iframe id="cardinal_collection_iframe" name="collectionIframe" height="10" width="10" style="display: none;"></iframe>"#)) (PreEscaped(format!("<form id=\"cardinal_collection_form\" method=\"POST\" target=\"collectionIframe\" action=\"{ddc_url}\"> <input id=\"cardinal_collection_form_input\" type=\"hidden\" name=\"JWT\" value=\"{access_token}\"> </form>"))) (PreEscaped(r#"<script> window.onload = function() { var cardinalCollectionForm = document.querySelector('#cardinal_collection_form'); if(cardinalCollectionForm) cardinalCollectionForm.submit(); } </script>"#)) (PreEscaped(format!("<script> {logging_template} window.addEventListener(\"message\", function(event) {{ if (event.origin === \"https://centinelapistag.cardinalcommerce.com\" || event.origin === \"https://centinelapi.cardinalcommerce.com\") {{ window.location.href = window.location.pathname.replace(/payments\\/redirect\\/(\\w+)\\/(\\w+)\\/\\w+/, \"payments/$1/$2/redirect/complete/cybersource?referenceId={reference_id}\"); }} }}, false); </script> "))) }} } RedirectForm::BarclaycardConsumerAuth { access_token, step_up_url, } => { maud::html! { (maud::DOCTYPE) html { head { meta name="viewport" content="width=device-width, initial-scale=1"; } body style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" { div id="loader1" class="lottie" style="height: 150px; display: block; position: relative; margin-top: 150px; margin-left: auto; margin-right: auto;" { "" } (PreEscaped(r#"<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.7.4/lottie.min.js"></script>"#)) (PreEscaped(r#" <script> var anime = bodymovin.loadAnimation({ container: document.getElementById('loader1'), renderer: 'svg', loop: true, autoplay: true, name: 'hyperswitch loader', animationData: {"v":"4.8.0","meta":{"g":"LottieFiles AE 3.1.1","a":"","k":"","d":"","tc":""},"fr":29.9700012207031,"ip":0,"op":31.0000012626559,"w":400,"h":250,"nm":"loader_shape","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":1,"ty":4,"nm":"circle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[278.25,202.671,0],"ix":2},"a":{"a":0,"k":[23.72,23.72,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[12.935,0],[0,-12.936],[-12.935,0],[0,12.935]],"o":[[-12.952,0],[0,12.935],[12.935,0],[0,-12.936]],"v":[[0,-23.471],[-23.47,0.001],[0,23.471],[23.47,0.001]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":10,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":19.99,"s":[100]},{"t":29.9800012211104,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[23.72,23.721],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"square 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[196.25,201.271,0],"ix":2},"a":{"a":0,"k":[22.028,22.03,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[1.914,0],[0,0],[0,-1.914],[0,0],[-1.914,0],[0,0],[0,1.914],[0,0]],"o":[[0,0],[-1.914,0],[0,0],[0,1.914],[0,0],[1.914,0],[0,0],[0,-1.914]],"v":[[18.313,-21.779],[-18.312,-21.779],[-21.779,-18.313],[-21.779,18.314],[-18.312,21.779],[18.313,21.779],[21.779,18.314],[21.779,-18.313]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":5,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":14.99,"s":[100]},{"t":24.9800010174563,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[22.028,22.029],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":47.0000019143492,"st":0,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"Triangle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[116.25,200.703,0],"ix":2},"a":{"a":0,"k":[27.11,21.243,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0.558,-0.879],[0,0],[-1.133,0],[0,0],[0.609,0.947],[0,0]],"o":[[-0.558,-0.879],[0,0],[-0.609,0.947],[0,0],[1.133,0],[0,0],[0,0]],"v":[[1.209,-20.114],[-1.192,-20.114],[-26.251,18.795],[-25.051,20.993],[25.051,20.993],[26.251,18.795],[1.192,-20.114]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":9.99,"s":[100]},{"t":19.9800008138021,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[27.11,21.243],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0}],"markers":[]} }) </script> "#)) h3 style="text-align: center;" { "Please wait while we process your payment..." } } // This is the iframe recommended by cybersource but the redirection happens inside this iframe once otp // is received and we lose control of the redirection on user client browser, so to avoid that we have removed this iframe and directly consumed it. // (PreEscaped(r#"<iframe id="step_up_iframe" style="border: none; margin-left: auto; margin-right: auto; display: block" height="800px" width="400px" name="stepUpIframe"></iframe>"#)) (PreEscaped(format!("<form id=\"step-up-form\" method=\"POST\" action=\"{step_up_url}\"> <input type=\"hidden\" name=\"JWT\" value=\"{access_token}\"> </form>"))) (PreEscaped(format!("<script> {logging_template} window.onload = function() {{ var stepUpForm = document.querySelector('#step-up-form'); if(stepUpForm) stepUpForm.submit(); }} </script>"))) }} } RedirectForm::BlueSnap { payment_fields_token, } => { let card_details = if let Some(PaymentMethodData::Card(ccard)) = payment_method_data { format!( "var saveCardDirectly={{cvv: \"{}\",amount: {},currency: \"{}\"}};", ccard.card_cvc.peek(), amount, currency ) } else { "".to_string() }; let bluesnap_sdk_url = config.connectors.bluesnap.secondary_base_url; maud::html! { (maud::DOCTYPE) html { head { meta name="viewport" content="width=device-width, initial-scale=1"; (PreEscaped(format!("<script src=\"{bluesnap_sdk_url}web-sdk/5/bluesnap.js\"></script>"))) } body style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" { div id="loader1" class="lottie" style="height: 150px; display: block; position: relative; margin-top: 150px; margin-left: auto; margin-right: auto;" { "" } (PreEscaped(r#"<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.7.4/lottie.min.js"></script>"#)) (PreEscaped(r#" <script> var anime = bodymovin.loadAnimation({ container: document.getElementById('loader1'), renderer: 'svg', loop: true, autoplay: true, name: 'hyperswitch loader', animationData: {"v":"4.8.0","meta":{"g":"LottieFiles AE 3.1.1","a":"","k":"","d":"","tc":""},"fr":29.9700012207031,"ip":0,"op":31.0000012626559,"w":400,"h":250,"nm":"loader_shape","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":1,"ty":4,"nm":"circle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[278.25,202.671,0],"ix":2},"a":{"a":0,"k":[23.72,23.72,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[12.935,0],[0,-12.936],[-12.935,0],[0,12.935]],"o":[[-12.952,0],[0,12.935],[12.935,0],[0,-12.936]],"v":[[0,-23.471],[-23.47,0.001],[0,23.471],[23.47,0.001]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":10,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":19.99,"s":[100]},{"t":29.9800012211104,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[23.72,23.721],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"square 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[196.25,201.271,0],"ix":2},"a":{"a":0,"k":[22.028,22.03,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[1.914,0],[0,0],[0,-1.914],[0,0],[-1.914,0],[0,0],[0,1.914],[0,0]],"o":[[0,0],[-1.914,0],[0,0],[0,1.914],[0,0],[1.914,0],[0,0],[0,-1.914]],"v":[[18.313,-21.779],[-18.312,-21.779],[-21.779,-18.313],[-21.779,18.314],[-18.312,21.779],[18.313,21.779],[21.779,18.314],[21.779,-18.313]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":5,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":14.99,"s":[100]},{"t":24.9800010174563,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[22.028,22.029],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":47.0000019143492,"st":0,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"Triangle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[116.25,200.703,0],"ix":2},"a":{"a":0,"k":[27.11,21.243,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0.558,-0.879],[0,0],[-1.133,0],[0,0],[0.609,0.947],[0,0]],"o":[[-0.558,-0.879],[0,0],[-0.609,0.947],[0,0],[1.133,0],[0,0],[0,0]],"v":[[1.209,-20.114],[-1.192,-20.114],[-26.251,18.795],[-25.051,20.993],[25.051,20.993],[26.251,18.795],[1.192,-20.114]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":9.99,"s":[100]},{"t":19.9800008138021,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[27.11,21.243],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0}],"markers":[]} }) </script> "#)) h3 style="text-align: center;" { "Please wait while we process your payment..." } } (PreEscaped(format!("<script> {logging_template} bluesnap.threeDsPaymentsSetup(\"{payment_fields_token}\", function(sdkResponse) {{ // console.log(sdkResponse); var f = document.createElement('form'); f.action=window.location.pathname.replace(/payments\\/redirect\\/(\\w+)\\/(\\w+)\\/\\w+/, \"payments/$1/$2/redirect/complete/bluesnap?paymentToken={payment_fields_token}\"); f.method='POST'; var i=document.createElement('input'); i.type='hidden'; i.name='authentication_response'; i.value=JSON.stringify(sdkResponse); f.appendChild(i); document.body.appendChild(f); f.submit(); }}); {card_details} bluesnap.threeDsPaymentsSubmitData(saveCardDirectly); </script> "))) }} } RedirectForm::CybersourceAuthSetup { access_token, ddc_url, reference_id, } => { maud::html! { (maud::DOCTYPE) html { head { meta name="viewport" content="width=device-width, initial-scale=1"; } body style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" { div id="loader1" class="lottie" style="height: 150px; display: block; position: relative; margin-top: 150px; margin-left: auto; margin-right: auto;" { "" } (PreEscaped(r#"<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.7.4/lottie.min.js"></script>"#)) (PreEscaped(r#" <script> var anime = bodymovin.loadAnimation({ container: document.getElementById('loader1'), renderer: 'svg', loop: true, autoplay: true, name: 'hyperswitch loader', animationData: {"v":"4.8.0","meta":{"g":"LottieFiles AE 3.1.1","a":"","k":"","d":"","tc":""},"fr":29.9700012207031,"ip":0,"op":31.0000012626559,"w":400,"h":250,"nm":"loader_shape","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":1,"ty":4,"nm":"circle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[278.25,202.671,0],"ix":2},"a":{"a":0,"k":[23.72,23.72,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[12.935,0],[0,-12.936],[-12.935,0],[0,12.935]],"o":[[-12.952,0],[0,12.935],[12.935,0],[0,-12.936]],"v":[[0,-23.471],[-23.47,0.001],[0,23.471],[23.47,0.001]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":10,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":19.99,"s":[100]},{"t":29.9800012211104,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[23.72,23.721],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"square 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[196.25,201.271,0],"ix":2},"a":{"a":0,"k":[22.028,22.03,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[1.914,0],[0,0],[0,-1.914],[0,0],[-1.914,0],[0,0],[0,1.914],[0,0]],"o":[[0,0],[-1.914,0],[0,0],[0,1.914],[0,0],[1.914,0],[0,0],[0,-1.914]],"v":[[18.313,-21.779],[-18.312,-21.779],[-21.779,-18.313],[-21.779,18.314],[-18.312,21.779],[18.313,21.779],[21.779,18.314],[21.779,-18.313]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":5,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":14.99,"s":[100]},{"t":24.9800010174563,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[22.028,22.029],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":47.0000019143492,"st":0,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"Triangle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[116.25,200.703,0],"ix":2},"a":{"a":0,"k":[27.11,21.243,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0.558,-0.879],[0,0],[-1.133,0],[0,0],[0.609,0.947],[0,0]],"o":[[-0.558,-0.879],[0,0],[-0.609,0.947],[0,0],[1.133,0],[0,0],[0,0]],"v":[[1.209,-20.114],[-1.192,-20.114],[-26.251,18.795],[-25.051,20.993],[25.051,20.993],[26.251,18.795],[1.192,-20.114]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":9.99,"s":[100]},{"t":19.9800008138021,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[27.11,21.243],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0}],"markers":[]} }) </script> "#)) h3 style="text-align: center;" { "Please wait while we process your payment..." } } (PreEscaped(r#"<iframe id="cardinal_collection_iframe" name="collectionIframe" height="10" width="10" style="display: none;"></iframe>"#)) (PreEscaped(format!("<form id=\"cardinal_collection_form\" method=\"POST\" target=\"collectionIframe\" action=\"{ddc_url}\"> <input id=\"cardinal_collection_form_input\" type=\"hidden\" name=\"JWT\" value=\"{access_token}\"> </form>"))) (PreEscaped(r#"<script> window.onload = function() { var cardinalCollectionForm = document.querySelector('#cardinal_collection_form'); if(cardinalCollectionForm) cardinalCollectionForm.submit(); } </script>"#)) (PreEscaped(format!("<script> {logging_template} window.addEventListener(\"message\", function(event) {{ if (event.origin === \"https://centinelapistag.cardinalcommerce.com\" || event.origin === \"https://centinelapi.cardinalcommerce.com\") {{ window.location.href = window.location.pathname.replace(/payments\\/redirect\\/(\\w+)\\/(\\w+)\\/\\w+/, \"payments/$1/$2/redirect/complete/cybersource?referenceId={reference_id}\"); }} }}, false); </script> "))) }} } RedirectForm::CybersourceConsumerAuth { access_token, step_up_url, } => { maud::html! { (maud::DOCTYPE) html { head { meta name="viewport" content="width=device-width, initial-scale=1"; } body style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" { div id="loader1" class="lottie" style="height: 150px; display: block; position: relative; margin-top: 150px; margin-left: auto; margin-right: auto;" { "" } (PreEscaped(r#"<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.7.4/lottie.min.js"></script>"#)) (PreEscaped(r#" <script> var anime = bodymovin.loadAnimation({ container: document.getElementById('loader1'), renderer: 'svg', loop: true, autoplay: true, name: 'hyperswitch loader', animationData: {"v":"4.8.0","meta":{"g":"LottieFiles AE 3.1.1","a":"","k":"","d":"","tc":""},"fr":29.9700012207031,"ip":0,"op":31.0000012626559,"w":400,"h":250,"nm":"loader_shape","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":1,"ty":4,"nm":"circle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[278.25,202.671,0],"ix":2},"a":{"a":0,"k":[23.72,23.72,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[12.935,0],[0,-12.936],[-12.935,0],[0,12.935]],"o":[[-12.952,0],[0,12.935],[12.935,0],[0,-12.936]],"v":[[0,-23.471],[-23.47,0.001],[0,23.471],[23.47,0.001]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":10,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":19.99,"s":[100]},{"t":29.9800012211104,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[23.72,23.721],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"square 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[196.25,201.271,0],"ix":2},"a":{"a":0,"k":[22.028,22.03,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[1.914,0],[0,0],[0,-1.914],[0,0],[-1.914,0],[0,0],[0,1.914],[0,0]],"o":[[0,0],[-1.914,0],[0,0],[0,1.914],[0,0],[1.914,0],[0,0],[0,-1.914]],"v":[[18.313,-21.779],[-18.312,-21.779],[-21.779,-18.313],[-21.779,18.314],[-18.312,21.779],[18.313,21.779],[21.779,18.314],[21.779,-18.313]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":5,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":14.99,"s":[100]},{"t":24.9800010174563,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[22.028,22.029],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":47.0000019143492,"st":0,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"Triangle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[116.25,200.703,0],"ix":2},"a":{"a":0,"k":[27.11,21.243,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0.558,-0.879],[0,0],[-1.133,0],[0,0],[0.609,0.947],[0,0]],"o":[[-0.558,-0.879],[0,0],[-0.609,0.947],[0,0],[1.133,0],[0,0],[0,0]],"v":[[1.209,-20.114],[-1.192,-20.114],[-26.251,18.795],[-25.051,20.993],[25.051,20.993],[26.251,18.795],[1.192,-20.114]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":9.99,"s":[100]},{"t":19.9800008138021,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[27.11,21.243],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0}],"markers":[]} }) </script> "#)) h3 style="text-align: center;" { "Please wait while we process your payment..." } } // This is the iframe recommended by cybersource but the redirection happens inside this iframe once otp // is received and we lose control of the redirection on user client browser, so to avoid that we have removed this iframe and directly consumed it. // (PreEscaped(r#"<iframe id="step_up_iframe" style="border: none; margin-left: auto; margin-right: auto; display: block" height="800px" width="400px" name="stepUpIframe"></iframe>"#)) (PreEscaped(format!("<form id=\"step-up-form\" method=\"POST\" action=\"{step_up_url}\"> <input type=\"hidden\" name=\"JWT\" value=\"{access_token}\"> </form>"))) (PreEscaped(format!("<script> {logging_template} window.onload = function() {{ var stepUpForm = document.querySelector('#step-up-form'); if(stepUpForm) stepUpForm.submit(); }} </script>"))) }} } RedirectForm::DeutschebankThreeDSChallengeFlow { acs_url, creq } => { maud::html! { (maud::DOCTYPE) html { head { meta name="viewport" content="width=device-width, initial-scale=1"; } body style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" { div id="loader1" class="lottie" style="height: 150px; display: block; position: relative; margin-top: 150px; margin-left: auto; margin-right: auto;" { "" } (PreEscaped(r#"<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.7.4/lottie.min.js"></script>"#)) (PreEscaped(r#" <script> var anime = bodymovin.loadAnimation({ container: document.getElementById('loader1'), renderer: 'svg', loop: true, autoplay: true, name: 'hyperswitch loader', animationData: {"v":"4.8.0","meta":{"g":"LottieFiles AE 3.1.1","a":"","k":"","d":"","tc":""},"fr":29.9700012207031,"ip":0,"op":31.0000012626559,"w":400,"h":250,"nm":"loader_shape","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":1,"ty":4,"nm":"circle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[278.25,202.671,0],"ix":2},"a":{"a":0,"k":[23.72,23.72,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[12.935,0],[0,-12.936],[-12.935,0],[0,12.935]],"o":[[-12.952,0],[0,12.935],[12.935,0],[0,-12.936]],"v":[[0,-23.471],[-23.47,0.001],[0,23.471],[23.47,0.001]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":10,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":19.99,"s":[100]},{"t":29.9800012211104,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[23.72,23.721],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"square 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[196.25,201.271,0],"ix":2},"a":{"a":0,"k":[22.028,22.03,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[1.914,0],[0,0],[0,-1.914],[0,0],[-1.914,0],[0,0],[0,1.914],[0,0]],"o":[[0,0],[-1.914,0],[0,0],[0,1.914],[0,0],[1.914,0],[0,0],[0,-1.914]],"v":[[18.313,-21.779],[-18.312,-21.779],[-21.779,-18.313],[-21.779,18.314],[-18.312,21.779],[18.313,21.779],[21.779,18.314],[21.779,-18.313]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":5,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":14.99,"s":[100]},{"t":24.9800010174563,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[22.028,22.029],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":47.0000019143492,"st":0,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"Triangle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[116.25,200.703,0],"ix":2},"a":{"a":0,"k":[27.11,21.243,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0.558,-0.879],[0,0],[-1.133,0],[0,0],[0.609,0.947],[0,0]],"o":[[-0.558,-0.879],[0,0],[-0.609,0.947],[0,0],[1.133,0],[0,0],[0,0]],"v":[[1.209,-20.114],[-1.192,-20.114],[-26.251,18.795],[-25.051,20.993],[25.051,20.993],[26.251,18.795],[1.192,-20.114]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":9.99,"s":[100]},{"t":19.9800008138021,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[27.11,21.243],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0}],"markers":[]} }) </script> "#)) h3 style="text-align: center;" { "Please wait while we process your payment..." } } (PreEscaped(format!("<form id=\"PaReqForm\" method=\"POST\" action=\"{acs_url}\"> <input type=\"hidden\" name=\"creq\" value=\"{creq}\"> </form>"))) (PreEscaped(format!("<script> {logging_template} window.onload = function() {{ var paReqForm = document.querySelector('#PaReqForm'); if(paReqForm) paReqForm.submit(); }} </script>"))) } } } RedirectForm::Payme => { maud::html! { (maud::DOCTYPE) head { (PreEscaped(r#"<script src="https://cdn.paymeservice.com/hf/v1/hostedfields.js"></script>"#)) } (PreEscaped(format!("<script> {logging_template} var f = document.createElement('form'); f.action=window.location.pathname.replace(/payments\\/redirect\\/(\\w+)\\/(\\w+)\\/\\w+/, \"payments/$1/$2/redirect/complete/payme\"); f.method='POST'; PayMe.clientData() .then((data) => {{ var i=document.createElement('input'); i.type='hidden'; i.name='meta_data'; i.value=data.hash; f.appendChild(i); document.body.appendChild(f); f.submit(); }}) .catch((error) => {{ f.submit(); }}); </script> "))) } } RedirectForm::Braintree { client_token, card_token, bin, acs_url, } => { maud::html! { (maud::DOCTYPE) html { head { meta name="viewport" content="width=device-width, initial-scale=1"; (PreEscaped(r#"<script src="https://js.braintreegateway.com/web/3.97.1/js/three-d-secure.js"></script>"#)) // (PreEscaped(r#"<script src="https://js.braintreegateway.com/web/3.97.1/js/hosted-fields.js"></script>"#)) } body style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" { div id="loader1" class="lottie" style="height: 150px; display: block; position: relative; margin-top: 150px; margin-left: auto; margin-right: auto;" { "" } (PreEscaped(r#"<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.7.4/lottie.min.js"></script>"#)) (PreEscaped(r#" <script> var anime = bodymovin.loadAnimation({ container: document.getElementById('loader1'), renderer: 'svg', loop: true, autoplay: true, name: 'hyperswitch loader', animationData: {"v":"4.8.0","meta":{"g":"LottieFiles AE 3.1.1","a":"","k":"","d":"","tc":""},"fr":29.9700012207031,"ip":0,"op":31.0000012626559,"w":400,"h":250,"nm":"loader_shape","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":1,"ty":4,"nm":"circle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[278.25,202.671,0],"ix":2},"a":{"a":0,"k":[23.72,23.72,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[12.935,0],[0,-12.936],[-12.935,0],[0,12.935]],"o":[[-12.952,0],[0,12.935],[12.935,0],[0,-12.936]],"v":[[0,-23.471],[-23.47,0.001],[0,23.471],[23.47,0.001]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":10,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":19.99,"s":[100]},{"t":29.9800012211104,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[23.72,23.721],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"square 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[196.25,201.271,0],"ix":2},"a":{"a":0,"k":[22.028,22.03,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[1.914,0],[0,0],[0,-1.914],[0,0],[-1.914,0],[0,0],[0,1.914],[0,0]],"o":[[0,0],[-1.914,0],[0,0],[0,1.914],[0,0],[1.914,0],[0,0],[0,-1.914]],"v":[[18.313,-21.779],[-18.312,-21.779],[-21.779,-18.313],[-21.779,18.314],[-18.312,21.779],[18.313,21.779],[21.779,18.314],[21.779,-18.313]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":5,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":14.99,"s":[100]},{"t":24.9800010174563,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[22.028,22.029],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":47.0000019143492,"st":0,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"Triangle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[116.25,200.703,0],"ix":2},"a":{"a":0,"k":[27.11,21.243,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0.558,-0.879],[0,0],[-1.133,0],[0,0],[0.609,0.947],[0,0]],"o":[[-0.558,-0.879],[0,0],[-0.609,0.947],[0,0],[1.133,0],[0,0],[0,0]],"v":[[1.209,-20.114],[-1.192,-20.114],[-26.251,18.795],[-25.051,20.993],[25.051,20.993],[26.251,18.795],[1.192,-20.114]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":9.99,"s":[100]},{"t":19.9800008138021,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[27.11,21.243],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0}],"markers":[]} }) </script> "#)) h3 style="text-align: center;" { "Please wait while we process your payment..." } } (PreEscaped(format!("<script> {logging_template} var my3DSContainer; var clientToken = \"{client_token}\"; braintree.threeDSecure.create({{ authorization: clientToken, version: 2 }}, function(err, threeDs) {{ threeDs.verifyCard({{ amount: \"{amount}\", nonce: \"{card_token}\", bin: \"{bin}\", addFrame: function(err, iframe) {{ my3DSContainer = document.createElement('div'); my3DSContainer.appendChild(iframe); document.body.appendChild(my3DSContainer); }}, removeFrame: function() {{ if(my3DSContainer && my3DSContainer.parentNode) {{ my3DSContainer.parentNode.removeChild(my3DSContainer); }} }}, onLookupComplete: function(data, next) {{ // console.log(\"onLookup Complete\", data); next(); }} }}, function(err, payload) {{ if(err) {{ console.error(err); var f = document.createElement('form'); f.action=window.location.pathname.replace(/payments\\/redirect\\/(\\w+)\\/(\\w+)\\/\\w+/, \"payments/$1/$2/redirect/response/braintree\"); var i = document.createElement('input'); i.type = 'hidden'; f.method='POST'; i.name = 'authentication_response'; i.value = JSON.stringify(err); f.appendChild(i); f.body = JSON.stringify(err); document.body.appendChild(f); f.submit(); }} else {{ // console.log(payload); var f = document.createElement('form'); f.action=\"{acs_url}\"; var i = document.createElement('input'); i.type = 'hidden'; f.method='POST'; i.name = 'authentication_response'; i.value = JSON.stringify(payload); f.appendChild(i); f.body = JSON.stringify(payload); document.body.appendChild(f); f.submit(); }} }}); }}); </script>" ))) }} } RedirectForm::Nmi { amount, currency, public_key, customer_vault_id, order_id, } => { let public_key_val = public_key.peek(); maud::html! { (maud::DOCTYPE) head { (PreEscaped(r#"<script src="https://secure.networkmerchants.com/js/v1/Gateway.js"></script>"#)) } body style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" { div id="loader-wrapper" { div id="loader1" class="lottie" style="height: 150px; display: block; position: relative; margin-top: 150px; margin-left: auto; margin-right: auto;" { "" } (PreEscaped(r#"<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.7.4/lottie.min.js"></script>"#)) (PreEscaped(r#" <script> var anime = bodymovin.loadAnimation({ container: document.getElementById('loader1'), renderer: 'svg', loop: true, autoplay: true, name: 'hyperswitch loader', animationData: {"v":"4.8.0","meta":{"g":"LottieFiles AE 3.1.1","a":"","k":"","d":"","tc":""},"fr":29.9700012207031,"ip":0,"op":31.0000012626559,"w":400,"h":250,"nm":"loader_shape","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":1,"ty":4,"nm":"circle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[278.25,202.671,0],"ix":2},"a":{"a":0,"k":[23.72,23.72,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[12.935,0],[0,-12.936],[-12.935,0],[0,12.935]],"o":[[-12.952,0],[0,12.935],[12.935,0],[0,-12.936]],"v":[[0,-23.471],[-23.47,0.001],[0,23.471],[23.47,0.001]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":10,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":19.99,"s":[100]},{"t":29.9800012211104,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[23.72,23.721],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"square 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[196.25,201.271,0],"ix":2},"a":{"a":0,"k":[22.028,22.03,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[1.914,0],[0,0],[0,-1.914],[0,0],[-1.914,0],[0,0],[0,1.914],[0,0]],"o":[[0,0],[-1.914,0],[0,0],[0,1.914],[0,0],[1.914,0],[0,0],[0,-1.914]],"v":[[18.313,-21.779],[-18.312,-21.779],[-21.779,-18.313],[-21.779,18.314],[-18.312,21.779],[18.313,21.779],[21.779,18.314],[21.779,-18.313]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":5,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":14.99,"s":[100]},{"t":24.9800010174563,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[22.028,22.029],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":47.0000019143492,"st":0,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"Triangle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[116.25,200.703,0],"ix":2},"a":{"a":0,"k":[27.11,21.243,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0.558,-0.879],[0,0],[-1.133,0],[0,0],[0.609,0.947],[0,0]],"o":[[-0.558,-0.879],[0,0],[-0.609,0.947],[0,0],[1.133,0],[0,0],[0,0]],"v":[[1.209,-20.114],[-1.192,-20.114],[-26.251,18.795],[-25.051,20.993],[25.051,20.993],[26.251,18.795],[1.192,-20.114]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":9.99,"s":[100]},{"t":19.9800008138021,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[27.11,21.243],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0}],"markers":[]} }) </script> "#)) h3 style="text-align: center;" { "Please wait while we process your payment..." } } div id="threeds-wrapper" style="display: flex; width: 100%; height: 100vh; align-items: center; justify-content: center;" {""} } (PreEscaped(format!("<script> {logging_template} const gateway = Gateway.create('{public_key_val}'); // Initialize the ThreeDSService const threeDS = gateway.get3DSecure(); const options = {{ customerVaultId: '{customer_vault_id}', currency: '{currency}', amount: '{amount}' }}; const threeDSsecureInterface = threeDS.createUI(options); threeDSsecureInterface.on('challenge', function(e) {{ document.getElementById('loader-wrapper').style.display = 'none'; }}); threeDSsecureInterface.on('complete', function(e) {{ var responseForm = document.createElement('form'); responseForm.action=window.location.pathname.replace(/payments\\/redirect\\/(\\w+)\\/(\\w+)\\/\\w+/, \"payments/$1/$2/redirect/complete/nmi\"); responseForm.method='POST'; var item1=document.createElement('input'); item1.type='hidden'; item1.name='cavv'; item1.value=e.cavv; responseForm.appendChild(item1); var item2=document.createElement('input'); item2.type='hidden'; item2.name='xid'; item2.value=e.xid; responseForm.appendChild(item2); var item6=document.createElement('input'); item6.type='hidden'; item6.name='eci'; item6.value=e.eci; responseForm.appendChild(item6); var item7=document.createElement('input'); item7.type='hidden'; item7.name='directoryServerId'; item7.value=e.directoryServerId; responseForm.appendChild(item7); var item3=document.createElement('input'); item3.type='hidden'; item3.name='cardHolderAuth'; item3.value=e.cardHolderAuth; responseForm.appendChild(item3); var item4=document.createElement('input'); item4.type='hidden'; item4.name='threeDsVersion'; item4.value=e.threeDsVersion; responseForm.appendChild(item4); var item5=document.createElement('input'); item5.type='hidden'; item5.name='orderId'; item5.value='{order_id}'; responseForm.appendChild(item5); var item6=document.createElement('input'); item6.type='hidden'; item6.name='customerVaultId'; item6.value='{customer_vault_id}'; responseForm.appendChild(item6); document.body.appendChild(responseForm); responseForm.submit(); }}); threeDSsecureInterface.on('failure', function(e) {{ var responseForm = document.createElement('form'); responseForm.action=window.location.pathname.replace(/payments\\/redirect\\/(\\w+)\\/(\\w+)\\/\\w+/, \"payments/$1/$2/redirect/complete/nmi\"); responseForm.method='POST'; var error_code=document.createElement('input'); error_code.type='hidden'; error_code.name='code'; error_code.value= e.code; responseForm.appendChild(error_code); var error_message=document.createElement('input'); error_message.type='hidden'; error_message.name='message'; error_message.value= e.message; responseForm.appendChild(error_message); document.body.appendChild(responseForm); responseForm.submit(); }}); threeDSsecureInterface.start('#threeds-wrapper'); </script>" ))) } } RedirectForm::Mifinity { initialization_token, } => { let mifinity_base_url = config.connectors.mifinity.base_url; maud::html! { (maud::DOCTYPE) head { (PreEscaped(format!(r#"<script src='{mifinity_base_url}widgets/sgpg.js?58190a411dc3'></script>"#))) } (PreEscaped(format!("<div id='widget-container'></div> <script> var widget = showPaymentIframe('widget-container', {{ token: '{initialization_token}', complete: function() {{ var f = document.createElement('form'); f.action=window.location.pathname.replace(/payments\\/redirect\\/(\\w+)\\/(\\w+)\\/\\w+/, \"payments/$1/$2/redirect/response/mifinity\"); f.method='GET'; document.body.appendChild(f); f.submit(); }} }}); </script>"))) } } RedirectForm::WorldpayDDCForm { endpoint, method, form_fields, collection_id, } => maud::html! { (maud::DOCTYPE) html { meta name="viewport" content="width=device-width, initial-scale=1"; head { (PreEscaped(r##" <style> #loader1 { width: 500px; } @media (max-width: 600px) { #loader1 { width: 200px; } } </style> "##)) } body style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" { div id="loader1" class="lottie" style="height: 150px; display: block; position: relative; margin-left: auto; margin-right: auto;" { "" } (PreEscaped(r#"<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.7.4/lottie.min.js"></script>"#)) (PreEscaped(r#" <script> var anime = bodymovin.loadAnimation({ container: document.getElementById('loader1'), renderer: 'svg', loop: true, autoplay: true, name: 'hyperswitch loader', animationData: {"v":"4.8.0","meta":{"g":"LottieFiles AE 3.1.1","a":"","k":"","d":"","tc":""},"fr":29.9700012207031,"ip":0,"op":31.0000012626559,"w":400,"h":250,"nm":"loader_shape","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":1,"ty":4,"nm":"circle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[278.25,202.671,0],"ix":2},"a":{"a":0,"k":[23.72,23.72,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[12.935,0],[0,-12.936],[-12.935,0],[0,12.935]],"o":[[-12.952,0],[0,12.935],[12.935,0],[0,-12.936]],"v":[[0,-23.471],[-23.47,0.001],[0,23.471],[23.47,0.001]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":10,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":19.99,"s":[100]},{"t":29.9800012211104,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[23.72,23.721],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"square 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[196.25,201.271,0],"ix":2},"a":{"a":0,"k":[22.028,22.03,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[1.914,0],[0,0],[0,-1.914],[0,0],[-1.914,0],[0,0],[0,1.914],[0,0]],"o":[[0,0],[-1.914,0],[0,0],[0,1.914],[0,0],[1.914,0],[0,0],[0,-1.914]],"v":[[18.313,-21.779],[-18.312,-21.779],[-21.779,-18.313],[-21.779,18.314],[-18.312,21.779],[18.313,21.779],[21.779,18.314],[21.779,-18.313]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":5,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":14.99,"s":[100]},{"t":24.9800010174563,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[22.028,22.029],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":47.0000019143492,"st":0,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"Triangle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[116.25,200.703,0],"ix":2},"a":{"a":0,"k":[27.11,21.243,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0.558,-0.879],[0,0],[-1.133,0],[0,0],[0.609,0.947],[0,0]],"o":[[-0.558,-0.879],[0,0],[-0.609,0.947],[0,0],[1.133,0],[0,0],[0,0]],"v":[[1.209,-20.114],[-1.192,-20.114],[-26.251,18.795],[-25.051,20.993],[25.051,20.993],[26.251,18.795],[1.192,-20.114]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":9.99,"s":[100]},{"t":19.9800008138021,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[27.11,21.243],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0}],"markers":[]} }) </script> "#)) h3 style="text-align: center;" { "Please wait while we process your payment..." } script { (PreEscaped(format!( r#" var ddcProcessed = false; var timeoutHandle = null; function submitCollectionReference(collectionReference) {{ if (ddcProcessed) {{ console.log("DDC already processed, ignoring duplicate submission"); return; }} ddcProcessed = true; if (timeoutHandle) {{ clearTimeout(timeoutHandle); timeoutHandle = null; }} var redirectPathname = window.location.pathname.replace(/payments\/redirect\/([^\/]+)\/([^\/]+)\/[^\/]+/, "payments/$1/$2/redirect/complete/worldpay"); var redirectUrl = window.location.origin + redirectPathname; try {{ if (typeof collectionReference === "string" && collectionReference.length > 0) {{ var form = document.createElement("form"); form.action = redirectPathname; form.method = "GET"; var input = document.createElement("input"); input.type = "hidden"; input.name = "collectionReference"; input.value = collectionReference; form.appendChild(input); document.body.appendChild(form); form.submit(); }} else {{ window.location.replace(redirectUrl); }} }} catch (error) {{ console.error("Error submitting DDC:", error); window.location.replace(redirectUrl); }} }} var allowedHost = "{}"; var collectionField = "{}"; window.addEventListener("message", function(event) {{ if (ddcProcessed) {{ console.log("DDC already processed, ignoring message event"); return; }} if (event.origin === allowedHost) {{ try {{ var data = JSON.parse(event.data); if (collectionField.length > 0) {{ var collectionReference = data[collectionField]; return submitCollectionReference(collectionReference); }} else {{ console.error("Collection field not found in event data (" + collectionField + ")"); }} }} catch (error) {{ console.error("Error parsing event data: ", error); }} }} else {{ console.error("Invalid origin: " + event.origin, "Expected origin: " + allowedHost); }} submitCollectionReference(""); }}); // Timeout after 10 seconds and will submit empty collection reference timeoutHandle = window.setTimeout(function() {{ if (!ddcProcessed) {{ console.log("DDC timeout reached, submitting empty collection reference"); submitCollectionReference(""); }} }}, 10000); "#, endpoint.host_str().map_or(endpoint.as_ref().split('/').take(3).collect::<Vec<&str>>().join("/"), |host| format!("{}://{}", endpoint.scheme(), host)), collection_id.clone().unwrap_or("".to_string()))) ) } iframe style="display: none;" srcdoc=( maud::html! { (maud::DOCTYPE) html { body { form action=(PreEscaped(endpoint.to_string())) method=(method.to_string()) #payment_form { @for (field, value) in form_fields { input type="hidden" name=(field) value=(value); } } (PreEscaped(format!(r#" <script type="text/javascript"> {logging_template} var form = document.getElementById("payment_form"); var formFields = form.querySelectorAll("input"); window.setTimeout(function () {{ if (form.method.toUpperCase() === "GET" && formFields.length === 0) {{ window.location.href = form.action; }} else {{ form.submit(); }} }}, 300); </script> "#))) } } }.into_string() ) {} } } }, } } fn build_payment_link_template( payment_link_data: PaymentLinkFormData, ) -> CustomResult<(Tera, Context), errors::ApiErrorResponse> { let mut tera = Tera::default(); // Add modification to css template with dynamic data let css_template = include_str!("../core/payment_link/payment_link_initiate/payment_link.css").to_string(); let _ = tera.add_raw_template("payment_link_css", &css_template); let mut context = Context::new(); context.insert("css_color_scheme", &payment_link_data.css_script); let rendered_css = match tera.render("payment_link_css", &context) { Ok(rendered_css) => rendered_css, Err(tera_error) => { crate::logger::warn!("{tera_error}"); Err(errors::ApiErrorResponse::InternalServerError)? } }; // Add modification to js template with dynamic data let js_template = include_str!("../core/payment_link/payment_link_initiate/payment_link.js").to_string(); let _ = tera.add_raw_template("payment_link_js", &js_template); context.insert("payment_details_js_script", &payment_link_data.js_script); let sdk_origin = payment_link_data .sdk_url .host_str() .ok_or_else(|| { logger::error!("Host missing for payment link SDK URL"); report!(errors::ApiErrorResponse::InternalServerError) }) .and_then(|host| { if host == "localhost" { let port = payment_link_data.sdk_url.port().ok_or_else(|| { logger::error!("Port missing for localhost in SDK URL"); report!(errors::ApiErrorResponse::InternalServerError) })?; Ok(format!( "{}://{}:{}", payment_link_data.sdk_url.scheme(), host, port )) } else { Ok(format!("{}://{}", payment_link_data.sdk_url.scheme(), host)) } })?; context.insert("sdk_origin", &sdk_origin); let rendered_js = match tera.render("payment_link_js", &context) { Ok(rendered_js) => rendered_js, Err(tera_error) => { crate::logger::warn!("{tera_error}"); Err(errors::ApiErrorResponse::InternalServerError)? } }; // Logging template let logging_template = include_str!("redirection/assets/redirect_error_logs_push.js").to_string(); //Locale template let locale_template = include_str!("../core/payment_link/locale.js").to_string(); // Modify Html template with rendered js and rendered css files let html_template = include_str!("../core/payment_link/payment_link_initiate/payment_link.html").to_string(); let _ = tera.add_raw_template("payment_link", &html_template); context.insert("rendered_meta_tag_html", &payment_link_data.html_meta_tags); context.insert( "preload_link_tags", &get_preload_link_html_template(&payment_link_data.sdk_url), ); context.insert( "hyperloader_sdk_link", &get_hyper_loader_sdk(&payment_link_data.sdk_url), ); context.insert("locale_template", &locale_template); context.insert("rendered_css", &rendered_css); context.insert("rendered_js", &rendered_js); context.insert("logging_template", &logging_template); Ok((tera, context)) } pub fn build_payment_link_html( payment_link_data: PaymentLinkFormData, ) -> CustomResult<String, errors::ApiErrorResponse> { let (tera, mut context) = build_payment_link_template(payment_link_data) .attach_printable("Failed to build payment link's HTML template")?; let payment_link_initiator = include_str!("../core/payment_link/payment_link_initiate/payment_link_initiator.js") .to_string(); context.insert("payment_link_initiator", &payment_link_initiator); tera.render("payment_link", &context) .map_err(|tera_error: TeraError| { crate::logger::warn!("{tera_error}"); report!(errors::ApiErrorResponse::InternalServerError) }) .attach_printable("Error while rendering open payment link's HTML template") } pub fn build_secure_payment_link_html( payment_link_data: PaymentLinkFormData, ) -> CustomResult<String, errors::ApiErrorResponse> { let (tera, mut context) = build_payment_link_template(payment_link_data) .attach_printable("Failed to build payment link's HTML template")?; let payment_link_initiator = include_str!("../core/payment_link/payment_link_initiate/secure_payment_link_initiator.js") .to_string(); context.insert("payment_link_initiator", &payment_link_initiator); tera.render("payment_link", &context) .map_err(|tera_error: TeraError| { crate::logger::warn!("{tera_error}"); report!(errors::ApiErrorResponse::InternalServerError) }) .attach_printable("Error while rendering secure payment link's HTML template") } fn get_hyper_loader_sdk(sdk_url: &url::Url) -> String { format!("<script src=\"{sdk_url}\" onload=\"initializeSDK()\"></script>") } fn get_preload_link_html_template(sdk_url: &url::Url) -> String { format!( r#"<link rel="preload" href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;600;700;800" as="style"> <link rel="preload" href="{sdk_url}" as="script">"#, ) } pub fn get_payment_link_status( payment_link_data: PaymentLinkStatusData, ) -> CustomResult<String, errors::ApiErrorResponse> { let mut tera = Tera::default(); // Add modification to css template with dynamic data let css_template = include_str!("../core/payment_link/payment_link_status/status.css").to_string(); let _ = tera.add_raw_template("payment_link_css", &css_template); let mut context = Context::new(); context.insert("css_color_scheme", &payment_link_data.css_script); let rendered_css = match tera.render("payment_link_css", &context) { Ok(rendered_css) => rendered_css, Err(tera_error) => { crate::logger::warn!("{tera_error}"); Err(errors::ApiErrorResponse::InternalServerError)? } }; //Locale template let locale_template = include_str!("../core/payment_link/locale.js"); // Logging template let logging_template = include_str!("redirection/assets/redirect_error_logs_push.js").to_string(); // Add modification to js template with dynamic data let js_template = include_str!("../core/payment_link/payment_link_status/status.js").to_string(); let _ = tera.add_raw_template("payment_link_js", &js_template); context.insert("payment_details_js_script", &payment_link_data.js_script); let rendered_js = match tera.render("payment_link_js", &context) { Ok(rendered_js) => rendered_js, Err(tera_error) => { crate::logger::warn!("{tera_error}"); Err(errors::ApiErrorResponse::InternalServerError)? } }; // Modify Html template with rendered js and rendered css files let html_template = include_str!("../core/payment_link/payment_link_status/status.html").to_string(); let _ = tera.add_raw_template("payment_link_status", &html_template); context.insert("rendered_css", &rendered_css); context.insert("locale_template", &locale_template); context.insert("rendered_js", &rendered_js); context.insert("logging_template", &logging_template); match tera.render("payment_link_status", &context) { Ok(rendered_html) => Ok(rendered_html), Err(tera_error) => { crate::logger::warn!("{tera_error}"); Err(errors::ApiErrorResponse::InternalServerError)? } } } pub fn extract_mapped_fields( value: &serde_json::Value, mapping: Option<&HashMap<String, String>>, existing_enhancement: Option<&serde_json::Value>, ) -> Option<serde_json::Value> { let mapping = mapping?; if mapping.is_empty() { return existing_enhancement.cloned(); } let mut enhancement = match existing_enhancement { Some(existing) if existing.is_object() => existing.clone(), _ => serde_json::json!({}), }; for (dot_path, output_key) in mapping { if let Some(extracted_value) = extract_field_by_dot_path(value, dot_path) { if let Some(obj) = enhancement.as_object_mut() { obj.insert(output_key.clone(), extracted_value); } } } if enhancement.as_object().is_some_and(|obj| !obj.is_empty()) { Some(enhancement) } else { None } } pub fn extract_field_by_dot_path( value: &serde_json::Value, path: &str, ) -> Option<serde_json::Value> { let parts: Vec<&str> = path.split('.').collect(); let mut current = value; for part in parts { match current { serde_json::Value::Object(obj) => { current = obj.get(part)?; } serde_json::Value::Array(arr) => { // Try to parse part as array index if let Ok(index) = part.parse::<usize>() { current = arr.get(index)?; } else { return None; } } _ => return None, } } Some(current.clone()) } #[cfg(test)] mod tests { #[test] fn test_mime_essence() { assert_eq!(mime::APPLICATION_JSON.essence_str(), "application/json"); } }
crates/router/src/services/api.rs
router::src::services::api
39,560
true
// File: crates/router/src/services/authorization.rs // Module: router::src::services::authorization use std::sync::Arc; use common_utils::id_type; use error_stack::ResultExt; use redis_interface::RedisConnectionPool; use router_env::logger; use super::authentication::AuthToken; use crate::{ consts, core::errors::{ApiErrorResponse, RouterResult, StorageErrorExt}, routes::app::SessionStateInfo, }; #[cfg(feature = "olap")] pub mod info; pub mod permission_groups; pub mod permissions; pub mod roles; pub async fn get_role_info<A>(state: &A, token: &AuthToken) -> RouterResult<roles::RoleInfo> where A: SessionStateInfo + Sync, { if let Some(role_info) = roles::predefined_roles::PREDEFINED_ROLES.get(token.role_id.as_str()) { return Ok(role_info.clone()); } if let Ok(role_info) = get_role_info_from_cache(state, &token.role_id) .await .map_err(|e| logger::error!("Failed to get permissions from cache {e:?}")) { return Ok(role_info.clone()); } let role_info = get_role_info_from_db( state, &token.role_id, &token.org_id, token .tenant_id .as_ref() .unwrap_or(&state.session_state().tenant.tenant_id), ) .await?; let token_expiry = i64::try_from(token.exp).change_context(ApiErrorResponse::InternalServerError)?; let cache_ttl = token_expiry - common_utils::date_time::now_unix_timestamp(); if cache_ttl > 0 { set_role_info_in_cache(state, &token.role_id, &role_info, cache_ttl) .await .map_err(|e| logger::error!("Failed to set role info in cache {e:?}")) .ok(); } Ok(role_info) } async fn get_role_info_from_cache<A>(state: &A, role_id: &str) -> RouterResult<roles::RoleInfo> where A: SessionStateInfo + Sync, { let redis_conn = get_redis_connection_for_global_tenant(state)?; redis_conn .get_and_deserialize_key(&get_cache_key_from_role_id(role_id).into(), "RoleInfo") .await .change_context(ApiErrorResponse::InternalServerError) } pub fn get_cache_key_from_role_id(role_id: &str) -> String { format!("{}{}", consts::ROLE_INFO_CACHE_PREFIX, role_id) } async fn get_role_info_from_db<A>( state: &A, role_id: &str, org_id: &id_type::OrganizationId, tenant_id: &id_type::TenantId, ) -> RouterResult<roles::RoleInfo> where A: SessionStateInfo + Sync, { state .session_state() .global_store .find_by_role_id_org_id_tenant_id(role_id, org_id, tenant_id) .await .map(roles::RoleInfo::from) .to_not_found_response(ApiErrorResponse::InvalidJwtToken) } pub async fn set_role_info_in_cache<A>( state: &A, role_id: &str, role_info: &roles::RoleInfo, expiry: i64, ) -> RouterResult<()> where A: SessionStateInfo + Sync, { let redis_conn = get_redis_connection_for_global_tenant(state)?; redis_conn .serialize_and_set_key_with_expiry( &get_cache_key_from_role_id(role_id).into(), role_info, expiry, ) .await .change_context(ApiErrorResponse::InternalServerError) } pub fn check_permission( required_permission: permissions::Permission, role_info: &roles::RoleInfo, ) -> RouterResult<()> { role_info .check_permission_exists(required_permission) .then_some(()) .ok_or( ApiErrorResponse::AccessForbidden { resource: required_permission.to_string(), } .into(), ) } pub fn check_tenant( token_tenant_id: Option<id_type::TenantId>, header_tenant_id: &id_type::TenantId, ) -> RouterResult<()> { if let Some(tenant_id) = token_tenant_id { if tenant_id != *header_tenant_id { return Err(ApiErrorResponse::InvalidJwtToken).attach_printable(format!( "Token tenant ID: '{}' does not match Header tenant ID: '{}'", tenant_id.get_string_repr().to_owned(), header_tenant_id.get_string_repr().to_owned() )); } } Ok(()) } fn get_redis_connection_for_global_tenant<A: SessionStateInfo>( state: &A, ) -> RouterResult<Arc<RedisConnectionPool>> { state .global_store() .get_redis_conn() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection") }
crates/router/src/services/authorization.rs
router::src::services::authorization
1,065
true
// File: crates/router/src/services/pm_auth.rs // Module: router::src::services::pm_auth use pm_auth::{ consts, core::errors::ConnectorError, types::{self as pm_auth_types, api::BoxedConnectorIntegration, PaymentAuthRouterData}, }; use crate::{ core::errors::{self}, logger, routes::SessionState, services::{self}, }; pub async fn execute_connector_processing_step<'b, T, Req, Resp>( state: &'b SessionState, connector_integration: BoxedConnectorIntegration<'_, T, Req, Resp>, req: &'b PaymentAuthRouterData<T, Req, Resp>, connector: &pm_auth_types::PaymentMethodAuthConnectors, ) -> errors::CustomResult<PaymentAuthRouterData<T, Req, Resp>, ConnectorError> where T: Clone + 'static, Req: Clone + 'static, Resp: Clone + 'static, { let mut router_data = req.clone(); let connector_request = connector_integration.build_request(req, connector)?; match connector_request { Some(request) => { logger::debug!(connector_request=?request); let response = services::api::call_connector_api( state, request, "execute_connector_processing_step", ) .await; logger::debug!(connector_response=?response); match response { Ok(body) => { let response = match body { Ok(body) => { let body = pm_auth_types::Response { headers: body.headers, response: body.response, status_code: body.status_code, }; let connector_http_status_code = Some(body.status_code); let mut data = connector_integration.handle_response(&router_data, body)?; data.connector_http_status_code = connector_http_status_code; data } Err(body) => { let body = pm_auth_types::Response { headers: body.headers, response: body.response, status_code: body.status_code, }; router_data.connector_http_status_code = Some(body.status_code); let error = match body.status_code { 500..=511 => connector_integration.get_5xx_error_response(body)?, _ => connector_integration.get_error_response(body)?, }; router_data.response = Err(error); router_data } }; Ok(response) } Err(error) => { if error.current_context().is_upstream_timeout() { let error_response = pm_auth_types::ErrorResponse { code: consts::REQUEST_TIMEOUT_ERROR_CODE.to_string(), message: consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_string(), reason: Some(consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_string()), status_code: 504, }; router_data.response = Err(error_response); router_data.connector_http_status_code = Some(504); Ok(router_data) } else { Err(error.change_context(ConnectorError::ProcessingStepFailed(None))) } } } } None => Ok(router_data), } }
crates/router/src/services/pm_auth.rs
router::src::services::pm_auth
644
true
// File: crates/router/src/services/kafka/refund_event.rs // Module: router::src::services::kafka::refund_event #[cfg(feature = "v2")] use common_utils::pii; #[cfg(feature = "v2")] use common_utils::types::{self, ChargeRefunds}; use common_utils::{ id_type, types::{ConnectorTransactionIdTrait, MinorUnit}, }; use diesel_models::{enums as storage_enums, refund::Refund}; use time::OffsetDateTime; use crate::events; #[cfg(feature = "v1")] #[serde_with::skip_serializing_none] #[derive(serde::Serialize, Debug)] pub struct KafkaRefundEvent<'a> { pub internal_reference_id: &'a String, pub refund_id: &'a String, //merchant_reference id pub payment_id: &'a id_type::PaymentId, pub merchant_id: &'a id_type::MerchantId, pub connector_transaction_id: &'a String, pub connector: &'a String, pub connector_refund_id: Option<&'a String>, pub external_reference_id: Option<&'a String>, pub refund_type: &'a storage_enums::RefundType, pub total_amount: &'a MinorUnit, pub currency: &'a storage_enums::Currency, pub refund_amount: &'a MinorUnit, pub refund_status: &'a storage_enums::RefundStatus, pub sent_to_gateway: &'a bool, pub refund_error_message: Option<&'a String>, pub refund_arn: Option<&'a String>, #[serde(with = "time::serde::timestamp::nanoseconds")] pub created_at: OffsetDateTime, #[serde(with = "time::serde::timestamp::nanoseconds")] pub modified_at: OffsetDateTime, pub description: Option<&'a String>, pub attempt_id: &'a String, pub refund_reason: Option<&'a String>, pub refund_error_code: Option<&'a String>, pub profile_id: Option<&'a id_type::ProfileId>, pub organization_id: &'a id_type::OrganizationId, } #[cfg(feature = "v1")] impl<'a> KafkaRefundEvent<'a> { pub fn from_storage(refund: &'a Refund) -> Self { Self { internal_reference_id: &refund.internal_reference_id, refund_id: &refund.refund_id, payment_id: &refund.payment_id, merchant_id: &refund.merchant_id, connector_transaction_id: refund.get_connector_transaction_id(), connector: &refund.connector, connector_refund_id: refund.get_optional_connector_refund_id(), external_reference_id: refund.external_reference_id.as_ref(), refund_type: &refund.refund_type, total_amount: &refund.total_amount, currency: &refund.currency, refund_amount: &refund.refund_amount, refund_status: &refund.refund_status, sent_to_gateway: &refund.sent_to_gateway, refund_error_message: refund.refund_error_message.as_ref(), refund_arn: refund.refund_arn.as_ref(), created_at: refund.created_at.assume_utc(), modified_at: refund.modified_at.assume_utc(), description: refund.description.as_ref(), attempt_id: &refund.attempt_id, refund_reason: refund.refund_reason.as_ref(), refund_error_code: refund.refund_error_code.as_ref(), profile_id: refund.profile_id.as_ref(), organization_id: &refund.organization_id, } } } #[cfg(feature = "v2")] #[serde_with::skip_serializing_none] #[derive(serde::Serialize, Debug)] pub struct KafkaRefundEvent<'a> { pub refund_id: &'a id_type::GlobalRefundId, pub merchant_reference_id: &'a id_type::RefundReferenceId, pub payment_id: &'a id_type::GlobalPaymentId, pub merchant_id: &'a id_type::MerchantId, pub connector_transaction_id: &'a types::ConnectorTransactionId, pub connector: &'a String, pub connector_refund_id: Option<&'a types::ConnectorTransactionId>, pub external_reference_id: Option<&'a String>, pub refund_type: &'a storage_enums::RefundType, pub total_amount: &'a MinorUnit, pub currency: &'a storage_enums::Currency, pub refund_amount: &'a MinorUnit, pub refund_status: &'a storage_enums::RefundStatus, pub sent_to_gateway: &'a bool, pub refund_error_message: Option<&'a String>, pub refund_arn: Option<&'a String>, #[serde(with = "time::serde::timestamp::nanoseconds")] pub created_at: OffsetDateTime, #[serde(with = "time::serde::timestamp::nanoseconds")] pub modified_at: OffsetDateTime, pub description: Option<&'a String>, pub attempt_id: &'a id_type::GlobalAttemptId, pub refund_reason: Option<&'a String>, pub refund_error_code: Option<&'a String>, pub profile_id: Option<&'a id_type::ProfileId>, pub organization_id: &'a id_type::OrganizationId, pub metadata: Option<&'a pii::SecretSerdeValue>, pub updated_by: &'a String, pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>, pub charges: Option<&'a ChargeRefunds>, pub connector_refund_data: Option<&'a String>, pub connector_transaction_data: Option<&'a String>, pub split_refunds: Option<&'a common_types::refunds::SplitRefund>, pub unified_code: Option<&'a String>, pub unified_message: Option<&'a String>, pub processor_refund_data: Option<&'a String>, pub processor_transaction_data: Option<&'a String>, } #[cfg(feature = "v2")] impl<'a> KafkaRefundEvent<'a> { pub fn from_storage(refund: &'a Refund) -> Self { let Refund { payment_id, merchant_id, connector_transaction_id, connector, connector_refund_id, external_reference_id, refund_type, total_amount, currency, refund_amount, refund_status, sent_to_gateway, refund_error_message, metadata, refund_arn, created_at, modified_at, description, attempt_id, refund_reason, refund_error_code, profile_id, updated_by, charges, organization_id, split_refunds, unified_code, unified_message, processor_refund_data, processor_transaction_data, id, merchant_reference_id, connector_id, } = refund; Self { refund_id: id, merchant_reference_id, payment_id, merchant_id, connector_transaction_id, connector, connector_refund_id: connector_refund_id.as_ref(), external_reference_id: external_reference_id.as_ref(), refund_type, total_amount, currency, refund_amount, refund_status, sent_to_gateway, refund_error_message: refund_error_message.as_ref(), refund_arn: refund_arn.as_ref(), created_at: created_at.assume_utc(), modified_at: modified_at.assume_utc(), description: description.as_ref(), attempt_id, refund_reason: refund_reason.as_ref(), refund_error_code: refund_error_code.as_ref(), profile_id: profile_id.as_ref(), organization_id, metadata: metadata.as_ref(), updated_by, merchant_connector_id: connector_id.as_ref(), charges: charges.as_ref(), connector_refund_data: processor_refund_data.as_ref(), connector_transaction_data: processor_transaction_data.as_ref(), split_refunds: split_refunds.as_ref(), unified_code: unified_code.as_ref(), unified_message: unified_message.as_ref(), processor_refund_data: processor_refund_data.as_ref(), processor_transaction_data: processor_transaction_data.as_ref(), } } } #[cfg(feature = "v1")] impl super::KafkaMessage for KafkaRefundEvent<'_> { fn key(&self) -> String { format!( "{}_{}_{}_{}", self.merchant_id.get_string_repr(), self.payment_id.get_string_repr(), self.attempt_id, self.refund_id ) } fn event_type(&self) -> events::EventType { events::EventType::Refund } } #[cfg(feature = "v2")] impl super::KafkaMessage for KafkaRefundEvent<'_> { fn key(&self) -> String { format!( "{}_{}_{}_{}", self.merchant_id.get_string_repr(), self.payment_id.get_string_repr(), self.attempt_id.get_string_repr(), self.merchant_reference_id.get_string_repr() ) } fn event_type(&self) -> events::EventType { events::EventType::Refund } }
crates/router/src/services/kafka/refund_event.rs
router::src::services::kafka::refund_event
1,913
true
// File: crates/router/src/services/kafka/dispute.rs // Module: router::src::services::kafka::dispute use common_utils::{ ext_traits::StringExt, id_type, types::{AmountConvertor, MinorUnit, StringMinorUnitForConnector}, }; use diesel_models::enums as storage_enums; use masking::Secret; use time::OffsetDateTime; use crate::types::storage::dispute::Dispute; #[derive(serde::Serialize, Debug)] pub struct KafkaDispute<'a> { pub dispute_id: &'a String, pub dispute_amount: MinorUnit, pub currency: storage_enums::Currency, pub dispute_stage: &'a storage_enums::DisputeStage, pub dispute_status: &'a storage_enums::DisputeStatus, pub payment_id: &'a id_type::PaymentId, pub attempt_id: &'a String, pub merchant_id: &'a id_type::MerchantId, pub connector_status: &'a String, pub connector_dispute_id: &'a String, pub connector_reason: Option<&'a String>, pub connector_reason_code: Option<&'a String>, #[serde(default, with = "time::serde::timestamp::option")] pub challenge_required_by: Option<OffsetDateTime>, #[serde(default, with = "time::serde::timestamp::option")] pub connector_created_at: Option<OffsetDateTime>, #[serde(default, with = "time::serde::timestamp::option")] pub connector_updated_at: Option<OffsetDateTime>, #[serde(default, with = "time::serde::timestamp")] pub created_at: OffsetDateTime, #[serde(default, with = "time::serde::timestamp")] pub modified_at: OffsetDateTime, pub connector: &'a String, pub evidence: &'a Secret<serde_json::Value>, pub profile_id: Option<&'a id_type::ProfileId>, pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>, pub organization_id: &'a id_type::OrganizationId, } impl<'a> KafkaDispute<'a> { pub fn from_storage(dispute: &'a Dispute) -> Self { let currency = dispute.dispute_currency.unwrap_or( dispute .currency .to_uppercase() .parse_enum("Currency") .unwrap_or_default(), ); Self { dispute_id: &dispute.dispute_id, dispute_amount: StringMinorUnitForConnector::convert_back( &StringMinorUnitForConnector, dispute.amount.clone(), currency, ) .unwrap_or_else(|e| { router_env::logger::error!("Failed to convert dispute amount: {e:?}"); MinorUnit::new(0) }), currency, dispute_stage: &dispute.dispute_stage, dispute_status: &dispute.dispute_status, payment_id: &dispute.payment_id, attempt_id: &dispute.attempt_id, merchant_id: &dispute.merchant_id, connector_status: &dispute.connector_status, connector_dispute_id: &dispute.connector_dispute_id, connector_reason: dispute.connector_reason.as_ref(), connector_reason_code: dispute.connector_reason_code.as_ref(), challenge_required_by: dispute.challenge_required_by.map(|i| i.assume_utc()), connector_created_at: dispute.connector_created_at.map(|i| i.assume_utc()), connector_updated_at: dispute.connector_updated_at.map(|i| i.assume_utc()), created_at: dispute.created_at.assume_utc(), modified_at: dispute.modified_at.assume_utc(), connector: &dispute.connector, evidence: &dispute.evidence, profile_id: dispute.profile_id.as_ref(), merchant_connector_id: dispute.merchant_connector_id.as_ref(), organization_id: &dispute.organization_id, } } } impl super::KafkaMessage for KafkaDispute<'_> { fn key(&self) -> String { format!( "{}_{}_{}", self.merchant_id.get_string_repr(), self.payment_id.get_string_repr(), self.dispute_id ) } fn event_type(&self) -> crate::events::EventType { crate::events::EventType::Dispute } }
crates/router/src/services/kafka/dispute.rs
router::src::services::kafka::dispute
907
true
// File: crates/router/src/services/kafka/payment_attempt.rs // Module: router::src::services::kafka::payment_attempt #[cfg(feature = "v2")] use common_types::payments; #[cfg(feature = "v2")] use common_utils::types; use common_utils::{id_type, types::MinorUnit}; use diesel_models::enums as storage_enums; #[cfg(feature = "v2")] use diesel_models::payment_attempt; #[cfg(feature = "v2")] use hyperswitch_domain_models::{ address, payments::payment_attempt::PaymentAttemptFeatureMetadata, router_response_types::RedirectForm, }; use hyperswitch_domain_models::{ mandates::MandateDetails, payments::payment_attempt::PaymentAttempt, }; use time::OffsetDateTime; #[cfg(feature = "v1")] #[derive(serde::Serialize, Debug)] pub struct KafkaPaymentAttempt<'a> { pub payment_id: &'a id_type::PaymentId, pub merchant_id: &'a id_type::MerchantId, pub attempt_id: &'a String, pub status: storage_enums::AttemptStatus, pub amount: MinorUnit, pub currency: Option<storage_enums::Currency>, pub save_to_locker: Option<bool>, pub connector: Option<&'a String>, pub error_message: Option<&'a String>, pub offer_amount: Option<MinorUnit>, pub surcharge_amount: Option<MinorUnit>, pub tax_amount: Option<MinorUnit>, pub payment_method_id: Option<&'a String>, pub payment_method: Option<storage_enums::PaymentMethod>, pub connector_transaction_id: Option<&'a String>, pub capture_method: Option<storage_enums::CaptureMethod>, #[serde(default, with = "time::serde::timestamp::option")] pub capture_on: Option<OffsetDateTime>, pub confirm: bool, pub authentication_type: Option<storage_enums::AuthenticationType>, #[serde(with = "time::serde::timestamp")] pub created_at: OffsetDateTime, #[serde(with = "time::serde::timestamp")] pub modified_at: OffsetDateTime, #[serde(default, with = "time::serde::timestamp::option")] pub last_synced: Option<OffsetDateTime>, pub cancellation_reason: Option<&'a String>, pub amount_to_capture: Option<MinorUnit>, pub mandate_id: Option<&'a String>, pub browser_info: Option<String>, pub error_code: Option<&'a String>, pub connector_metadata: Option<String>, // TODO: These types should implement copy ideally pub payment_experience: Option<&'a storage_enums::PaymentExperience>, pub payment_method_type: Option<&'a storage_enums::PaymentMethodType>, pub payment_method_data: Option<String>, pub error_reason: Option<&'a String>, pub multiple_capture_count: Option<i16>, pub amount_capturable: MinorUnit, pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>, pub net_amount: MinorUnit, pub unified_code: Option<&'a String>, pub unified_message: Option<&'a String>, pub mandate_data: Option<&'a MandateDetails>, pub client_source: Option<&'a String>, pub client_version: Option<&'a String>, pub profile_id: &'a id_type::ProfileId, pub organization_id: &'a id_type::OrganizationId, pub card_network: Option<String>, pub card_discovery: Option<String>, pub routing_approach: Option<storage_enums::RoutingApproach>, pub debit_routing_savings: Option<MinorUnit>, pub signature_network: Option<common_enums::CardNetwork>, pub is_issuer_regulated: Option<bool>, } #[cfg(feature = "v1")] impl<'a> KafkaPaymentAttempt<'a> { pub fn from_storage(attempt: &'a PaymentAttempt) -> Self { let card_payment_method_data = attempt .get_payment_method_data() .and_then(|data| data.get_additional_card_info()); Self { payment_id: &attempt.payment_id, merchant_id: &attempt.merchant_id, attempt_id: &attempt.attempt_id, status: attempt.status, amount: attempt.net_amount.get_order_amount(), currency: attempt.currency, save_to_locker: attempt.save_to_locker, connector: attempt.connector.as_ref(), error_message: attempt.error_message.as_ref(), offer_amount: attempt.offer_amount, surcharge_amount: attempt.net_amount.get_surcharge_amount(), tax_amount: attempt.net_amount.get_tax_on_surcharge(), payment_method_id: attempt.payment_method_id.as_ref(), payment_method: attempt.payment_method, connector_transaction_id: attempt.connector_transaction_id.as_ref(), capture_method: attempt.capture_method, capture_on: attempt.capture_on.map(|i| i.assume_utc()), confirm: attempt.confirm, authentication_type: attempt.authentication_type, created_at: attempt.created_at.assume_utc(), modified_at: attempt.modified_at.assume_utc(), last_synced: attempt.last_synced.map(|i| i.assume_utc()), cancellation_reason: attempt.cancellation_reason.as_ref(), amount_to_capture: attempt.amount_to_capture, mandate_id: attempt.mandate_id.as_ref(), browser_info: attempt.browser_info.as_ref().map(|v| v.to_string()), error_code: attempt.error_code.as_ref(), connector_metadata: attempt.connector_metadata.as_ref().map(|v| v.to_string()), payment_experience: attempt.payment_experience.as_ref(), payment_method_type: attempt.payment_method_type.as_ref(), payment_method_data: attempt.payment_method_data.as_ref().map(|v| v.to_string()), error_reason: attempt.error_reason.as_ref(), multiple_capture_count: attempt.multiple_capture_count, amount_capturable: attempt.amount_capturable, merchant_connector_id: attempt.merchant_connector_id.as_ref(), net_amount: attempt.net_amount.get_total_amount(), unified_code: attempt.unified_code.as_ref(), unified_message: attempt.unified_message.as_ref(), mandate_data: attempt.mandate_data.as_ref(), client_source: attempt.client_source.as_ref(), client_version: attempt.client_version.as_ref(), profile_id: &attempt.profile_id, organization_id: &attempt.organization_id, card_network: attempt .payment_method_data .as_ref() .and_then(|data| data.as_object()) .and_then(|pm| pm.get("card")) .and_then(|data| data.as_object()) .and_then(|card| card.get("card_network")) .and_then(|network| network.as_str()) .map(|network| network.to_string()), card_discovery: attempt .card_discovery .map(|discovery| discovery.to_string()), routing_approach: attempt.routing_approach.clone(), debit_routing_savings: attempt.debit_routing_savings, signature_network: card_payment_method_data .as_ref() .and_then(|data| data.signature_network.clone()), is_issuer_regulated: card_payment_method_data.and_then(|data| data.is_regulated), } } } #[cfg(feature = "v2")] #[derive(serde::Serialize, Debug)] pub struct KafkaPaymentAttempt<'a> { pub payment_id: &'a id_type::GlobalPaymentId, pub merchant_id: &'a id_type::MerchantId, pub attempt_id: &'a id_type::GlobalAttemptId, pub attempts_group_id: Option<&'a String>, pub status: storage_enums::AttemptStatus, pub amount: MinorUnit, pub connector: Option<&'a String>, pub error_message: Option<&'a String>, pub surcharge_amount: Option<MinorUnit>, pub tax_amount: Option<MinorUnit>, pub payment_method_id: Option<&'a id_type::GlobalPaymentMethodId>, pub payment_method: storage_enums::PaymentMethod, pub connector_transaction_id: Option<&'a String>, pub authentication_type: storage_enums::AuthenticationType, #[serde(with = "time::serde::timestamp")] pub created_at: OffsetDateTime, #[serde(with = "time::serde::timestamp")] pub modified_at: OffsetDateTime, #[serde(default, with = "time::serde::timestamp::option")] pub last_synced: Option<OffsetDateTime>, pub cancellation_reason: Option<&'a String>, pub amount_to_capture: Option<MinorUnit>, pub browser_info: Option<&'a types::BrowserInformation>, pub error_code: Option<&'a String>, pub connector_metadata: Option<String>, // TODO: These types should implement copy ideally pub payment_experience: Option<&'a storage_enums::PaymentExperience>, pub payment_method_type: &'a storage_enums::PaymentMethodType, pub payment_method_data: Option<String>, pub error_reason: Option<&'a String>, pub multiple_capture_count: Option<i16>, pub amount_capturable: MinorUnit, pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>, pub net_amount: MinorUnit, pub unified_code: Option<&'a String>, pub unified_message: Option<&'a String>, pub client_source: Option<&'a String>, pub client_version: Option<&'a String>, pub profile_id: &'a id_type::ProfileId, pub organization_id: &'a id_type::OrganizationId, pub card_network: Option<String>, pub card_discovery: Option<String>, pub connector_payment_id: Option<types::ConnectorTransactionId>, pub payment_token: Option<String>, pub preprocessing_step_id: Option<String>, pub connector_response_reference_id: Option<String>, pub updated_by: &'a String, pub encoded_data: Option<&'a masking::Secret<String>>, pub external_three_ds_authentication_attempted: Option<bool>, pub authentication_connector: Option<String>, pub authentication_id: Option<String>, pub fingerprint_id: Option<String>, pub customer_acceptance: Option<&'a masking::Secret<payments::CustomerAcceptance>>, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, pub charges: Option<payments::ConnectorChargeResponseData>, pub processor_merchant_id: &'a id_type::MerchantId, pub created_by: Option<&'a types::CreatedBy>, pub payment_method_type_v2: storage_enums::PaymentMethod, pub payment_method_subtype: storage_enums::PaymentMethodType, pub routing_result: Option<serde_json::Value>, pub authentication_applied: Option<common_enums::AuthenticationType>, pub external_reference_id: Option<String>, pub tax_on_surcharge: Option<MinorUnit>, pub payment_method_billing_address: Option<masking::Secret<&'a address::Address>>, // adjusted from Encryption pub redirection_data: Option<&'a RedirectForm>, pub connector_payment_data: Option<String>, pub connector_token_details: Option<&'a payment_attempt::ConnectorTokenDetails>, pub feature_metadata: Option<&'a PaymentAttemptFeatureMetadata>, pub network_advice_code: Option<String>, pub network_decline_code: Option<String>, pub network_error_message: Option<String>, pub connector_request_reference_id: Option<String>, } #[cfg(feature = "v2")] impl<'a> KafkaPaymentAttempt<'a> { pub fn from_storage(attempt: &'a PaymentAttempt) -> Self { use masking::PeekInterface; let PaymentAttempt { payment_id, merchant_id, attempts_group_id, amount_details, status, connector, error, authentication_type, created_at, modified_at, last_synced, cancellation_reason, browser_info, payment_token, connector_metadata, payment_experience, payment_method_data, routing_result, preprocessing_step_id, multiple_capture_count, connector_response_reference_id, updated_by, redirection_data, encoded_data, merchant_connector_id, external_three_ds_authentication_attempted, authentication_connector, authentication_id, fingerprint_id, client_source, client_version, customer_acceptance, profile_id, organization_id, payment_method_type, payment_method_id, connector_payment_id, payment_method_subtype, authentication_applied, external_reference_id, payment_method_billing_address, id, connector_token_details, card_discovery, charges, feature_metadata, processor_merchant_id, created_by, connector_request_reference_id, network_transaction_id: _, authorized_amount: _, } = attempt; let (connector_payment_id, connector_payment_data) = connector_payment_id .clone() .map(types::ConnectorTransactionId::form_id_and_data) .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) .unwrap_or((None, None)); Self { payment_id, merchant_id, attempt_id: id, attempts_group_id: attempts_group_id.as_ref(), status: *status, amount: amount_details.get_net_amount(), connector: connector.as_ref(), error_message: error.as_ref().map(|error_details| &error_details.message), surcharge_amount: amount_details.get_surcharge_amount(), tax_amount: amount_details.get_tax_on_surcharge(), payment_method_id: payment_method_id.as_ref(), payment_method: *payment_method_type, connector_transaction_id: connector_response_reference_id.as_ref(), authentication_type: *authentication_type, created_at: created_at.assume_utc(), modified_at: modified_at.assume_utc(), last_synced: last_synced.map(|i| i.assume_utc()), cancellation_reason: cancellation_reason.as_ref(), amount_to_capture: amount_details.get_amount_to_capture(), browser_info: browser_info.as_ref(), error_code: error.as_ref().map(|error_details| &error_details.code), connector_metadata: connector_metadata.as_ref().map(|v| v.peek().to_string()), payment_experience: payment_experience.as_ref(), payment_method_type: payment_method_subtype, payment_method_data: payment_method_data.as_ref().map(|v| v.peek().to_string()), error_reason: error .as_ref() .and_then(|error_details| error_details.reason.as_ref()), multiple_capture_count: *multiple_capture_count, amount_capturable: amount_details.get_amount_capturable(), merchant_connector_id: merchant_connector_id.as_ref(), net_amount: amount_details.get_net_amount(), unified_code: error .as_ref() .and_then(|error_details| error_details.unified_code.as_ref()), unified_message: error .as_ref() .and_then(|error_details| error_details.unified_message.as_ref()), client_source: client_source.as_ref(), client_version: client_version.as_ref(), profile_id, organization_id, card_network: payment_method_data .as_ref() .map(|data| data.peek()) .and_then(|data| data.as_object()) .and_then(|pm| pm.get("card")) .and_then(|data| data.as_object()) .and_then(|card| card.get("card_network")) .and_then(|network| network.as_str()) .map(|network| network.to_string()), card_discovery: card_discovery.map(|discovery| discovery.to_string()), payment_token: payment_token.clone(), preprocessing_step_id: preprocessing_step_id.clone(), connector_response_reference_id: connector_response_reference_id.clone(), updated_by, encoded_data: encoded_data.as_ref(), external_three_ds_authentication_attempted: *external_three_ds_authentication_attempted, authentication_connector: authentication_connector.clone(), authentication_id: authentication_id .as_ref() .map(|id| id.get_string_repr().to_string().clone()), fingerprint_id: fingerprint_id.clone(), customer_acceptance: customer_acceptance.as_ref(), shipping_cost: amount_details.get_shipping_cost(), order_tax_amount: amount_details.get_order_tax_amount(), charges: charges.clone(), processor_merchant_id, created_by: created_by.as_ref(), payment_method_type_v2: *payment_method_type, connector_payment_id: connector_payment_id.as_ref().cloned(), payment_method_subtype: *payment_method_subtype, routing_result: routing_result.clone(), authentication_applied: *authentication_applied, external_reference_id: external_reference_id.clone(), tax_on_surcharge: amount_details.get_tax_on_surcharge(), payment_method_billing_address: payment_method_billing_address .as_ref() .map(|v| masking::Secret::new(v.get_inner())), redirection_data: redirection_data.as_ref(), connector_payment_data, connector_token_details: connector_token_details.as_ref(), feature_metadata: feature_metadata.as_ref(), network_advice_code: error .as_ref() .and_then(|details| details.network_advice_code.clone()), network_decline_code: error .as_ref() .and_then(|details| details.network_decline_code.clone()), network_error_message: error .as_ref() .and_then(|details| details.network_error_message.clone()), connector_request_reference_id: connector_request_reference_id.clone(), } } } impl super::KafkaMessage for KafkaPaymentAttempt<'_> { #[cfg(feature = "v1")] fn key(&self) -> String { format!( "{}_{}_{}", self.merchant_id.get_string_repr(), self.payment_id.get_string_repr(), self.attempt_id ) } #[cfg(feature = "v2")] fn key(&self) -> String { format!( "{}_{}_{}", self.merchant_id.get_string_repr(), self.payment_id.get_string_repr(), self.attempt_id.get_string_repr() ) } fn event_type(&self) -> crate::events::EventType { crate::events::EventType::PaymentAttempt } }
crates/router/src/services/kafka/payment_attempt.rs
router::src::services::kafka::payment_attempt
3,844
true
// File: crates/router/src/services/kafka/payout.rs // Module: router::src::services::kafka::payout use common_utils::{id_type, pii, types::MinorUnit}; use diesel_models::enums as storage_enums; use hyperswitch_domain_models::payouts::{payout_attempt::PayoutAttempt, payouts::Payouts}; use time::OffsetDateTime; #[derive(serde::Serialize, Debug)] pub struct KafkaPayout<'a> { pub payout_id: &'a id_type::PayoutId, pub payout_attempt_id: &'a String, pub merchant_id: &'a id_type::MerchantId, pub customer_id: Option<&'a id_type::CustomerId>, pub address_id: Option<&'a String>, pub profile_id: &'a id_type::ProfileId, pub payout_method_id: Option<&'a String>, pub payout_type: Option<storage_enums::PayoutType>, pub amount: MinorUnit, pub destination_currency: storage_enums::Currency, pub source_currency: storage_enums::Currency, pub description: Option<&'a String>, pub recurring: bool, pub auto_fulfill: bool, pub return_url: Option<&'a String>, pub entity_type: storage_enums::PayoutEntityType, pub metadata: Option<pii::SecretSerdeValue>, #[serde(with = "time::serde::timestamp")] pub created_at: OffsetDateTime, #[serde(with = "time::serde::timestamp")] pub last_modified_at: OffsetDateTime, pub attempt_count: i16, pub status: storage_enums::PayoutStatus, pub priority: Option<storage_enums::PayoutSendPriority>, pub connector: Option<&'a String>, pub connector_payout_id: Option<&'a String>, pub is_eligible: Option<bool>, pub error_message: Option<&'a String>, pub error_code: Option<&'a String>, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<&'a String>, pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>, } impl<'a> KafkaPayout<'a> { pub fn from_storage(payouts: &'a Payouts, payout_attempt: &'a PayoutAttempt) -> Self { Self { payout_id: &payouts.payout_id, payout_attempt_id: &payout_attempt.payout_attempt_id, merchant_id: &payouts.merchant_id, customer_id: payouts.customer_id.as_ref(), address_id: payouts.address_id.as_ref(), profile_id: &payouts.profile_id, payout_method_id: payouts.payout_method_id.as_ref(), payout_type: payouts.payout_type, amount: payouts.amount, destination_currency: payouts.destination_currency, source_currency: payouts.source_currency, description: payouts.description.as_ref(), recurring: payouts.recurring, auto_fulfill: payouts.auto_fulfill, return_url: payouts.return_url.as_ref(), entity_type: payouts.entity_type, metadata: payouts.metadata.clone(), created_at: payouts.created_at.assume_utc(), last_modified_at: payouts.last_modified_at.assume_utc(), attempt_count: payouts.attempt_count, status: payouts.status, priority: payouts.priority, connector: payout_attempt.connector.as_ref(), connector_payout_id: payout_attempt.connector_payout_id.as_ref(), is_eligible: payout_attempt.is_eligible, error_message: payout_attempt.error_message.as_ref(), error_code: payout_attempt.error_code.as_ref(), business_country: payout_attempt.business_country, business_label: payout_attempt.business_label.as_ref(), merchant_connector_id: payout_attempt.merchant_connector_id.as_ref(), } } } impl super::KafkaMessage for KafkaPayout<'_> { fn key(&self) -> String { format!( "{}_{}", self.merchant_id.get_string_repr(), self.payout_attempt_id ) } fn event_type(&self) -> crate::events::EventType { crate::events::EventType::Payout } }
crates/router/src/services/kafka/payout.rs
router::src::services::kafka::payout
893
true
// File: crates/router/src/services/kafka/fraud_check.rs // Module: router::src::services::kafka::fraud_check // use diesel_models::enums as storage_enums; use diesel_models::{ enums as storage_enums, enums::{FraudCheckLastStep, FraudCheckStatus, FraudCheckType}, fraud_check::FraudCheck, }; use time::OffsetDateTime; #[derive(serde::Serialize, Debug)] pub struct KafkaFraudCheck<'a> { pub frm_id: &'a String, pub payment_id: &'a common_utils::id_type::PaymentId, pub merchant_id: &'a common_utils::id_type::MerchantId, pub attempt_id: &'a String, #[serde(with = "time::serde::timestamp")] pub created_at: OffsetDateTime, pub frm_name: &'a String, pub frm_transaction_id: Option<&'a String>, pub frm_transaction_type: FraudCheckType, pub frm_status: FraudCheckStatus, pub frm_score: Option<i32>, pub frm_reason: Option<serde_json::Value>, pub frm_error: Option<&'a String>, pub payment_details: Option<serde_json::Value>, pub metadata: Option<serde_json::Value>, #[serde(with = "time::serde::timestamp")] pub modified_at: OffsetDateTime, pub last_step: FraudCheckLastStep, pub payment_capture_method: Option<storage_enums::CaptureMethod>, // In postFrm, we are updating capture method from automatic to manual. To store the merchant actual capture method, we are storing the actual capture method in payment_capture_method. It will be useful while approving the FRM decision. } impl<'a> KafkaFraudCheck<'a> { pub fn from_storage(check: &'a FraudCheck) -> Self { Self { frm_id: &check.frm_id, payment_id: &check.payment_id, merchant_id: &check.merchant_id, attempt_id: &check.attempt_id, created_at: check.created_at.assume_utc(), frm_name: &check.frm_name, frm_transaction_id: check.frm_transaction_id.as_ref(), frm_transaction_type: check.frm_transaction_type, frm_status: check.frm_status, frm_score: check.frm_score, frm_reason: check.frm_reason.clone(), frm_error: check.frm_error.as_ref(), payment_details: check.payment_details.clone(), metadata: check.metadata.clone(), modified_at: check.modified_at.assume_utc(), last_step: check.last_step, payment_capture_method: check.payment_capture_method, } } } impl super::KafkaMessage for KafkaFraudCheck<'_> { fn key(&self) -> String { format!( "{}_{}_{}_{}", self.merchant_id.get_string_repr(), self.payment_id.get_string_repr(), self.attempt_id, self.frm_id ) } fn event_type(&self) -> crate::events::EventType { crate::events::EventType::FraudCheck } }
crates/router/src/services/kafka/fraud_check.rs
router::src::services::kafka::fraud_check
659
true
// File: crates/router/src/services/kafka/dispute_event.rs // Module: router::src::services::kafka::dispute_event use common_utils::{ ext_traits::StringExt, types::{AmountConvertor, MinorUnit, StringMinorUnitForConnector}, }; use diesel_models::enums as storage_enums; use masking::Secret; use time::OffsetDateTime; use crate::types::storage::dispute::Dispute; #[serde_with::skip_serializing_none] #[derive(serde::Serialize, Debug)] pub struct KafkaDisputeEvent<'a> { pub dispute_id: &'a String, pub dispute_amount: MinorUnit, pub currency: storage_enums::Currency, pub dispute_stage: &'a storage_enums::DisputeStage, pub dispute_status: &'a storage_enums::DisputeStatus, pub payment_id: &'a common_utils::id_type::PaymentId, pub attempt_id: &'a String, pub merchant_id: &'a common_utils::id_type::MerchantId, pub connector_status: &'a String, pub connector_dispute_id: &'a String, pub connector_reason: Option<&'a String>, pub connector_reason_code: Option<&'a String>, #[serde(default, with = "time::serde::timestamp::nanoseconds::option")] pub challenge_required_by: Option<OffsetDateTime>, #[serde(default, with = "time::serde::timestamp::nanoseconds::option")] pub connector_created_at: Option<OffsetDateTime>, #[serde(default, with = "time::serde::timestamp::nanoseconds::option")] pub connector_updated_at: Option<OffsetDateTime>, #[serde(with = "time::serde::timestamp::nanoseconds")] pub created_at: OffsetDateTime, #[serde(with = "time::serde::timestamp::nanoseconds")] pub modified_at: OffsetDateTime, pub connector: &'a String, pub evidence: &'a Secret<serde_json::Value>, pub profile_id: Option<&'a common_utils::id_type::ProfileId>, pub merchant_connector_id: Option<&'a common_utils::id_type::MerchantConnectorAccountId>, pub organization_id: &'a common_utils::id_type::OrganizationId, } impl<'a> KafkaDisputeEvent<'a> { pub fn from_storage(dispute: &'a Dispute) -> Self { let currency = dispute.dispute_currency.unwrap_or( dispute .currency .to_uppercase() .parse_enum("Currency") .unwrap_or_default(), ); Self { dispute_id: &dispute.dispute_id, dispute_amount: StringMinorUnitForConnector::convert_back( &StringMinorUnitForConnector, dispute.amount.clone(), currency, ) .unwrap_or_else(|e| { router_env::logger::error!("Failed to convert dispute amount: {e:?}"); MinorUnit::new(0) }), currency, dispute_stage: &dispute.dispute_stage, dispute_status: &dispute.dispute_status, payment_id: &dispute.payment_id, attempt_id: &dispute.attempt_id, merchant_id: &dispute.merchant_id, connector_status: &dispute.connector_status, connector_dispute_id: &dispute.connector_dispute_id, connector_reason: dispute.connector_reason.as_ref(), connector_reason_code: dispute.connector_reason_code.as_ref(), challenge_required_by: dispute.challenge_required_by.map(|i| i.assume_utc()), connector_created_at: dispute.connector_created_at.map(|i| i.assume_utc()), connector_updated_at: dispute.connector_updated_at.map(|i| i.assume_utc()), created_at: dispute.created_at.assume_utc(), modified_at: dispute.modified_at.assume_utc(), connector: &dispute.connector, evidence: &dispute.evidence, profile_id: dispute.profile_id.as_ref(), merchant_connector_id: dispute.merchant_connector_id.as_ref(), organization_id: &dispute.organization_id, } } } impl super::KafkaMessage for KafkaDisputeEvent<'_> { fn key(&self) -> String { format!( "{}_{}_{}", self.merchant_id.get_string_repr(), self.payment_id.get_string_repr(), self.dispute_id ) } fn event_type(&self) -> crate::events::EventType { crate::events::EventType::Dispute } }
crates/router/src/services/kafka/dispute_event.rs
router::src::services::kafka::dispute_event
943
true
// File: crates/router/src/services/kafka/payment_attempt_event.rs // Module: router::src::services::kafka::payment_attempt_event #[cfg(feature = "v2")] use common_types::payments; #[cfg(feature = "v2")] use common_utils::types; use common_utils::{id_type, types::MinorUnit}; use diesel_models::enums as storage_enums; #[cfg(feature = "v2")] use diesel_models::payment_attempt; #[cfg(feature = "v2")] use hyperswitch_domain_models::{ address, payments::payment_attempt::PaymentAttemptFeatureMetadata, router_response_types::RedirectForm, }; use hyperswitch_domain_models::{ mandates::MandateDetails, payments::payment_attempt::PaymentAttempt, }; use time::OffsetDateTime; #[cfg(feature = "v1")] #[serde_with::skip_serializing_none] #[derive(serde::Serialize, Debug)] pub struct KafkaPaymentAttemptEvent<'a> { pub payment_id: &'a id_type::PaymentId, pub merchant_id: &'a id_type::MerchantId, pub attempt_id: &'a String, pub status: storage_enums::AttemptStatus, pub amount: MinorUnit, pub currency: Option<storage_enums::Currency>, pub save_to_locker: Option<bool>, pub connector: Option<&'a String>, pub error_message: Option<&'a String>, pub offer_amount: Option<MinorUnit>, pub surcharge_amount: Option<MinorUnit>, pub tax_amount: Option<MinorUnit>, pub payment_method_id: Option<&'a String>, pub payment_method: Option<storage_enums::PaymentMethod>, pub connector_transaction_id: Option<&'a String>, pub capture_method: Option<storage_enums::CaptureMethod>, #[serde(default, with = "time::serde::timestamp::nanoseconds::option")] pub capture_on: Option<OffsetDateTime>, pub confirm: bool, pub authentication_type: Option<storage_enums::AuthenticationType>, #[serde(with = "time::serde::timestamp::nanoseconds")] pub created_at: OffsetDateTime, #[serde(with = "time::serde::timestamp::nanoseconds")] pub modified_at: OffsetDateTime, #[serde(default, with = "time::serde::timestamp::nanoseconds::option")] pub last_synced: Option<OffsetDateTime>, pub cancellation_reason: Option<&'a String>, pub amount_to_capture: Option<MinorUnit>, pub mandate_id: Option<&'a String>, pub browser_info: Option<String>, pub error_code: Option<&'a String>, pub connector_metadata: Option<String>, // TODO: These types should implement copy ideally pub payment_experience: Option<&'a storage_enums::PaymentExperience>, pub payment_method_type: Option<&'a storage_enums::PaymentMethodType>, pub payment_method_data: Option<String>, pub error_reason: Option<&'a String>, pub multiple_capture_count: Option<i16>, pub amount_capturable: MinorUnit, pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>, pub net_amount: MinorUnit, pub unified_code: Option<&'a String>, pub unified_message: Option<&'a String>, pub mandate_data: Option<&'a MandateDetails>, pub client_source: Option<&'a String>, pub client_version: Option<&'a String>, pub profile_id: &'a id_type::ProfileId, pub organization_id: &'a id_type::OrganizationId, pub card_network: Option<String>, pub card_discovery: Option<String>, pub routing_approach: Option<storage_enums::RoutingApproach>, pub debit_routing_savings: Option<MinorUnit>, pub signature_network: Option<common_enums::CardNetwork>, pub is_issuer_regulated: Option<bool>, } #[cfg(feature = "v1")] impl<'a> KafkaPaymentAttemptEvent<'a> { pub fn from_storage(attempt: &'a PaymentAttempt) -> Self { let card_payment_method_data = attempt .get_payment_method_data() .and_then(|data| data.get_additional_card_info()); Self { payment_id: &attempt.payment_id, merchant_id: &attempt.merchant_id, attempt_id: &attempt.attempt_id, status: attempt.status, amount: attempt.net_amount.get_order_amount(), currency: attempt.currency, save_to_locker: attempt.save_to_locker, connector: attempt.connector.as_ref(), error_message: attempt.error_message.as_ref(), offer_amount: attempt.offer_amount, surcharge_amount: attempt.net_amount.get_surcharge_amount(), tax_amount: attempt.net_amount.get_tax_on_surcharge(), payment_method_id: attempt.payment_method_id.as_ref(), payment_method: attempt.payment_method, connector_transaction_id: attempt.connector_transaction_id.as_ref(), capture_method: attempt.capture_method, capture_on: attempt.capture_on.map(|i| i.assume_utc()), confirm: attempt.confirm, authentication_type: attempt.authentication_type, created_at: attempt.created_at.assume_utc(), modified_at: attempt.modified_at.assume_utc(), last_synced: attempt.last_synced.map(|i| i.assume_utc()), cancellation_reason: attempt.cancellation_reason.as_ref(), amount_to_capture: attempt.amount_to_capture, mandate_id: attempt.mandate_id.as_ref(), browser_info: attempt.browser_info.as_ref().map(|v| v.to_string()), error_code: attempt.error_code.as_ref(), connector_metadata: attempt.connector_metadata.as_ref().map(|v| v.to_string()), payment_experience: attempt.payment_experience.as_ref(), payment_method_type: attempt.payment_method_type.as_ref(), payment_method_data: attempt.payment_method_data.as_ref().map(|v| v.to_string()), error_reason: attempt.error_reason.as_ref(), multiple_capture_count: attempt.multiple_capture_count, amount_capturable: attempt.amount_capturable, merchant_connector_id: attempt.merchant_connector_id.as_ref(), net_amount: attempt.net_amount.get_total_amount(), unified_code: attempt.unified_code.as_ref(), unified_message: attempt.unified_message.as_ref(), mandate_data: attempt.mandate_data.as_ref(), client_source: attempt.client_source.as_ref(), client_version: attempt.client_version.as_ref(), profile_id: &attempt.profile_id, organization_id: &attempt.organization_id, card_network: attempt .payment_method_data .as_ref() .and_then(|data| data.as_object()) .and_then(|pm| pm.get("card")) .and_then(|data| data.as_object()) .and_then(|card| card.get("card_network")) .and_then(|network| network.as_str()) .map(|network| network.to_string()), card_discovery: attempt .card_discovery .map(|discovery| discovery.to_string()), routing_approach: attempt.routing_approach.clone(), debit_routing_savings: attempt.debit_routing_savings, signature_network: card_payment_method_data .as_ref() .and_then(|data| data.signature_network.clone()), is_issuer_regulated: card_payment_method_data.and_then(|data| data.is_regulated), } } } #[cfg(feature = "v2")] #[serde_with::skip_serializing_none] #[derive(serde::Serialize, Debug)] pub struct KafkaPaymentAttemptEvent<'a> { pub payment_id: &'a id_type::GlobalPaymentId, pub merchant_id: &'a id_type::MerchantId, pub attempt_id: &'a id_type::GlobalAttemptId, pub attempts_group_id: Option<&'a String>, pub status: storage_enums::AttemptStatus, pub amount: MinorUnit, pub connector: Option<&'a String>, pub error_message: Option<&'a String>, pub surcharge_amount: Option<MinorUnit>, pub tax_amount: Option<MinorUnit>, pub payment_method_id: Option<&'a id_type::GlobalPaymentMethodId>, pub payment_method: storage_enums::PaymentMethod, pub connector_transaction_id: Option<&'a String>, pub authentication_type: storage_enums::AuthenticationType, #[serde(with = "time::serde::timestamp::nanoseconds")] pub created_at: OffsetDateTime, #[serde(with = "time::serde::timestamp::nanoseconds")] pub modified_at: OffsetDateTime, #[serde(default, with = "time::serde::timestamp::nanoseconds::option")] pub last_synced: Option<OffsetDateTime>, pub cancellation_reason: Option<&'a String>, pub amount_to_capture: Option<MinorUnit>, pub browser_info: Option<&'a types::BrowserInformation>, pub error_code: Option<&'a String>, pub connector_metadata: Option<String>, // TODO: These types should implement copy ideally pub payment_experience: Option<&'a storage_enums::PaymentExperience>, pub payment_method_type: &'a storage_enums::PaymentMethodType, pub payment_method_data: Option<String>, pub error_reason: Option<&'a String>, pub multiple_capture_count: Option<i16>, pub amount_capturable: MinorUnit, pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>, pub net_amount: MinorUnit, pub unified_code: Option<&'a String>, pub unified_message: Option<&'a String>, pub client_source: Option<&'a String>, pub client_version: Option<&'a String>, pub profile_id: &'a id_type::ProfileId, pub organization_id: &'a id_type::OrganizationId, pub card_network: Option<String>, pub card_discovery: Option<String>, pub connector_payment_id: Option<types::ConnectorTransactionId>, pub payment_token: Option<String>, pub preprocessing_step_id: Option<String>, pub connector_response_reference_id: Option<String>, pub updated_by: &'a String, pub encoded_data: Option<&'a masking::Secret<String>>, pub external_three_ds_authentication_attempted: Option<bool>, pub authentication_connector: Option<String>, pub authentication_id: Option<String>, pub fingerprint_id: Option<String>, pub customer_acceptance: Option<&'a masking::Secret<payments::CustomerAcceptance>>, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, pub charges: Option<payments::ConnectorChargeResponseData>, pub processor_merchant_id: &'a id_type::MerchantId, pub created_by: Option<&'a types::CreatedBy>, pub payment_method_type_v2: storage_enums::PaymentMethod, pub payment_method_subtype: storage_enums::PaymentMethodType, pub routing_result: Option<serde_json::Value>, pub authentication_applied: Option<common_enums::AuthenticationType>, pub external_reference_id: Option<String>, pub tax_on_surcharge: Option<MinorUnit>, pub payment_method_billing_address: Option<masking::Secret<&'a address::Address>>, // adjusted from Encryption pub redirection_data: Option<&'a RedirectForm>, pub connector_payment_data: Option<String>, pub connector_token_details: Option<&'a payment_attempt::ConnectorTokenDetails>, pub feature_metadata: Option<&'a PaymentAttemptFeatureMetadata>, pub network_advice_code: Option<String>, pub network_decline_code: Option<String>, pub network_error_message: Option<String>, pub connector_request_reference_id: Option<String>, } #[cfg(feature = "v2")] impl<'a> KafkaPaymentAttemptEvent<'a> { pub fn from_storage(attempt: &'a PaymentAttempt) -> Self { use masking::PeekInterface; let PaymentAttempt { payment_id, merchant_id, attempts_group_id, amount_details, status, connector, error, authentication_type, created_at, modified_at, last_synced, cancellation_reason, browser_info, payment_token, connector_metadata, payment_experience, payment_method_data, routing_result, preprocessing_step_id, multiple_capture_count, connector_response_reference_id, updated_by, redirection_data, encoded_data, merchant_connector_id, external_three_ds_authentication_attempted, authentication_connector, authentication_id, fingerprint_id, client_source, client_version, customer_acceptance, profile_id, organization_id, payment_method_type, payment_method_id, connector_payment_id, payment_method_subtype, authentication_applied, external_reference_id, payment_method_billing_address, id, connector_token_details, card_discovery, charges, feature_metadata, processor_merchant_id, created_by, connector_request_reference_id, network_transaction_id: _, authorized_amount: _, } = attempt; let (connector_payment_id, connector_payment_data) = connector_payment_id .clone() .map(types::ConnectorTransactionId::form_id_and_data) .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) .unwrap_or((None, None)); Self { payment_id, merchant_id, attempt_id: id, attempts_group_id: attempts_group_id.as_ref(), status: *status, amount: amount_details.get_net_amount(), connector: connector.as_ref(), error_message: error.as_ref().map(|error_details| &error_details.message), surcharge_amount: amount_details.get_surcharge_amount(), tax_amount: amount_details.get_tax_on_surcharge(), payment_method_id: payment_method_id.as_ref(), payment_method: *payment_method_type, connector_transaction_id: connector_response_reference_id.as_ref(), authentication_type: *authentication_type, created_at: created_at.assume_utc(), modified_at: modified_at.assume_utc(), last_synced: last_synced.map(|i| i.assume_utc()), cancellation_reason: cancellation_reason.as_ref(), amount_to_capture: amount_details.get_amount_to_capture(), browser_info: browser_info.as_ref(), error_code: error.as_ref().map(|error_details| &error_details.code), connector_metadata: connector_metadata.as_ref().map(|v| v.peek().to_string()), payment_experience: payment_experience.as_ref(), payment_method_type: payment_method_subtype, payment_method_data: payment_method_data.as_ref().map(|v| v.peek().to_string()), error_reason: error .as_ref() .and_then(|error_details| error_details.reason.as_ref()), multiple_capture_count: *multiple_capture_count, amount_capturable: amount_details.get_amount_capturable(), merchant_connector_id: merchant_connector_id.as_ref(), net_amount: amount_details.get_net_amount(), unified_code: error .as_ref() .and_then(|error_details| error_details.unified_code.as_ref()), unified_message: error .as_ref() .and_then(|error_details| error_details.unified_message.as_ref()), client_source: client_source.as_ref(), client_version: client_version.as_ref(), profile_id, organization_id, card_network: payment_method_data .as_ref() .map(|data| data.peek()) .and_then(|data| data.as_object()) .and_then(|pm| pm.get("card")) .and_then(|data| data.as_object()) .and_then(|card| card.get("card_network")) .and_then(|network| network.as_str()) .map(|network| network.to_string()), card_discovery: card_discovery.map(|discovery| discovery.to_string()), payment_token: payment_token.clone(), preprocessing_step_id: preprocessing_step_id.clone(), connector_response_reference_id: connector_response_reference_id.clone(), updated_by, encoded_data: encoded_data.as_ref(), external_three_ds_authentication_attempted: *external_three_ds_authentication_attempted, authentication_connector: authentication_connector.clone(), authentication_id: authentication_id .as_ref() .map(|id| id.get_string_repr().to_string()), fingerprint_id: fingerprint_id.clone(), customer_acceptance: customer_acceptance.as_ref(), shipping_cost: amount_details.get_shipping_cost(), order_tax_amount: amount_details.get_order_tax_amount(), charges: charges.clone(), processor_merchant_id, created_by: created_by.as_ref(), payment_method_type_v2: *payment_method_type, connector_payment_id: connector_payment_id.as_ref().cloned(), payment_method_subtype: *payment_method_subtype, routing_result: routing_result.clone(), authentication_applied: *authentication_applied, external_reference_id: external_reference_id.clone(), tax_on_surcharge: amount_details.get_tax_on_surcharge(), payment_method_billing_address: payment_method_billing_address .as_ref() .map(|v| masking::Secret::new(v.get_inner())), redirection_data: redirection_data.as_ref(), connector_payment_data, connector_token_details: connector_token_details.as_ref(), feature_metadata: feature_metadata.as_ref(), network_advice_code: error .as_ref() .and_then(|details| details.network_advice_code.clone()), network_decline_code: error .as_ref() .and_then(|details| details.network_decline_code.clone()), network_error_message: error .as_ref() .and_then(|details| details.network_error_message.clone()), connector_request_reference_id: connector_request_reference_id.clone(), } } } impl super::KafkaMessage for KafkaPaymentAttemptEvent<'_> { #[cfg(feature = "v1")] fn key(&self) -> String { format!( "{}_{}_{}", self.merchant_id.get_string_repr(), self.payment_id.get_string_repr(), self.attempt_id ) } #[cfg(feature = "v2")] fn key(&self) -> String { format!( "{}_{}_{}", self.merchant_id.get_string_repr(), self.payment_id.get_string_repr(), self.attempt_id.get_string_repr() ) } fn event_type(&self) -> crate::events::EventType { crate::events::EventType::PaymentAttempt } }
crates/router/src/services/kafka/payment_attempt_event.rs
router::src::services::kafka::payment_attempt_event
3,888
true
// File: crates/router/src/services/kafka/fraud_check_event.rs // Module: router::src::services::kafka::fraud_check_event use diesel_models::{ enums as storage_enums, enums::{FraudCheckLastStep, FraudCheckStatus, FraudCheckType}, fraud_check::FraudCheck, }; use time::OffsetDateTime; #[derive(serde::Serialize, Debug)] pub struct KafkaFraudCheckEvent<'a> { pub frm_id: &'a String, pub payment_id: &'a common_utils::id_type::PaymentId, pub merchant_id: &'a common_utils::id_type::MerchantId, pub attempt_id: &'a String, #[serde(with = "time::serde::timestamp::nanoseconds")] pub created_at: OffsetDateTime, pub frm_name: &'a String, pub frm_transaction_id: Option<&'a String>, pub frm_transaction_type: FraudCheckType, pub frm_status: FraudCheckStatus, pub frm_score: Option<i32>, pub frm_reason: Option<serde_json::Value>, pub frm_error: Option<&'a String>, pub payment_details: Option<serde_json::Value>, pub metadata: Option<serde_json::Value>, #[serde(with = "time::serde::timestamp::nanoseconds")] pub modified_at: OffsetDateTime, pub last_step: FraudCheckLastStep, pub payment_capture_method: Option<storage_enums::CaptureMethod>, // In postFrm, we are updating capture method from automatic to manual. To store the merchant actual capture method, we are storing the actual capture method in payment_capture_method. It will be useful while approving the FRM decision. } impl<'a> KafkaFraudCheckEvent<'a> { pub fn from_storage(check: &'a FraudCheck) -> Self { Self { frm_id: &check.frm_id, payment_id: &check.payment_id, merchant_id: &check.merchant_id, attempt_id: &check.attempt_id, created_at: check.created_at.assume_utc(), frm_name: &check.frm_name, frm_transaction_id: check.frm_transaction_id.as_ref(), frm_transaction_type: check.frm_transaction_type, frm_status: check.frm_status, frm_score: check.frm_score, frm_reason: check.frm_reason.clone(), frm_error: check.frm_error.as_ref(), payment_details: check.payment_details.clone(), metadata: check.metadata.clone(), modified_at: check.modified_at.assume_utc(), last_step: check.last_step, payment_capture_method: check.payment_capture_method, } } } impl super::KafkaMessage for KafkaFraudCheckEvent<'_> { fn key(&self) -> String { format!( "{}_{}_{}_{}", self.merchant_id.get_string_repr(), self.payment_id.get_string_repr(), self.attempt_id, self.frm_id ) } fn event_type(&self) -> crate::events::EventType { crate::events::EventType::FraudCheck } }
crates/router/src/services/kafka/fraud_check_event.rs
router::src::services::kafka::fraud_check_event
659
true
// File: crates/router/src/services/kafka/refund.rs // Module: router::src::services::kafka::refund #[cfg(feature = "v2")] use common_utils::pii; #[cfg(feature = "v2")] use common_utils::types::{self, ChargeRefunds}; use common_utils::{ id_type, types::{ConnectorTransactionIdTrait, MinorUnit}, }; use diesel_models::{enums as storage_enums, refund::Refund}; use time::OffsetDateTime; use crate::events; #[cfg(feature = "v1")] #[derive(serde::Serialize, Debug)] pub struct KafkaRefund<'a> { pub internal_reference_id: &'a String, pub refund_id: &'a String, //merchant_reference id pub payment_id: &'a id_type::PaymentId, pub merchant_id: &'a id_type::MerchantId, pub connector_transaction_id: &'a String, pub connector: &'a String, pub connector_refund_id: Option<&'a String>, pub external_reference_id: Option<&'a String>, pub refund_type: &'a storage_enums::RefundType, pub total_amount: &'a MinorUnit, pub currency: &'a storage_enums::Currency, pub refund_amount: &'a MinorUnit, pub refund_status: &'a storage_enums::RefundStatus, pub sent_to_gateway: &'a bool, pub refund_error_message: Option<&'a String>, pub refund_arn: Option<&'a String>, #[serde(default, with = "time::serde::timestamp")] pub created_at: OffsetDateTime, #[serde(default, with = "time::serde::timestamp")] pub modified_at: OffsetDateTime, pub description: Option<&'a String>, pub attempt_id: &'a String, pub refund_reason: Option<&'a String>, pub refund_error_code: Option<&'a String>, pub profile_id: Option<&'a id_type::ProfileId>, pub organization_id: &'a id_type::OrganizationId, } #[cfg(feature = "v1")] impl<'a> KafkaRefund<'a> { pub fn from_storage(refund: &'a Refund) -> Self { Self { internal_reference_id: &refund.internal_reference_id, refund_id: &refund.refund_id, payment_id: &refund.payment_id, merchant_id: &refund.merchant_id, connector_transaction_id: refund.get_connector_transaction_id(), connector: &refund.connector, connector_refund_id: refund.get_optional_connector_refund_id(), external_reference_id: refund.external_reference_id.as_ref(), refund_type: &refund.refund_type, total_amount: &refund.total_amount, currency: &refund.currency, refund_amount: &refund.refund_amount, refund_status: &refund.refund_status, sent_to_gateway: &refund.sent_to_gateway, refund_error_message: refund.refund_error_message.as_ref(), refund_arn: refund.refund_arn.as_ref(), created_at: refund.created_at.assume_utc(), modified_at: refund.modified_at.assume_utc(), description: refund.description.as_ref(), attempt_id: &refund.attempt_id, refund_reason: refund.refund_reason.as_ref(), refund_error_code: refund.refund_error_code.as_ref(), profile_id: refund.profile_id.as_ref(), organization_id: &refund.organization_id, } } } #[cfg(feature = "v2")] #[derive(serde::Serialize, Debug)] pub struct KafkaRefund<'a> { pub refund_id: &'a id_type::GlobalRefundId, pub merchant_reference_id: &'a id_type::RefundReferenceId, pub payment_id: &'a id_type::GlobalPaymentId, pub merchant_id: &'a id_type::MerchantId, pub connector_transaction_id: &'a types::ConnectorTransactionId, pub connector: &'a String, pub connector_refund_id: Option<&'a types::ConnectorTransactionId>, pub external_reference_id: Option<&'a String>, pub refund_type: &'a storage_enums::RefundType, pub total_amount: &'a MinorUnit, pub currency: &'a storage_enums::Currency, pub refund_amount: &'a MinorUnit, pub refund_status: &'a storage_enums::RefundStatus, pub sent_to_gateway: &'a bool, pub refund_error_message: Option<&'a String>, pub refund_arn: Option<&'a String>, #[serde(default, with = "time::serde::timestamp")] pub created_at: OffsetDateTime, #[serde(default, with = "time::serde::timestamp")] pub modified_at: OffsetDateTime, pub description: Option<&'a String>, pub attempt_id: &'a id_type::GlobalAttemptId, pub refund_reason: Option<&'a String>, pub refund_error_code: Option<&'a String>, pub profile_id: Option<&'a id_type::ProfileId>, pub organization_id: &'a id_type::OrganizationId, pub metadata: Option<&'a pii::SecretSerdeValue>, pub updated_by: &'a String, pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>, pub charges: Option<&'a ChargeRefunds>, pub connector_refund_data: Option<&'a String>, pub connector_transaction_data: Option<&'a String>, pub split_refunds: Option<&'a common_types::refunds::SplitRefund>, pub unified_code: Option<&'a String>, pub unified_message: Option<&'a String>, pub processor_refund_data: Option<&'a String>, pub processor_transaction_data: Option<&'a String>, } #[cfg(feature = "v2")] impl<'a> KafkaRefund<'a> { pub fn from_storage(refund: &'a Refund) -> Self { let Refund { payment_id, merchant_id, connector_transaction_id, connector, connector_refund_id, external_reference_id, refund_type, total_amount, currency, refund_amount, refund_status, sent_to_gateway, refund_error_message, metadata, refund_arn, created_at, modified_at, description, attempt_id, refund_reason, refund_error_code, profile_id, updated_by, charges, organization_id, split_refunds, unified_code, unified_message, processor_refund_data, processor_transaction_data, id, merchant_reference_id, connector_id, } = refund; Self { refund_id: id, merchant_reference_id, payment_id, merchant_id, connector_transaction_id, connector, connector_refund_id: connector_refund_id.as_ref(), external_reference_id: external_reference_id.as_ref(), refund_type, total_amount, currency, refund_amount, refund_status, sent_to_gateway, refund_error_message: refund_error_message.as_ref(), refund_arn: refund_arn.as_ref(), created_at: created_at.assume_utc(), modified_at: modified_at.assume_utc(), description: description.as_ref(), attempt_id, refund_reason: refund_reason.as_ref(), refund_error_code: refund_error_code.as_ref(), profile_id: profile_id.as_ref(), organization_id, metadata: metadata.as_ref(), updated_by, merchant_connector_id: connector_id.as_ref(), charges: charges.as_ref(), connector_refund_data: processor_refund_data.as_ref(), connector_transaction_data: processor_transaction_data.as_ref(), split_refunds: split_refunds.as_ref(), unified_code: unified_code.as_ref(), unified_message: unified_message.as_ref(), processor_refund_data: processor_refund_data.as_ref(), processor_transaction_data: processor_transaction_data.as_ref(), } } } impl super::KafkaMessage for KafkaRefund<'_> { #[cfg(feature = "v1")] fn key(&self) -> String { format!( "{}_{}_{}_{}", self.merchant_id.get_string_repr(), self.payment_id.get_string_repr(), self.attempt_id, self.refund_id ) } #[cfg(feature = "v2")] fn key(&self) -> String { format!( "{}_{}_{}_{}", self.merchant_id.get_string_repr(), self.payment_id.get_string_repr(), self.attempt_id.get_string_repr(), self.merchant_reference_id.get_string_repr() ) } fn event_type(&self) -> events::EventType { events::EventType::Refund } }
crates/router/src/services/kafka/refund.rs
router::src::services::kafka::refund
1,849
true
// File: crates/router/src/services/kafka/payment_intent_event.rs // Module: router::src::services::kafka::payment_intent_event #[cfg(feature = "v2")] use ::common_types::{ payments, primitive_wrappers::{EnablePartialAuthorizationBool, RequestExtendedAuthorizationBool}, }; #[cfg(feature = "v2")] use common_enums::{self, RequestIncrementalAuthorization}; use common_utils::{ crypto::Encryptable, hashing::HashedString, id_type, pii, types as common_types, }; use diesel_models::enums as storage_enums; #[cfg(feature = "v2")] use diesel_models::{types as diesel_types, PaymentLinkConfigRequestForPayments}; #[cfg(feature = "v2")] use diesel_models::{types::OrderDetailsWithAmount, TaxDetails}; use hyperswitch_domain_models::payments::PaymentIntent; #[cfg(feature = "v2")] use hyperswitch_domain_models::{address, routing}; use masking::{PeekInterface, Secret}; use serde_json::Value; use time::OffsetDateTime; #[cfg(feature = "v1")] #[serde_with::skip_serializing_none] #[derive(serde::Serialize, Debug)] pub struct KafkaPaymentIntentEvent<'a> { pub payment_id: &'a id_type::PaymentId, pub merchant_id: &'a id_type::MerchantId, pub status: storage_enums::IntentStatus, pub amount: common_types::MinorUnit, pub currency: Option<storage_enums::Currency>, pub amount_captured: Option<common_types::MinorUnit>, pub customer_id: Option<&'a id_type::CustomerId>, pub description: Option<&'a String>, pub return_url: Option<&'a String>, pub metadata: Option<String>, pub connector_id: Option<&'a String>, pub statement_descriptor_name: Option<&'a String>, pub statement_descriptor_suffix: Option<&'a String>, #[serde(with = "time::serde::timestamp::nanoseconds")] pub created_at: OffsetDateTime, #[serde(with = "time::serde::timestamp::nanoseconds")] pub modified_at: OffsetDateTime, #[serde(default, with = "time::serde::timestamp::nanoseconds::option")] pub last_synced: Option<OffsetDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, pub client_secret: Option<&'a String>, pub active_attempt_id: String, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<&'a String>, pub attempt_count: i16, pub profile_id: Option<&'a id_type::ProfileId>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, pub billing_details: Option<Encryptable<Secret<Value>>>, pub shipping_details: Option<Encryptable<Secret<Value>>>, pub customer_email: Option<HashedString<pii::EmailStrategy>>, pub feature_metadata: Option<&'a Value>, pub merchant_order_reference_id: Option<&'a String>, pub organization_id: &'a id_type::OrganizationId, #[serde(flatten)] pub infra_values: Option<Value>, } #[cfg(feature = "v2")] #[serde_with::skip_serializing_none] #[derive(serde::Serialize, Debug)] pub struct KafkaPaymentIntentEvent<'a> { pub payment_id: &'a id_type::GlobalPaymentId, pub merchant_id: &'a id_type::MerchantId, pub status: storage_enums::IntentStatus, pub amount: common_types::MinorUnit, pub currency: storage_enums::Currency, pub amount_captured: Option<common_types::MinorUnit>, pub customer_id: Option<&'a id_type::GlobalCustomerId>, pub description: Option<&'a common_types::Description>, pub return_url: Option<&'a common_types::Url>, pub metadata: Option<&'a Secret<Value>>, pub statement_descriptor: Option<&'a common_types::StatementDescriptor>, #[serde(with = "time::serde::timestamp::nanoseconds")] pub created_at: OffsetDateTime, #[serde(with = "time::serde::timestamp::nanoseconds")] pub modified_at: OffsetDateTime, #[serde(default, with = "time::serde::timestamp::nanoseconds::option")] pub last_synced: Option<OffsetDateTime>, pub setup_future_usage: storage_enums::FutureUsage, pub off_session: bool, pub active_attempt_id: Option<&'a id_type::GlobalAttemptId>, pub active_attempt_id_type: common_enums::ActiveAttemptIDType, pub active_attempts_group_id: Option<&'a String>, pub attempt_count: i16, pub profile_id: &'a id_type::ProfileId, pub customer_email: Option<HashedString<pii::EmailStrategy>>, pub feature_metadata: Option<&'a diesel_types::FeatureMetadata>, pub organization_id: &'a id_type::OrganizationId, pub order_details: Option<&'a Vec<Secret<OrderDetailsWithAmount>>>, pub allowed_payment_method_types: Option<&'a Vec<common_enums::PaymentMethodType>>, pub connector_metadata: Option<&'a api_models::payments::ConnectorMetadata>, pub payment_link_id: Option<&'a String>, pub updated_by: &'a String, pub surcharge_applicable: Option<bool>, pub request_incremental_authorization: RequestIncrementalAuthorization, pub split_txns_enabled: common_enums::SplitTxnsEnabled, pub authorization_count: Option<i32>, #[serde(with = "time::serde::timestamp::nanoseconds")] pub session_expiry: OffsetDateTime, pub request_external_three_ds_authentication: common_enums::External3dsAuthenticationRequest, pub frm_metadata: Option<Secret<&'a Value>>, pub customer_details: Option<Secret<&'a Value>>, pub shipping_cost: Option<common_types::MinorUnit>, pub tax_details: Option<TaxDetails>, pub skip_external_tax_calculation: bool, pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>, pub split_payments: Option<&'a payments::SplitPaymentsRequest>, pub platform_merchant_id: Option<&'a id_type::MerchantId>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, pub processor_merchant_id: &'a id_type::MerchantId, pub created_by: Option<&'a common_types::CreatedBy>, pub is_iframe_redirection_enabled: Option<bool>, pub merchant_reference_id: Option<&'a id_type::PaymentReferenceId>, pub capture_method: storage_enums::CaptureMethod, pub authentication_type: Option<common_enums::AuthenticationType>, pub prerouting_algorithm: Option<&'a routing::PaymentRoutingInfo>, pub surcharge_amount: Option<common_types::MinorUnit>, pub billing_address: Option<Secret<&'a address::Address>>, pub shipping_address: Option<Secret<&'a address::Address>>, pub tax_on_surcharge: Option<common_types::MinorUnit>, pub frm_merchant_decision: Option<common_enums::MerchantDecision>, pub enable_payment_link: common_enums::EnablePaymentLinkRequest, pub apply_mit_exemption: common_enums::MitExemptionRequest, pub customer_present: common_enums::PresenceOfCustomerDuringPayment, pub routing_algorithm_id: Option<&'a id_type::RoutingId>, pub payment_link_config: Option<&'a PaymentLinkConfigRequestForPayments>, pub enable_partial_authorization: Option<EnablePartialAuthorizationBool>, #[serde(flatten)] infra_values: Option<Value>, } impl KafkaPaymentIntentEvent<'_> { #[cfg(feature = "v1")] pub fn get_id(&self) -> &id_type::PaymentId { self.payment_id } #[cfg(feature = "v2")] pub fn get_id(&self) -> &id_type::GlobalPaymentId { self.payment_id } } #[cfg(feature = "v1")] impl<'a> KafkaPaymentIntentEvent<'a> { pub fn from_storage(intent: &'a PaymentIntent, infra_values: Option<Value>) -> Self { Self { payment_id: &intent.payment_id, merchant_id: &intent.merchant_id, status: intent.status, amount: intent.amount, currency: intent.currency, amount_captured: intent.amount_captured, customer_id: intent.customer_id.as_ref(), description: intent.description.as_ref(), return_url: intent.return_url.as_ref(), metadata: intent.metadata.as_ref().map(|x| x.to_string()), connector_id: intent.connector_id.as_ref(), statement_descriptor_name: intent.statement_descriptor_name.as_ref(), statement_descriptor_suffix: intent.statement_descriptor_suffix.as_ref(), created_at: intent.created_at.assume_utc(), modified_at: intent.modified_at.assume_utc(), last_synced: intent.last_synced.map(|i| i.assume_utc()), setup_future_usage: intent.setup_future_usage, off_session: intent.off_session, client_secret: intent.client_secret.as_ref(), active_attempt_id: intent.active_attempt.get_id(), business_country: intent.business_country, business_label: intent.business_label.as_ref(), attempt_count: intent.attempt_count, profile_id: intent.profile_id.as_ref(), payment_confirm_source: intent.payment_confirm_source, // TODO: use typed information here to avoid PII logging billing_details: None, shipping_details: None, customer_email: intent .customer_details .as_ref() .and_then(|value| value.get_inner().peek().as_object()) .and_then(|obj| obj.get("email")) .and_then(|email| email.as_str()) .map(|email| HashedString::from(Secret::new(email.to_string()))), feature_metadata: intent.feature_metadata.as_ref(), merchant_order_reference_id: intent.merchant_order_reference_id.as_ref(), organization_id: &intent.organization_id, infra_values: infra_values.clone(), } } } #[cfg(feature = "v2")] impl<'a> KafkaPaymentIntentEvent<'a> { pub fn from_storage(intent: &'a PaymentIntent, infra_values: Option<Value>) -> Self { let PaymentIntent { id, merchant_id, status, amount_details, amount_captured, customer_id, description, return_url, metadata, statement_descriptor, created_at, modified_at, last_synced, setup_future_usage, active_attempt_id, active_attempt_id_type, active_attempts_group_id, order_details, allowed_payment_method_types, connector_metadata, feature_metadata, attempt_count, profile_id, payment_link_id, frm_merchant_decision, updated_by, request_incremental_authorization, split_txns_enabled, authorization_count, session_expiry, request_external_three_ds_authentication, frm_metadata, customer_details, merchant_reference_id, billing_address, shipping_address, capture_method, authentication_type, prerouting_algorithm, organization_id, enable_payment_link, apply_mit_exemption, customer_present, payment_link_config, routing_algorithm_id, split_payments, force_3ds_challenge, force_3ds_challenge_trigger, processor_merchant_id, created_by, is_iframe_redirection_enabled, is_payment_id_from_merchant, enable_partial_authorization, } = intent; Self { payment_id: id, merchant_id, status: *status, amount: amount_details.order_amount, currency: amount_details.currency, amount_captured: *amount_captured, customer_id: customer_id.as_ref(), description: description.as_ref(), return_url: return_url.as_ref(), metadata: metadata.as_ref(), statement_descriptor: statement_descriptor.as_ref(), created_at: created_at.assume_utc(), modified_at: modified_at.assume_utc(), last_synced: last_synced.map(|t| t.assume_utc()), setup_future_usage: *setup_future_usage, off_session: setup_future_usage.is_off_session(), active_attempt_id: active_attempt_id.as_ref(), active_attempt_id_type: *active_attempt_id_type, active_attempts_group_id: active_attempts_group_id.as_ref(), attempt_count: *attempt_count, profile_id, customer_email: None, feature_metadata: feature_metadata.as_ref(), organization_id, order_details: order_details.as_ref(), allowed_payment_method_types: allowed_payment_method_types.as_ref(), connector_metadata: connector_metadata.as_ref(), payment_link_id: payment_link_id.as_ref(), updated_by, surcharge_applicable: None, request_incremental_authorization: *request_incremental_authorization, split_txns_enabled: *split_txns_enabled, authorization_count: *authorization_count, session_expiry: session_expiry.assume_utc(), request_external_three_ds_authentication: *request_external_three_ds_authentication, frm_metadata: frm_metadata .as_ref() .map(|frm_metadata| frm_metadata.as_ref()), customer_details: customer_details .as_ref() .map(|customer_details| customer_details.get_inner().as_ref()), shipping_cost: amount_details.shipping_cost, tax_details: amount_details.tax_details.clone(), skip_external_tax_calculation: amount_details.get_external_tax_action_as_bool(), request_extended_authorization: None, psd2_sca_exemption_type: None, split_payments: split_payments.as_ref(), platform_merchant_id: None, force_3ds_challenge: *force_3ds_challenge, force_3ds_challenge_trigger: *force_3ds_challenge_trigger, processor_merchant_id, created_by: created_by.as_ref(), is_iframe_redirection_enabled: *is_iframe_redirection_enabled, merchant_reference_id: merchant_reference_id.as_ref(), billing_address: billing_address .as_ref() .map(|billing_address| Secret::new(billing_address.get_inner())), shipping_address: shipping_address .as_ref() .map(|shipping_address| Secret::new(shipping_address.get_inner())), capture_method: *capture_method, authentication_type: *authentication_type, prerouting_algorithm: prerouting_algorithm.as_ref(), surcharge_amount: amount_details.surcharge_amount, tax_on_surcharge: amount_details.tax_on_surcharge, frm_merchant_decision: *frm_merchant_decision, enable_payment_link: *enable_payment_link, apply_mit_exemption: *apply_mit_exemption, customer_present: *customer_present, routing_algorithm_id: routing_algorithm_id.as_ref(), payment_link_config: payment_link_config.as_ref(), infra_values, enable_partial_authorization: *enable_partial_authorization, } } } impl super::KafkaMessage for KafkaPaymentIntentEvent<'_> { fn key(&self) -> String { format!( "{}_{}", self.merchant_id.get_string_repr(), self.get_id().get_string_repr(), ) } fn event_type(&self) -> crate::events::EventType { crate::events::EventType::PaymentIntent } }
crates/router/src/services/kafka/payment_intent_event.rs
router::src::services::kafka::payment_intent_event
3,285
true
// File: crates/router/src/services/kafka/authentication_event.rs // Module: router::src::services::kafka::authentication_event use diesel_models::{authentication::Authentication, enums as storage_enums}; use time::OffsetDateTime; #[serde_with::skip_serializing_none] #[derive(serde::Serialize, Debug)] pub struct KafkaAuthenticationEvent<'a> { pub authentication_id: &'a common_utils::id_type::AuthenticationId, pub merchant_id: &'a common_utils::id_type::MerchantId, pub authentication_connector: Option<&'a String>, pub connector_authentication_id: Option<&'a String>, pub authentication_data: Option<serde_json::Value>, pub payment_method_id: &'a String, pub authentication_type: Option<storage_enums::DecoupledAuthenticationType>, pub authentication_status: storage_enums::AuthenticationStatus, pub authentication_lifecycle_status: storage_enums::AuthenticationLifecycleStatus, #[serde(default, with = "time::serde::timestamp::milliseconds")] pub created_at: OffsetDateTime, #[serde(default, with = "time::serde::timestamp::milliseconds")] pub modified_at: OffsetDateTime, pub error_message: Option<&'a String>, pub error_code: Option<&'a String>, pub connector_metadata: Option<serde_json::Value>, pub maximum_supported_version: Option<common_utils::types::SemanticVersion>, pub threeds_server_transaction_id: Option<&'a String>, pub cavv: Option<&'a String>, pub authentication_flow_type: Option<&'a String>, pub message_version: Option<common_utils::types::SemanticVersion>, pub eci: Option<&'a String>, pub trans_status: Option<storage_enums::TransactionStatus>, pub acquirer_bin: Option<&'a String>, pub acquirer_merchant_id: Option<&'a String>, pub three_ds_method_data: Option<&'a String>, pub three_ds_method_url: Option<&'a String>, pub acs_url: Option<&'a String>, pub challenge_request: Option<&'a String>, pub acs_reference_number: Option<&'a String>, pub acs_trans_id: Option<&'a String>, pub acs_signed_content: Option<&'a String>, pub profile_id: &'a common_utils::id_type::ProfileId, pub payment_id: Option<&'a common_utils::id_type::PaymentId>, pub merchant_connector_id: Option<&'a common_utils::id_type::MerchantConnectorAccountId>, pub ds_trans_id: Option<&'a String>, pub directory_server_id: Option<&'a String>, pub acquirer_country_code: Option<&'a String>, pub organization_id: &'a common_utils::id_type::OrganizationId, } impl<'a> KafkaAuthenticationEvent<'a> { pub fn from_storage(authentication: &'a Authentication) -> Self { Self { created_at: authentication.created_at.assume_utc(), modified_at: authentication.modified_at.assume_utc(), authentication_id: &authentication.authentication_id, merchant_id: &authentication.merchant_id, authentication_status: authentication.authentication_status, authentication_connector: authentication.authentication_connector.as_ref(), connector_authentication_id: authentication.connector_authentication_id.as_ref(), authentication_data: authentication.authentication_data.clone(), payment_method_id: &authentication.payment_method_id, authentication_type: authentication.authentication_type, authentication_lifecycle_status: authentication.authentication_lifecycle_status, error_code: authentication.error_code.as_ref(), error_message: authentication.error_message.as_ref(), connector_metadata: authentication.connector_metadata.clone(), maximum_supported_version: authentication.maximum_supported_version.clone(), threeds_server_transaction_id: authentication.threeds_server_transaction_id.as_ref(), cavv: authentication.cavv.as_ref(), authentication_flow_type: authentication.authentication_flow_type.as_ref(), message_version: authentication.message_version.clone(), eci: authentication.eci.as_ref(), trans_status: authentication.trans_status.clone(), acquirer_bin: authentication.acquirer_bin.as_ref(), acquirer_merchant_id: authentication.acquirer_merchant_id.as_ref(), three_ds_method_data: authentication.three_ds_method_data.as_ref(), three_ds_method_url: authentication.three_ds_method_url.as_ref(), acs_url: authentication.acs_url.as_ref(), challenge_request: authentication.challenge_request.as_ref(), acs_reference_number: authentication.acs_reference_number.as_ref(), acs_trans_id: authentication.acs_trans_id.as_ref(), acs_signed_content: authentication.acs_signed_content.as_ref(), profile_id: &authentication.profile_id, payment_id: authentication.payment_id.as_ref(), merchant_connector_id: authentication.merchant_connector_id.as_ref(), ds_trans_id: authentication.ds_trans_id.as_ref(), directory_server_id: authentication.directory_server_id.as_ref(), acquirer_country_code: authentication.acquirer_country_code.as_ref(), organization_id: &authentication.organization_id, } } } impl super::KafkaMessage for KafkaAuthenticationEvent<'_> { fn key(&self) -> String { format!( "{}_{}", self.merchant_id.get_string_repr(), self.authentication_id.get_string_repr() ) } fn event_type(&self) -> crate::events::EventType { crate::events::EventType::Authentication } }
crates/router/src/services/kafka/authentication_event.rs
router::src::services::kafka::authentication_event
1,127
true
// File: crates/router/src/services/kafka/revenue_recovery.rs // Module: router::src::services::kafka::revenue_recovery use common_utils::{id_type, types::MinorUnit}; use masking::Secret; use time::OffsetDateTime; #[derive(serde::Serialize, Debug)] pub struct RevenueRecovery<'a> { pub merchant_id: &'a id_type::MerchantId, pub invoice_amount: MinorUnit, pub invoice_currency: &'a common_enums::Currency, #[serde(default, with = "time::serde::timestamp::nanoseconds::option")] pub invoice_due_date: Option<OffsetDateTime>, #[serde(with = "time::serde::timestamp::nanoseconds::option")] pub invoice_date: Option<OffsetDateTime>, pub billing_country: Option<&'a common_enums::CountryAlpha2>, pub billing_state: Option<Secret<String>>, pub billing_city: Option<Secret<String>>, pub attempt_amount: MinorUnit, pub attempt_currency: &'a common_enums::Currency, pub attempt_status: &'a common_enums::AttemptStatus, pub pg_error_code: Option<String>, pub network_advice_code: Option<String>, pub network_error_code: Option<String>, pub first_pg_error_code: Option<String>, pub first_network_advice_code: Option<String>, pub first_network_error_code: Option<String>, #[serde(default, with = "time::serde::timestamp::nanoseconds")] pub attempt_created_at: OffsetDateTime, pub payment_method_type: Option<&'a common_enums::PaymentMethod>, pub payment_method_subtype: Option<&'a common_enums::PaymentMethodType>, pub card_network: Option<&'a common_enums::CardNetwork>, pub card_issuer: Option<String>, pub retry_count: Option<i32>, pub payment_gateway: Option<common_enums::connector_enums::Connector>, } impl super::KafkaMessage for RevenueRecovery<'_> { fn key(&self) -> String { self.merchant_id.get_string_repr().to_string() } fn event_type(&self) -> crate::events::EventType { crate::events::EventType::RevenueRecovery } }
crates/router/src/services/kafka/revenue_recovery.rs
router::src::services::kafka::revenue_recovery
471
true
// File: crates/router/src/services/kafka/authentication.rs // Module: router::src::services::kafka::authentication use diesel_models::{authentication::Authentication, enums as storage_enums}; use time::OffsetDateTime; #[derive(serde::Serialize, Debug)] pub struct KafkaAuthentication<'a> { pub authentication_id: &'a common_utils::id_type::AuthenticationId, pub merchant_id: &'a common_utils::id_type::MerchantId, pub authentication_connector: Option<&'a String>, pub connector_authentication_id: Option<&'a String>, pub authentication_data: Option<serde_json::Value>, pub payment_method_id: &'a String, pub authentication_type: Option<storage_enums::DecoupledAuthenticationType>, pub authentication_status: storage_enums::AuthenticationStatus, pub authentication_lifecycle_status: storage_enums::AuthenticationLifecycleStatus, #[serde(default, with = "time::serde::timestamp::milliseconds")] pub created_at: OffsetDateTime, #[serde(default, with = "time::serde::timestamp::milliseconds")] pub modified_at: OffsetDateTime, pub error_message: Option<&'a String>, pub error_code: Option<&'a String>, pub connector_metadata: Option<serde_json::Value>, pub maximum_supported_version: Option<common_utils::types::SemanticVersion>, pub threeds_server_transaction_id: Option<&'a String>, pub cavv: Option<&'a String>, pub authentication_flow_type: Option<&'a String>, pub message_version: Option<common_utils::types::SemanticVersion>, pub eci: Option<&'a String>, pub trans_status: Option<storage_enums::TransactionStatus>, pub acquirer_bin: Option<&'a String>, pub acquirer_merchant_id: Option<&'a String>, pub three_ds_method_data: Option<&'a String>, pub three_ds_method_url: Option<&'a String>, pub acs_url: Option<&'a String>, pub challenge_request: Option<&'a String>, pub acs_reference_number: Option<&'a String>, pub acs_trans_id: Option<&'a String>, pub acs_signed_content: Option<&'a String>, pub profile_id: &'a common_utils::id_type::ProfileId, pub payment_id: Option<&'a common_utils::id_type::PaymentId>, pub merchant_connector_id: Option<&'a common_utils::id_type::MerchantConnectorAccountId>, pub ds_trans_id: Option<&'a String>, pub directory_server_id: Option<&'a String>, pub acquirer_country_code: Option<&'a String>, pub organization_id: &'a common_utils::id_type::OrganizationId, } impl<'a> KafkaAuthentication<'a> { pub fn from_storage(authentication: &'a Authentication) -> Self { Self { created_at: authentication.created_at.assume_utc(), modified_at: authentication.modified_at.assume_utc(), authentication_id: &authentication.authentication_id, merchant_id: &authentication.merchant_id, authentication_status: authentication.authentication_status, authentication_connector: authentication.authentication_connector.as_ref(), connector_authentication_id: authentication.connector_authentication_id.as_ref(), authentication_data: authentication.authentication_data.clone(), payment_method_id: &authentication.payment_method_id, authentication_type: authentication.authentication_type, authentication_lifecycle_status: authentication.authentication_lifecycle_status, error_code: authentication.error_code.as_ref(), error_message: authentication.error_message.as_ref(), connector_metadata: authentication.connector_metadata.clone(), maximum_supported_version: authentication.maximum_supported_version.clone(), threeds_server_transaction_id: authentication.threeds_server_transaction_id.as_ref(), cavv: authentication.cavv.as_ref(), authentication_flow_type: authentication.authentication_flow_type.as_ref(), message_version: authentication.message_version.clone(), eci: authentication.eci.as_ref(), trans_status: authentication.trans_status.clone(), acquirer_bin: authentication.acquirer_bin.as_ref(), acquirer_merchant_id: authentication.acquirer_merchant_id.as_ref(), three_ds_method_data: authentication.three_ds_method_data.as_ref(), three_ds_method_url: authentication.three_ds_method_url.as_ref(), acs_url: authentication.acs_url.as_ref(), challenge_request: authentication.challenge_request.as_ref(), acs_reference_number: authentication.acs_reference_number.as_ref(), acs_trans_id: authentication.acs_trans_id.as_ref(), acs_signed_content: authentication.acs_signed_content.as_ref(), profile_id: &authentication.profile_id, payment_id: authentication.payment_id.as_ref(), merchant_connector_id: authentication.merchant_connector_id.as_ref(), ds_trans_id: authentication.ds_trans_id.as_ref(), directory_server_id: authentication.directory_server_id.as_ref(), acquirer_country_code: authentication.acquirer_country_code.as_ref(), organization_id: &authentication.organization_id, } } } impl super::KafkaMessage for KafkaAuthentication<'_> { fn key(&self) -> String { format!( "{}_{}", self.merchant_id.get_string_repr(), self.authentication_id.get_string_repr() ) } fn event_type(&self) -> crate::events::EventType { crate::events::EventType::Authentication } }
crates/router/src/services/kafka/authentication.rs
router::src::services::kafka::authentication
1,113
true
// File: crates/router/src/services/kafka/payment_intent.rs // Module: router::src::services::kafka::payment_intent #[cfg(feature = "v2")] use ::common_types::{ payments, primitive_wrappers::{EnablePartialAuthorizationBool, RequestExtendedAuthorizationBool}, }; #[cfg(feature = "v2")] use common_enums; #[cfg(feature = "v2")] use common_enums::RequestIncrementalAuthorization; use common_utils::{ crypto::Encryptable, hashing::HashedString, id_type, pii, types as common_types, }; use diesel_models::enums as storage_enums; #[cfg(feature = "v2")] use diesel_models::{types as diesel_types, PaymentLinkConfigRequestForPayments}; #[cfg(feature = "v2")] use diesel_models::{types::OrderDetailsWithAmount, TaxDetails}; use hyperswitch_domain_models::payments::PaymentIntent; #[cfg(feature = "v2")] use hyperswitch_domain_models::{address, routing}; use masking::{PeekInterface, Secret}; use serde_json::Value; use time::OffsetDateTime; #[cfg(feature = "v1")] #[derive(serde::Serialize, Debug)] pub struct KafkaPaymentIntent<'a> { pub payment_id: &'a id_type::PaymentId, pub merchant_id: &'a id_type::MerchantId, pub status: storage_enums::IntentStatus, pub amount: common_types::MinorUnit, pub currency: Option<storage_enums::Currency>, pub amount_captured: Option<common_types::MinorUnit>, pub customer_id: Option<&'a id_type::CustomerId>, pub description: Option<&'a String>, pub return_url: Option<&'a String>, pub metadata: Option<String>, pub connector_id: Option<&'a String>, pub statement_descriptor_name: Option<&'a String>, pub statement_descriptor_suffix: Option<&'a String>, #[serde(with = "time::serde::timestamp")] pub created_at: OffsetDateTime, #[serde(with = "time::serde::timestamp")] pub modified_at: OffsetDateTime, #[serde(default, with = "time::serde::timestamp::option")] pub last_synced: Option<OffsetDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, pub client_secret: Option<&'a String>, pub active_attempt_id: String, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<&'a String>, pub attempt_count: i16, pub profile_id: Option<&'a id_type::ProfileId>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, pub billing_details: Option<Encryptable<Secret<Value>>>, pub shipping_details: Option<Encryptable<Secret<Value>>>, pub customer_email: Option<HashedString<pii::EmailStrategy>>, pub feature_metadata: Option<&'a Value>, pub merchant_order_reference_id: Option<&'a String>, pub organization_id: &'a id_type::OrganizationId, #[serde(flatten)] infra_values: Option<Value>, } #[cfg(feature = "v1")] impl<'a> KafkaPaymentIntent<'a> { pub fn from_storage(intent: &'a PaymentIntent, infra_values: Option<Value>) -> Self { Self { payment_id: &intent.payment_id, merchant_id: &intent.merchant_id, status: intent.status, amount: intent.amount, currency: intent.currency, amount_captured: intent.amount_captured, customer_id: intent.customer_id.as_ref(), description: intent.description.as_ref(), return_url: intent.return_url.as_ref(), metadata: intent.metadata.as_ref().map(|x| x.to_string()), connector_id: intent.connector_id.as_ref(), statement_descriptor_name: intent.statement_descriptor_name.as_ref(), statement_descriptor_suffix: intent.statement_descriptor_suffix.as_ref(), created_at: intent.created_at.assume_utc(), modified_at: intent.modified_at.assume_utc(), last_synced: intent.last_synced.map(|i| i.assume_utc()), setup_future_usage: intent.setup_future_usage, off_session: intent.off_session, client_secret: intent.client_secret.as_ref(), active_attempt_id: intent.active_attempt.get_id(), business_country: intent.business_country, business_label: intent.business_label.as_ref(), attempt_count: intent.attempt_count, profile_id: intent.profile_id.as_ref(), payment_confirm_source: intent.payment_confirm_source, // TODO: use typed information here to avoid PII logging billing_details: None, shipping_details: None, customer_email: intent .customer_details .as_ref() .and_then(|value| value.get_inner().peek().as_object()) .and_then(|obj| obj.get("email")) .and_then(|email| email.as_str()) .map(|email| HashedString::from(Secret::new(email.to_string()))), feature_metadata: intent.feature_metadata.as_ref(), merchant_order_reference_id: intent.merchant_order_reference_id.as_ref(), organization_id: &intent.organization_id, infra_values, } } } #[cfg(feature = "v2")] #[derive(serde::Serialize, Debug)] pub struct KafkaPaymentIntent<'a> { pub payment_id: &'a id_type::GlobalPaymentId, pub merchant_id: &'a id_type::MerchantId, pub status: storage_enums::IntentStatus, pub amount: common_types::MinorUnit, pub currency: storage_enums::Currency, pub amount_captured: Option<common_types::MinorUnit>, pub customer_id: Option<&'a id_type::GlobalCustomerId>, pub description: Option<&'a common_types::Description>, pub return_url: Option<&'a common_types::Url>, pub metadata: Option<&'a Secret<Value>>, pub statement_descriptor: Option<&'a common_types::StatementDescriptor>, #[serde(with = "time::serde::timestamp")] pub created_at: OffsetDateTime, #[serde(with = "time::serde::timestamp")] pub modified_at: OffsetDateTime, #[serde(default, with = "time::serde::timestamp::option")] pub last_synced: Option<OffsetDateTime>, pub setup_future_usage: storage_enums::FutureUsage, pub off_session: bool, pub active_attempt_id: Option<&'a id_type::GlobalAttemptId>, pub active_attempt_id_type: common_enums::ActiveAttemptIDType, pub active_attempts_group_id: Option<&'a String>, pub attempt_count: i16, pub profile_id: &'a id_type::ProfileId, pub customer_email: Option<HashedString<pii::EmailStrategy>>, pub feature_metadata: Option<&'a diesel_types::FeatureMetadata>, pub organization_id: &'a id_type::OrganizationId, pub order_details: Option<&'a Vec<Secret<OrderDetailsWithAmount>>>, pub allowed_payment_method_types: Option<&'a Vec<common_enums::PaymentMethodType>>, pub connector_metadata: Option<&'a api_models::payments::ConnectorMetadata>, pub payment_link_id: Option<&'a String>, pub updated_by: &'a String, pub surcharge_applicable: Option<bool>, pub request_incremental_authorization: RequestIncrementalAuthorization, pub split_txns_enabled: common_enums::SplitTxnsEnabled, pub authorization_count: Option<i32>, #[serde(with = "time::serde::timestamp")] pub session_expiry: OffsetDateTime, pub request_external_three_ds_authentication: common_enums::External3dsAuthenticationRequest, pub frm_metadata: Option<Secret<&'a Value>>, pub customer_details: Option<Secret<&'a Value>>, pub shipping_cost: Option<common_types::MinorUnit>, pub tax_details: Option<TaxDetails>, pub skip_external_tax_calculation: bool, pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>, pub split_payments: Option<&'a payments::SplitPaymentsRequest>, pub platform_merchant_id: Option<&'a id_type::MerchantId>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, pub processor_merchant_id: &'a id_type::MerchantId, pub created_by: Option<&'a common_types::CreatedBy>, pub is_iframe_redirection_enabled: Option<bool>, pub merchant_reference_id: Option<&'a id_type::PaymentReferenceId>, pub capture_method: storage_enums::CaptureMethod, pub authentication_type: Option<common_enums::AuthenticationType>, pub prerouting_algorithm: Option<&'a routing::PaymentRoutingInfo>, pub surcharge_amount: Option<common_types::MinorUnit>, pub billing_address: Option<Secret<&'a address::Address>>, pub shipping_address: Option<Secret<&'a address::Address>>, pub tax_on_surcharge: Option<common_types::MinorUnit>, pub frm_merchant_decision: Option<common_enums::MerchantDecision>, pub enable_payment_link: common_enums::EnablePaymentLinkRequest, pub apply_mit_exemption: common_enums::MitExemptionRequest, pub customer_present: common_enums::PresenceOfCustomerDuringPayment, pub routing_algorithm_id: Option<&'a id_type::RoutingId>, pub payment_link_config: Option<&'a PaymentLinkConfigRequestForPayments>, pub enable_partial_authorization: Option<EnablePartialAuthorizationBool>, #[serde(flatten)] infra_values: Option<Value>, } #[cfg(feature = "v2")] impl<'a> KafkaPaymentIntent<'a> { pub fn from_storage(intent: &'a PaymentIntent, infra_values: Option<Value>) -> Self { let PaymentIntent { id, merchant_id, status, amount_details, amount_captured, customer_id, description, return_url, metadata, statement_descriptor, created_at, modified_at, last_synced, setup_future_usage, active_attempt_id, active_attempt_id_type, active_attempts_group_id, order_details, allowed_payment_method_types, connector_metadata, feature_metadata, attempt_count, profile_id, payment_link_id, frm_merchant_decision, updated_by, request_incremental_authorization, split_txns_enabled, authorization_count, session_expiry, request_external_three_ds_authentication, frm_metadata, customer_details, merchant_reference_id, billing_address, shipping_address, capture_method, authentication_type, prerouting_algorithm, organization_id, enable_payment_link, apply_mit_exemption, customer_present, payment_link_config, routing_algorithm_id, split_payments, force_3ds_challenge, force_3ds_challenge_trigger, processor_merchant_id, created_by, is_iframe_redirection_enabled, is_payment_id_from_merchant, enable_partial_authorization, } = intent; Self { payment_id: id, merchant_id, status: *status, amount: amount_details.order_amount, currency: amount_details.currency, amount_captured: *amount_captured, customer_id: customer_id.as_ref(), description: description.as_ref(), return_url: return_url.as_ref(), metadata: metadata.as_ref(), statement_descriptor: statement_descriptor.as_ref(), created_at: created_at.assume_utc(), modified_at: modified_at.assume_utc(), last_synced: last_synced.map(|t| t.assume_utc()), setup_future_usage: *setup_future_usage, off_session: setup_future_usage.is_off_session(), active_attempt_id: active_attempt_id.as_ref(), active_attempt_id_type: *active_attempt_id_type, active_attempts_group_id: active_attempts_group_id.as_ref(), attempt_count: *attempt_count, profile_id, customer_email: None, feature_metadata: feature_metadata.as_ref(), organization_id, order_details: order_details.as_ref(), allowed_payment_method_types: allowed_payment_method_types.as_ref(), connector_metadata: connector_metadata.as_ref(), payment_link_id: payment_link_id.as_ref(), updated_by, surcharge_applicable: None, request_incremental_authorization: *request_incremental_authorization, split_txns_enabled: *split_txns_enabled, authorization_count: *authorization_count, session_expiry: session_expiry.assume_utc(), request_external_three_ds_authentication: *request_external_three_ds_authentication, frm_metadata: frm_metadata .as_ref() .map(|frm_metadata| frm_metadata.as_ref()), customer_details: customer_details .as_ref() .map(|customer_details| customer_details.get_inner().as_ref()), shipping_cost: amount_details.shipping_cost, tax_details: amount_details.tax_details.clone(), skip_external_tax_calculation: amount_details.get_external_tax_action_as_bool(), request_extended_authorization: None, psd2_sca_exemption_type: None, split_payments: split_payments.as_ref(), platform_merchant_id: None, force_3ds_challenge: *force_3ds_challenge, force_3ds_challenge_trigger: *force_3ds_challenge_trigger, processor_merchant_id, created_by: created_by.as_ref(), is_iframe_redirection_enabled: *is_iframe_redirection_enabled, merchant_reference_id: merchant_reference_id.as_ref(), billing_address: billing_address .as_ref() .map(|billing_address| Secret::new(billing_address.get_inner())), shipping_address: shipping_address .as_ref() .map(|shipping_address| Secret::new(shipping_address.get_inner())), capture_method: *capture_method, authentication_type: *authentication_type, prerouting_algorithm: prerouting_algorithm.as_ref(), surcharge_amount: amount_details.surcharge_amount, tax_on_surcharge: amount_details.tax_on_surcharge, frm_merchant_decision: *frm_merchant_decision, enable_payment_link: *enable_payment_link, apply_mit_exemption: *apply_mit_exemption, customer_present: *customer_present, routing_algorithm_id: routing_algorithm_id.as_ref(), payment_link_config: payment_link_config.as_ref(), infra_values, enable_partial_authorization: *enable_partial_authorization, } } } impl KafkaPaymentIntent<'_> { #[cfg(feature = "v1")] fn get_id(&self) -> &id_type::PaymentId { self.payment_id } #[cfg(feature = "v2")] fn get_id(&self) -> &id_type::GlobalPaymentId { self.payment_id } } impl super::KafkaMessage for KafkaPaymentIntent<'_> { fn key(&self) -> String { format!( "{}_{}", self.merchant_id.get_string_repr(), self.get_id().get_string_repr(), ) } fn event_type(&self) -> crate::events::EventType { crate::events::EventType::PaymentIntent } }
crates/router/src/services/kafka/payment_intent.rs
router::src::services::kafka::payment_intent
3,242
true
// File: crates/router/src/services/api/request.rs // Module: router::src::services::api::request pub use common_utils::request::ContentType; pub use masking::{Mask, Maskable};
crates/router/src/services/api/request.rs
router::src::services::api::request
42
true
// File: crates/router/src/services/api/client.rs // Module: router::src::services::api::client use std::time::Duration; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; pub use external_services::http_client::{self, client}; use http::{HeaderValue, Method}; pub use hyperswitch_interfaces::{ api_client::{ApiClient, ApiClientWrapper, RequestBuilder}, types::Proxy, }; use masking::PeekInterface; use reqwest::multipart::Form; use router_env::tracing_actix_web::RequestId; use super::{request::Maskable, Request}; use crate::core::errors::{ApiClientError, CustomResult}; #[derive(Clone)] pub struct ProxyClient { proxy_config: Proxy, client: reqwest::Client, request_id: Option<RequestId>, } impl ProxyClient { pub fn new(proxy_config: &Proxy) -> CustomResult<Self, ApiClientError> { let client = client::get_client_builder(proxy_config) .switch()? .build() .change_context(ApiClientError::InvalidProxyConfiguration)?; Ok(Self { proxy_config: proxy_config.clone(), client, request_id: None, }) } pub fn get_reqwest_client( &self, client_certificate: Option<masking::Secret<String>>, client_certificate_key: Option<masking::Secret<String>>, ) -> CustomResult<reqwest::Client, ApiClientError> { match (client_certificate, client_certificate_key) { (Some(certificate), Some(certificate_key)) => { let client_builder = client::get_client_builder(&self.proxy_config).switch()?; let identity = client::create_identity_from_certificate_and_key(certificate, certificate_key) .switch()?; Ok(client_builder .identity(identity) .build() .change_context(ApiClientError::ClientConstructionFailed) .attach_printable( "Failed to construct client with certificate and certificate key", )?) } (_, _) => Ok(self.client.clone()), } } } pub struct RouterRequestBuilder { // Using option here to get around the reinitialization problem // request builder follows a chain pattern where the value is consumed and a newer requestbuilder is returned // Since for this brief period of time between the value being consumed & newer request builder // since requestbuilder does not allow moving the value // leaves our struct in an inconsistent state, we are using option to get around rust semantics inner: Option<reqwest::RequestBuilder>, } impl RequestBuilder for RouterRequestBuilder { fn json(&mut self, body: serde_json::Value) { self.inner = self.inner.take().map(|r| r.json(&body)); } fn url_encoded_form(&mut self, body: serde_json::Value) { self.inner = self.inner.take().map(|r| r.form(&body)); } fn timeout(&mut self, timeout: Duration) { self.inner = self.inner.take().map(|r| r.timeout(timeout)); } fn multipart(&mut self, form: Form) { self.inner = self.inner.take().map(|r| r.multipart(form)); } fn header(&mut self, key: String, value: Maskable<String>) -> CustomResult<(), ApiClientError> { let header_value = match value { Maskable::Masked(hvalue) => HeaderValue::from_str(hvalue.peek()).map(|mut h| { h.set_sensitive(true); h }), Maskable::Normal(hvalue) => HeaderValue::from_str(&hvalue), } .change_context(ApiClientError::HeaderMapConstructionFailed)?; self.inner = self.inner.take().map(|r| r.header(key, header_value)); Ok(()) } fn send( self, ) -> CustomResult< Box<dyn core::future::Future<Output = Result<reqwest::Response, reqwest::Error>> + 'static>, ApiClientError, > { Ok(Box::new( self.inner.ok_or(ApiClientError::UnexpectedState)?.send(), )) } } #[async_trait::async_trait] impl ApiClient for ProxyClient { fn request( &self, method: Method, url: String, ) -> CustomResult<Box<dyn RequestBuilder>, ApiClientError> { self.request_with_certificate(method, url, None, None) } fn request_with_certificate( &self, method: Method, url: String, certificate: Option<masking::Secret<String>>, certificate_key: Option<masking::Secret<String>>, ) -> CustomResult<Box<dyn RequestBuilder>, ApiClientError> { let client_builder = self .get_reqwest_client(certificate, certificate_key) .change_context(ApiClientError::ClientConstructionFailed)?; Ok(Box::new(RouterRequestBuilder { inner: Some(client_builder.request(method, url)), })) } async fn send_request( &self, api_client: &dyn ApiClientWrapper, request: Request, option_timeout_secs: Option<u64>, _forward_to_kafka: bool, ) -> CustomResult<reqwest::Response, ApiClientError> { http_client::send_request(&api_client.get_proxy(), request, option_timeout_secs) .await .switch() } fn add_request_id(&mut self, request_id: RequestId) { self.request_id = Some(request_id); } fn get_request_id(&self) -> Option<RequestId> { self.request_id } fn get_request_id_str(&self) -> Option<String> { self.request_id.map(|id| id.as_hyphenated().to_string()) } fn add_flow_name(&mut self, _flow_name: String) {} } /// Api client for testing sending request #[derive(Clone)] pub struct MockApiClient; #[async_trait::async_trait] impl ApiClient for MockApiClient { fn request( &self, _method: Method, _url: String, ) -> CustomResult<Box<dyn RequestBuilder>, ApiClientError> { // [#2066]: Add Mock implementation for ApiClient Err(ApiClientError::UnexpectedState.into()) } fn request_with_certificate( &self, _method: Method, _url: String, _certificate: Option<masking::Secret<String>>, _certificate_key: Option<masking::Secret<String>>, ) -> CustomResult<Box<dyn RequestBuilder>, ApiClientError> { // [#2066]: Add Mock implementation for ApiClient Err(ApiClientError::UnexpectedState.into()) } async fn send_request( &self, _state: &dyn ApiClientWrapper, _request: Request, _option_timeout_secs: Option<u64>, _forward_to_kafka: bool, ) -> CustomResult<reqwest::Response, ApiClientError> { // [#2066]: Add Mock implementation for ApiClient Err(ApiClientError::UnexpectedState.into()) } fn add_request_id(&mut self, _request_id: RequestId) { // [#2066]: Add Mock implementation for ApiClient } fn get_request_id(&self) -> Option<RequestId> { // [#2066]: Add Mock implementation for ApiClient None } fn get_request_id_str(&self) -> Option<String> { // [#2066]: Add Mock implementation for ApiClient None } fn add_flow_name(&mut self, _flow_name: String) {} }
crates/router/src/services/api/client.rs
router::src::services::api::client
1,631
true
// File: crates/router/src/services/api/generic_link_response.rs // Module: router::src::services::api::generic_link_response use common_utils::errors::CustomResult; use error_stack::ResultExt; use hyperswitch_domain_models::api::{ GenericExpiredLinkData, GenericLinkFormData, GenericLinkStatusData, GenericLinksData, }; use tera::{Context, Tera}; use super::build_secure_payment_link_html; use crate::core::errors; pub mod context; pub fn build_generic_link_html( boxed_generic_link_data: GenericLinksData, locale: String, ) -> CustomResult<String, errors::ApiErrorResponse> { match boxed_generic_link_data { GenericLinksData::ExpiredLink(link_data) => build_generic_expired_link_html(&link_data), GenericLinksData::PaymentMethodCollect(pm_collect_data) => { build_pm_collect_link_html(&pm_collect_data) } GenericLinksData::PaymentMethodCollectStatus(pm_collect_data) => { build_pm_collect_link_status_html(&pm_collect_data) } GenericLinksData::PayoutLink(payout_link_data) => { build_payout_link_html(&payout_link_data, locale.as_str()) } GenericLinksData::PayoutLinkStatus(pm_collect_data) => { build_payout_link_status_html(&pm_collect_data, locale.as_str()) } GenericLinksData::SecurePaymentLink(payment_link_data) => { build_secure_payment_link_html(payment_link_data) } } } pub fn build_generic_expired_link_html( link_data: &GenericExpiredLinkData, ) -> CustomResult<String, errors::ApiErrorResponse> { let mut tera = Tera::default(); let mut context = Context::new(); // Build HTML let html_template = include_str!("../../core/generic_link/expired_link/index.html").to_string(); let _ = tera.add_raw_template("generic_expired_link", &html_template); context.insert("title", &link_data.title); context.insert("message", &link_data.message); context.insert("theme", &link_data.theme); tera.render("generic_expired_link", &context) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to render expired link HTML template") } fn build_html_template( link_data: &GenericLinkFormData, document: &'static str, styles: &'static str, ) -> CustomResult<(Tera, Context), errors::ApiErrorResponse> { let mut tera: Tera = Tera::default(); let mut context = Context::new(); // Insert dynamic context in CSS let css_dynamic_context = "{{ color_scheme }}"; let css_template = styles.to_string(); let final_css = format!("{css_dynamic_context}\n{css_template}"); let _ = tera.add_raw_template("document_styles", &final_css); context.insert("color_scheme", &link_data.css_data); let css_style_tag = tera .render("document_styles", &context) .map(|css| format!("<style>{css}</style>")) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to render CSS template")?; // Insert HTML context let html_template = document.to_string(); let _ = tera.add_raw_template("html_template", &html_template); context.insert("css_style_tag", &css_style_tag); Ok((tera, context)) } pub fn build_payout_link_html( link_data: &GenericLinkFormData, locale: &str, ) -> CustomResult<String, errors::ApiErrorResponse> { let document = include_str!("../../core/generic_link/payout_link/initiate/index.html"); let styles = include_str!("../../core/generic_link/payout_link/initiate/styles.css"); let (mut tera, mut context) = build_html_template(link_data, document, styles) .attach_printable("Failed to build context for payout link's HTML template")?; // Insert dynamic context in JS let script = include_str!("../../core/generic_link/payout_link/initiate/script.js"); let js_template = script.to_string(); let js_dynamic_context = "{{ script_data }}"; let final_js = format!("{js_dynamic_context}\n{js_template}"); let _ = tera.add_raw_template("document_scripts", &final_js); context.insert("script_data", &link_data.js_data); context::insert_locales_in_context_for_payout_link(&mut context, locale); let js_script_tag = tera .render("document_scripts", &context) .map(|js| format!("<script>{js}</script>")) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to render JS template")?; context.insert("js_script_tag", &js_script_tag); context.insert( "hyper_sdk_loader_script_tag", &format!( r#"<script src="{}" onload="initializePayoutSDK()"></script>"#, link_data.sdk_url ), ); // Render HTML template tera.render("html_template", &context) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to render payout link's HTML template") } pub fn build_pm_collect_link_html( link_data: &GenericLinkFormData, ) -> CustomResult<String, errors::ApiErrorResponse> { let document = include_str!("../../core/generic_link/payment_method_collect/initiate/index.html"); let styles = include_str!("../../core/generic_link/payment_method_collect/initiate/styles.css"); let (mut tera, mut context) = build_html_template(link_data, document, styles) .attach_printable( "Failed to build context for payment method collect link's HTML template", )?; // Insert dynamic context in JS let script = include_str!("../../core/generic_link/payment_method_collect/initiate/script.js"); let js_template = script.to_string(); let js_dynamic_context = "{{ script_data }}"; let final_js = format!("{js_dynamic_context}\n{js_template}"); let _ = tera.add_raw_template("document_scripts", &final_js); context.insert("script_data", &link_data.js_data); let js_script_tag = tera .render("document_scripts", &context) .map(|js| format!("<script>{js}</script>")) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to render JS template")?; context.insert("js_script_tag", &js_script_tag); context.insert( "hyper_sdk_loader_script_tag", &format!( r#"<script src="{}" onload="initializeCollectSDK()"></script>"#, link_data.sdk_url ), ); // Render HTML template tera.render("html_template", &context) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to render payment method collect link's HTML template") } pub fn build_payout_link_status_html( link_data: &GenericLinkStatusData, locale: &str, ) -> CustomResult<String, errors::ApiErrorResponse> { let mut tera = Tera::default(); let mut context = Context::new(); // Insert dynamic context in CSS let css_dynamic_context = "{{ color_scheme }}"; let css_template = include_str!("../../core/generic_link/payout_link/status/styles.css").to_string(); let final_css = format!("{css_dynamic_context}\n{css_template}"); let _ = tera.add_raw_template("payout_link_status_styles", &final_css); context.insert("color_scheme", &link_data.css_data); let css_style_tag = tera .render("payout_link_status_styles", &context) .map(|css| format!("<style>{css}</style>")) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to render payout link status CSS template")?; // Insert dynamic context in JS let js_dynamic_context = "{{ script_data }}"; let js_template = include_str!("../../core/generic_link/payout_link/status/script.js").to_string(); let final_js = format!("{js_dynamic_context}\n{js_template}"); let _ = tera.add_raw_template("payout_link_status_script", &final_js); context.insert("script_data", &link_data.js_data); context::insert_locales_in_context_for_payout_link_status(&mut context, locale); let js_script_tag = tera .render("payout_link_status_script", &context) .map(|js| format!("<script>{js}</script>")) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to render payout link status JS template")?; // Build HTML let html_template = include_str!("../../core/generic_link/payout_link/status/index.html").to_string(); let _ = tera.add_raw_template("payout_status_link", &html_template); context.insert("css_style_tag", &css_style_tag); context.insert("js_script_tag", &js_script_tag); tera.render("payout_status_link", &context) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to render payout link status HTML template") } pub fn build_pm_collect_link_status_html( link_data: &GenericLinkStatusData, ) -> CustomResult<String, errors::ApiErrorResponse> { let mut tera = Tera::default(); let mut context = Context::new(); // Insert dynamic context in CSS let css_dynamic_context = "{{ color_scheme }}"; let css_template = include_str!("../../core/generic_link/payment_method_collect/status/styles.css") .to_string(); let final_css = format!("{css_dynamic_context}\n{css_template}"); let _ = tera.add_raw_template("pm_collect_link_status_styles", &final_css); context.insert("color_scheme", &link_data.css_data); let css_style_tag = tera .render("pm_collect_link_status_styles", &context) .map(|css| format!("<style>{css}</style>")) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to render payment method collect link status CSS template")?; // Insert dynamic context in JS let js_dynamic_context = "{{ collect_link_status_context }}"; let js_template = include_str!("../../core/generic_link/payment_method_collect/status/script.js").to_string(); let final_js = format!("{js_dynamic_context}\n{js_template}"); let _ = tera.add_raw_template("pm_collect_link_status_script", &final_js); context.insert("collect_link_status_context", &link_data.js_data); let js_script_tag = tera .render("pm_collect_link_status_script", &context) .map(|js| format!("<script>{js}</script>")) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to render payment method collect link status JS template")?; // Build HTML let html_template = include_str!("../../core/generic_link/payment_method_collect/status/index.html") .to_string(); let _ = tera.add_raw_template("payment_method_collect_status_link", &html_template); context.insert("css_style_tag", &css_style_tag); context.insert("js_script_tag", &js_script_tag); tera.render("payment_method_collect_status_link", &context) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to render payment method collect link status HTML template") }
crates/router/src/services/api/generic_link_response.rs
router::src::services::api::generic_link_response
2,494
true
// File: crates/router/src/services/api/generic_link_response/context.rs // Module: router::src::services::api::generic_link_response::context use common_utils::consts::DEFAULT_LOCALE; use rust_i18n::t; use tera::Context; fn get_language(locale_str: &str) -> String { let lowercase_str = locale_str.to_lowercase(); let primary_locale = lowercase_str.split(',').next().unwrap_or("").trim(); if primary_locale.is_empty() { return DEFAULT_LOCALE.to_string(); } let parts = primary_locale.split('-').collect::<Vec<&str>>(); let language = *parts.first().unwrap_or(&DEFAULT_LOCALE); let country = parts.get(1).copied(); match (language, country) { ("en", Some("gb")) => "en_gb".to_string(), ("fr", Some("be")) => "fr_be".to_string(), (lang, _) => lang.to_string(), } } pub fn insert_locales_in_context_for_payout_link(context: &mut Context, locale: &str) { let language = get_language(locale); let locale = language.as_str(); let i18n_payout_link_title = t!("payout_link.initiate.title", locale = locale); let i18n_january = t!("months.january", locale = locale); let i18n_february = t!("months.february", locale = locale); let i18n_march = t!("months.march", locale = locale); let i18n_april = t!("months.april", locale = locale); let i18n_may = t!("months.may", locale = locale); let i18n_june = t!("months.june", locale = locale); let i18n_july = t!("months.july", locale = locale); let i18n_august = t!("months.august", locale = locale); let i18n_september = t!("months.september", locale = locale); let i18n_october = t!("months.october", locale = locale); let i18n_november = t!("months.november", locale = locale); let i18n_december = t!("months.december", locale = locale); let i18n_not_allowed = t!("payout_link.initiate.not_allowed", locale = locale); let i18n_am = t!("time.am", locale = locale); let i18n_pm = t!("time.pm", locale = locale); context.insert("i18n_payout_link_title", &i18n_payout_link_title); context.insert("i18n_january", &i18n_january); context.insert("i18n_february", &i18n_february); context.insert("i18n_march", &i18n_march); context.insert("i18n_april", &i18n_april); context.insert("i18n_may", &i18n_may); context.insert("i18n_june", &i18n_june); context.insert("i18n_july", &i18n_july); context.insert("i18n_august", &i18n_august); context.insert("i18n_september", &i18n_september); context.insert("i18n_october", &i18n_october); context.insert("i18n_november", &i18n_november); context.insert("i18n_december", &i18n_december); context.insert("i18n_not_allowed", &i18n_not_allowed); context.insert("i18n_am", &i18n_am); context.insert("i18n_pm", &i18n_pm); } pub fn insert_locales_in_context_for_payout_link_status(context: &mut Context, locale: &str) { let language = get_language(locale); let locale = language.as_str(); let i18n_payout_link_status_title = t!("payout_link.status.title", locale = locale); let i18n_success_text = t!("payout_link.status.text.success", locale = locale); let i18n_success_message = t!("payout_link.status.message.success", locale = locale); let i18n_pending_text = t!("payout_link.status.text.processing", locale = locale); let i18n_pending_message = t!("payout_link.status.message.processing", locale = locale); let i18n_failed_text = t!("payout_link.status.text.failed", locale = locale); let i18n_failed_message = t!("payout_link.status.message.failed", locale = locale); let i18n_ref_id_text = t!("payout_link.status.info.ref_id", locale = locale); let i18n_error_code_text = t!("payout_link.status.info.error_code", locale = locale); let i18n_error_message = t!("payout_link.status.info.error_message", locale = locale); let i18n_redirecting_text = t!( "payout_link.status.redirection_text.redirecting", locale = locale ); let i18n_redirecting_in_text = t!( "payout_link.status.redirection_text.redirecting_in", locale = locale ); let i18n_seconds_text = t!( "payout_link.status.redirection_text.seconds", locale = locale ); context.insert( "i18n_payout_link_status_title", &i18n_payout_link_status_title, ); context.insert("i18n_success_text", &i18n_success_text); context.insert("i18n_success_message", &i18n_success_message); context.insert("i18n_pending_text", &i18n_pending_text); context.insert("i18n_pending_message", &i18n_pending_message); context.insert("i18n_failed_text", &i18n_failed_text); context.insert("i18n_failed_message", &i18n_failed_message); context.insert("i18n_ref_id_text", &i18n_ref_id_text); context.insert("i18n_error_code_text", &i18n_error_code_text); context.insert("i18n_error_message", &i18n_error_message); context.insert("i18n_redirecting_text", &i18n_redirecting_text); context.insert("i18n_redirecting_in_text", &i18n_redirecting_in_text); context.insert("i18n_seconds_text", &i18n_seconds_text); }
crates/router/src/services/api/generic_link_response/context.rs
router::src::services::api::generic_link_response::context
1,507
true
// File: crates/router/src/services/authorization/roles.rs // Module: router::src::services::authorization::roles #[cfg(feature = "recon")] use std::collections::HashMap; use std::collections::HashSet; #[cfg(feature = "recon")] use api_models::enums::ReconPermissionScope; use common_enums::{EntityType, PermissionGroup, Resource, RoleScope}; use common_utils::{errors::CustomResult, id_type}; #[cfg(feature = "recon")] use super::permission_groups::{RECON_OPS, RECON_REPORTS}; use super::{permission_groups::PermissionGroupExt, permissions::Permission}; use crate::{core::errors, routes::SessionState}; pub mod predefined_roles; #[derive(Clone, serde::Serialize, serde::Deserialize, Debug)] pub struct RoleInfo { role_id: String, role_name: String, groups: Vec<PermissionGroup>, scope: RoleScope, entity_type: EntityType, is_invitable: bool, is_deletable: bool, is_updatable: bool, is_internal: bool, } impl RoleInfo { pub fn get_role_id(&self) -> &str { &self.role_id } pub fn get_role_name(&self) -> &str { &self.role_name } pub fn get_permission_groups(&self) -> Vec<PermissionGroup> { self.groups .iter() .flat_map(|group| group.accessible_groups()) .collect::<HashSet<_>>() .into_iter() .collect() } pub fn get_scope(&self) -> RoleScope { self.scope } pub fn get_entity_type(&self) -> EntityType { self.entity_type } pub fn is_invitable(&self) -> bool { self.is_invitable } pub fn is_deletable(&self) -> bool { self.is_deletable } pub fn is_internal(&self) -> bool { self.is_internal } pub fn is_updatable(&self) -> bool { self.is_updatable } pub fn get_resources_set(&self) -> HashSet<Resource> { self.get_permission_groups() .iter() .flat_map(|group| group.resources()) .collect() } pub fn check_permission_exists(&self, required_permission: Permission) -> bool { required_permission.entity_type() <= self.entity_type && self.get_permission_groups().iter().any(|group| { required_permission.scope() <= group.scope() && group.resources().contains(&required_permission.resource()) }) } #[cfg(feature = "recon")] pub fn get_recon_acl(&self) -> HashMap<Resource, ReconPermissionScope> { let mut acl: HashMap<Resource, ReconPermissionScope> = HashMap::new(); let mut recon_resources = RECON_OPS.to_vec(); recon_resources.extend(RECON_REPORTS); let recon_internal_resources = [Resource::ReconToken]; self.get_permission_groups() .iter() .for_each(|permission_group| { permission_group.resources().iter().for_each(|resource| { if recon_resources.contains(resource) && !recon_internal_resources.contains(resource) { let scope = match resource { Resource::ReconAndSettlementAnalytics => ReconPermissionScope::Read, _ => ReconPermissionScope::from(permission_group.scope()), }; acl.entry(*resource) .and_modify(|curr_scope| { *curr_scope = if (*curr_scope) < scope { scope } else { *curr_scope } }) .or_insert(scope); } }) }); acl } pub fn from_predefined_roles(role_id: &str) -> Option<Self> { predefined_roles::PREDEFINED_ROLES.get(role_id).cloned() } pub async fn from_role_id_in_lineage( state: &SessionState, role_id: &str, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, profile_id: &id_type::ProfileId, tenant_id: &id_type::TenantId, ) -> CustomResult<Self, errors::StorageError> { if let Some(role) = predefined_roles::PREDEFINED_ROLES.get(role_id) { Ok(role.clone()) } else { state .global_store .find_role_by_role_id_in_lineage( role_id, merchant_id, org_id, profile_id, tenant_id, ) .await .map(Self::from) } } // TODO: To evaluate whether we can omit org_id and tenant_id for this function pub async fn from_role_id_org_id_tenant_id( state: &SessionState, role_id: &str, org_id: &id_type::OrganizationId, tenant_id: &id_type::TenantId, ) -> CustomResult<Self, errors::StorageError> { if let Some(role) = predefined_roles::PREDEFINED_ROLES.get(role_id) { Ok(role.clone()) } else { state .global_store .find_by_role_id_org_id_tenant_id(role_id, org_id, tenant_id) .await .map(Self::from) } } } impl From<diesel_models::role::Role> for RoleInfo { fn from(role: diesel_models::role::Role) -> Self { Self { role_id: role.role_id, role_name: role.role_name, groups: role.groups, scope: role.scope, entity_type: role.entity_type, is_invitable: true, is_deletable: true, is_updatable: true, is_internal: false, } } }
crates/router/src/services/authorization/roles.rs
router::src::services::authorization::roles
1,237
true
// File: crates/router/src/services/authorization/permission_groups.rs // Module: router::src::services::authorization::permission_groups use std::{collections::HashMap, ops::Not}; use common_enums::{EntityType, ParentGroup, PermissionGroup, PermissionScope, Resource}; use strum::IntoEnumIterator; use super::permissions; pub trait PermissionGroupExt { fn scope(&self) -> PermissionScope; fn parent(&self) -> ParentGroup; fn resources(&self) -> Vec<Resource>; fn accessible_groups(&self) -> Vec<PermissionGroup>; } impl PermissionGroupExt for PermissionGroup { fn scope(&self) -> PermissionScope { match self { Self::OperationsView | Self::ConnectorsView | Self::WorkflowsView | Self::AnalyticsView | Self::UsersView | Self::AccountView | Self::ReconOpsView | Self::ReconReportsView | Self::ThemeView => PermissionScope::Read, Self::OperationsManage | Self::ConnectorsManage | Self::WorkflowsManage | Self::UsersManage | Self::AccountManage | Self::ReconOpsManage | Self::ReconReportsManage | Self::InternalManage | Self::ThemeManage => PermissionScope::Write, } } fn parent(&self) -> ParentGroup { match self { Self::OperationsView | Self::OperationsManage => ParentGroup::Operations, Self::ConnectorsView | Self::ConnectorsManage => ParentGroup::Connectors, Self::WorkflowsView | Self::WorkflowsManage => ParentGroup::Workflows, Self::AnalyticsView => ParentGroup::Analytics, Self::UsersView | Self::UsersManage => ParentGroup::Users, Self::AccountView | Self::AccountManage => ParentGroup::Account, Self::ThemeView | Self::ThemeManage => ParentGroup::Theme, Self::ReconOpsView | Self::ReconOpsManage => ParentGroup::ReconOps, Self::ReconReportsView | Self::ReconReportsManage => ParentGroup::ReconReports, Self::InternalManage => ParentGroup::Internal, } } fn resources(&self) -> Vec<Resource> { self.parent().resources() } fn accessible_groups(&self) -> Vec<Self> { match self { Self::OperationsView => vec![Self::OperationsView, Self::ConnectorsView], Self::OperationsManage => vec![ Self::OperationsView, Self::OperationsManage, Self::ConnectorsView, ], Self::ConnectorsView => vec![Self::ConnectorsView], Self::ConnectorsManage => vec![Self::ConnectorsView, Self::ConnectorsManage], Self::WorkflowsView => vec![Self::WorkflowsView, Self::ConnectorsView], Self::WorkflowsManage => vec![ Self::WorkflowsView, Self::WorkflowsManage, Self::ConnectorsView, ], Self::AnalyticsView => vec![Self::AnalyticsView, Self::OperationsView], Self::UsersView => vec![Self::UsersView], Self::UsersManage => { vec![Self::UsersView, Self::UsersManage] } Self::ReconOpsView => vec![Self::ReconOpsView], Self::ReconOpsManage => vec![Self::ReconOpsView, Self::ReconOpsManage], Self::ReconReportsView => vec![Self::ReconReportsView], Self::ReconReportsManage => vec![Self::ReconReportsView, Self::ReconReportsManage], Self::AccountView => vec![Self::AccountView], Self::AccountManage => vec![Self::AccountView, Self::AccountManage], Self::InternalManage => vec![Self::InternalManage], Self::ThemeView => vec![Self::ThemeView, Self::AccountView], Self::ThemeManage => vec![Self::ThemeManage, Self::AccountView], } } } pub trait ParentGroupExt { fn resources(&self) -> Vec<Resource>; fn get_descriptions_for_groups( entity_type: EntityType, groups: Vec<PermissionGroup>, ) -> Option<HashMap<ParentGroup, String>>; fn get_available_scopes(&self) -> Vec<PermissionScope>; } impl ParentGroupExt for ParentGroup { fn resources(&self) -> Vec<Resource> { match self { Self::Operations => OPERATIONS.to_vec(), Self::Connectors => CONNECTORS.to_vec(), Self::Workflows => WORKFLOWS.to_vec(), Self::Analytics => ANALYTICS.to_vec(), Self::Users => USERS.to_vec(), Self::Account => ACCOUNT.to_vec(), Self::ReconOps => RECON_OPS.to_vec(), Self::ReconReports => RECON_REPORTS.to_vec(), Self::Internal => INTERNAL.to_vec(), Self::Theme => THEME.to_vec(), } } fn get_descriptions_for_groups( entity_type: EntityType, groups: Vec<PermissionGroup>, ) -> Option<HashMap<Self, String>> { let descriptions_map = Self::iter() .filter_map(|parent| { if !groups.iter().any(|group| group.parent() == parent) { return None; } let filtered_resources = permissions::filter_resources_by_entity_type(parent.resources(), entity_type)?; let description = filtered_resources .iter() .map(|res| permissions::get_resource_name(*res, entity_type)) .collect::<Option<Vec<_>>>()? .join(", "); Some((parent, description)) }) .collect::<HashMap<_, _>>(); descriptions_map .is_empty() .not() .then_some(descriptions_map) } fn get_available_scopes(&self) -> Vec<PermissionScope> { PermissionGroup::iter() .filter(|group| group.parent() == *self) .map(|group| group.scope()) .collect() } } pub static OPERATIONS: [Resource; 8] = [ Resource::Payment, Resource::Refund, Resource::Mandate, Resource::Dispute, Resource::Customer, Resource::Payout, Resource::Report, Resource::Account, ]; pub static CONNECTORS: [Resource; 2] = [Resource::Connector, Resource::Account]; pub static WORKFLOWS: [Resource; 5] = [ Resource::Routing, Resource::ThreeDsDecisionManager, Resource::SurchargeDecisionManager, Resource::Account, Resource::RevenueRecovery, ]; pub static ANALYTICS: [Resource; 3] = [Resource::Analytics, Resource::Report, Resource::Account]; pub static USERS: [Resource; 2] = [Resource::User, Resource::Account]; pub static ACCOUNT: [Resource; 3] = [Resource::Account, Resource::ApiKey, Resource::WebhookEvent]; pub static RECON_OPS: [Resource; 8] = [ Resource::ReconToken, Resource::ReconFiles, Resource::ReconUpload, Resource::RunRecon, Resource::ReconConfig, Resource::ReconAndSettlementAnalytics, Resource::ReconReports, Resource::Account, ]; pub static INTERNAL: [Resource; 1] = [Resource::InternalConnector]; pub static RECON_REPORTS: [Resource; 4] = [ Resource::ReconToken, Resource::ReconAndSettlementAnalytics, Resource::ReconReports, Resource::Account, ]; pub static THEME: [Resource; 1] = [Resource::Theme];
crates/router/src/services/authorization/permission_groups.rs
router::src::services::authorization::permission_groups
1,649
true
// File: crates/router/src/services/authorization/info.rs // Module: router::src::services::authorization::info use std::ops::Not; use api_models::user_role::GroupInfo; use common_enums::{ParentGroup, PermissionGroup}; use strum::IntoEnumIterator; // TODO: To be deprecated pub fn get_group_authorization_info() -> Option<Vec<GroupInfo>> { let groups = PermissionGroup::iter() .filter_map(get_group_info_from_permission_group) .collect::<Vec<_>>(); groups.is_empty().not().then_some(groups) } // TODO: To be deprecated fn get_group_info_from_permission_group(group: PermissionGroup) -> Option<GroupInfo> { let description = get_group_description(group)?; Some(GroupInfo { group, description }) } // TODO: To be deprecated fn get_group_description(group: PermissionGroup) -> Option<&'static str> { match group { PermissionGroup::OperationsView => { Some("View Payments, Refunds, Payouts, Mandates, Disputes and Customers") } PermissionGroup::OperationsManage => { Some("Create, modify and delete Payments, Refunds, Payouts, Mandates, Disputes and Customers") } PermissionGroup::ConnectorsView => { Some("View connected Payment Processors, Payout Processors and Fraud & Risk Manager details") } PermissionGroup::ConnectorsManage => Some("Create, modify and delete connectors like Payment Processors, Payout Processors and Fraud & Risk Manager"), PermissionGroup::WorkflowsView => { Some("View Routing, 3DS Decision Manager, Surcharge Decision Manager") } PermissionGroup::WorkflowsManage => { Some("Create, modify and delete Routing, 3DS Decision Manager, Surcharge Decision Manager") } PermissionGroup::AnalyticsView => Some("View Analytics"), PermissionGroup::UsersView => Some("View Users"), PermissionGroup::UsersManage => Some("Manage and invite Users to the Team"), PermissionGroup::AccountView => Some("View Merchant Details"), PermissionGroup::AccountManage => Some("Create, modify and delete Merchant Details like api keys, webhooks, etc"), PermissionGroup::ReconReportsView => Some("View reconciliation reports and analytics"), PermissionGroup::ReconReportsManage => Some("Manage reconciliation reports"), PermissionGroup::ReconOpsView => Some("View and access all reconciliation operations including reports and analytics"), PermissionGroup::ReconOpsManage => Some("Manage all reconciliation operations including reports and analytics"), PermissionGroup::ThemeView => Some("View Themes"), PermissionGroup::ThemeManage => Some("Manage Themes"), PermissionGroup::InternalManage => None, // Internal group, no user-facing description } } pub fn get_parent_group_description(group: ParentGroup) -> Option<&'static str> { match group { ParentGroup::Operations => Some("Payments, Refunds, Payouts, Mandates, Disputes and Customers"), ParentGroup::Connectors => Some("Create, modify and delete connectors like Payment Processors, Payout Processors and Fraud & Risk Manager"), ParentGroup::Workflows => Some("Create, modify and delete Routing, 3DS Decision Manager, Surcharge Decision Manager"), ParentGroup::Analytics => Some("View Analytics"), ParentGroup::Users => Some("Manage and invite Users to the Team"), ParentGroup::Account => Some("Create, modify and delete Merchant Details like api keys, webhooks, etc"), ParentGroup::ReconOps => Some("View, manage reconciliation operations like upload and process files, run reconciliation etc"), ParentGroup::ReconReports => Some("View, manage reconciliation reports and analytics"), ParentGroup::Theme => Some("Manage and view themes for the organization"), ParentGroup::Internal => None, // Internal group, no user-facing description } }
crates/router/src/services/authorization/info.rs
router::src::services::authorization::info
819
true
// File: crates/router/src/services/authorization/permissions.rs // Module: router::src::services::authorization::permissions use common_enums::{EntityType, PermissionScope, Resource}; use router_derive::generate_permissions; generate_permissions! { permissions: [ Payment: { scopes: [Read, Write], entities: [Profile, Merchant] }, Refund: { scopes: [Read, Write], entities: [Profile, Merchant] }, Dispute: { scopes: [Read, Write], entities: [Profile, Merchant] }, Mandate: { scopes: [Read, Write], entities: [Merchant] }, Customer: { scopes: [Read, Write], entities: [Merchant] }, Payout: { scopes: [Read], entities: [Profile, Merchant] }, ApiKey: { scopes: [Read, Write], entities: [Merchant] }, Account: { scopes: [Read, Write], entities: [Profile, Merchant, Organization, Tenant] }, Connector: { scopes: [Read, Write], entities: [Profile, Merchant] }, Routing: { scopes: [Read, Write], entities: [Profile, Merchant] }, Subscription: { scopes: [Read, Write], entities: [Profile, Merchant] }, ThreeDsDecisionManager: { scopes: [Read, Write], entities: [Merchant, Profile] }, SurchargeDecisionManager: { scopes: [Read, Write], entities: [Merchant] }, Analytics: { scopes: [Read], entities: [Profile, Merchant, Organization] }, Report: { scopes: [Read], entities: [Profile, Merchant, Organization] }, User: { scopes: [Read, Write], entities: [Profile, Merchant] }, WebhookEvent: { scopes: [Read, Write], entities: [Profile, Merchant] }, ReconToken: { scopes: [Read], entities: [Merchant] }, ReconFiles: { scopes: [Read, Write], entities: [Merchant] }, ReconAndSettlementAnalytics: { scopes: [Read], entities: [Merchant] }, ReconUpload: { scopes: [Read, Write], entities: [Merchant] }, ReconReports: { scopes: [Read, Write], entities: [Merchant] }, RunRecon: { scopes: [Read, Write], entities: [Merchant] }, ReconConfig: { scopes: [Read, Write], entities: [Merchant] }, RevenueRecovery: { scopes: [Read], entities: [Profile] }, InternalConnector: { scopes: [Write], entities: [Merchant] }, Theme: { scopes: [Read,Write], entities: [Organization] } ] } pub fn get_resource_name(resource: Resource, entity_type: EntityType) -> Option<&'static str> { match (resource, entity_type) { (Resource::Payment, _) => Some("Payments"), (Resource::Refund, _) => Some("Refunds"), (Resource::Dispute, _) => Some("Disputes"), (Resource::Mandate, _) => Some("Mandates"), (Resource::Customer, _) => Some("Customers"), (Resource::Payout, _) => Some("Payouts"), (Resource::ApiKey, _) => Some("Api Keys"), (Resource::Connector, _) => { Some("Payment Processors, Payout Processors, Fraud & Risk Managers") } (Resource::Routing, _) => Some("Routing"), (Resource::Subscription, _) => Some("Subscription"), (Resource::RevenueRecovery, _) => Some("Revenue Recovery"), (Resource::ThreeDsDecisionManager, _) => Some("3DS Decision Manager"), (Resource::SurchargeDecisionManager, _) => Some("Surcharge Decision Manager"), (Resource::Analytics, _) => Some("Analytics"), (Resource::Report, _) => Some("Operation Reports"), (Resource::User, _) => Some("Users"), (Resource::WebhookEvent, _) => Some("Webhook Events"), (Resource::ReconUpload, _) => Some("Reconciliation File Upload"), (Resource::RunRecon, _) => Some("Run Reconciliation Process"), (Resource::ReconConfig, _) => Some("Reconciliation Configurations"), (Resource::ReconToken, _) => Some("Generate & Verify Reconciliation Token"), (Resource::ReconFiles, _) => Some("Reconciliation Process Manager"), (Resource::ReconReports, _) => Some("Reconciliation Reports"), (Resource::ReconAndSettlementAnalytics, _) => Some("Reconciliation Analytics"), (Resource::Account, EntityType::Profile) => Some("Business Profile Account"), (Resource::Account, EntityType::Merchant) => Some("Merchant Account"), (Resource::Account, EntityType::Organization) => Some("Organization Account"), (Resource::Account, EntityType::Tenant) => Some("Tenant Account"), (Resource::Theme, _) => Some("Themes"), (Resource::InternalConnector, _) => None, } } pub fn get_scope_name(scope: PermissionScope) -> &'static str { match scope { PermissionScope::Read => "View", PermissionScope::Write => "View and Manage", } } pub fn filter_resources_by_entity_type( resources: Vec<Resource>, entity_type: EntityType, ) -> Option<Vec<Resource>> { let filtered: Vec<Resource> = resources .into_iter() .filter(|res| res.entities().iter().any(|entity| entity <= &entity_type)) .collect(); (!filtered.is_empty()).then_some(filtered) }
crates/router/src/services/authorization/permissions.rs
router::src::services::authorization::permissions
1,261
true
// File: crates/router/src/services/authorization/roles/predefined_roles.rs // Module: router::src::services::authorization::roles::predefined_roles use std::{collections::HashMap, sync::LazyLock}; use common_enums::{EntityType, PermissionGroup, RoleScope}; use super::RoleInfo; use crate::consts; pub static PREDEFINED_ROLES: LazyLock<HashMap<&'static str, RoleInfo>> = LazyLock::new(|| { let mut roles = HashMap::new(); // Internal Roles roles.insert( common_utils::consts::ROLE_ID_INTERNAL_ADMIN, RoleInfo { groups: vec![ PermissionGroup::OperationsView, PermissionGroup::OperationsManage, PermissionGroup::ConnectorsView, PermissionGroup::ConnectorsManage, PermissionGroup::WorkflowsView, PermissionGroup::WorkflowsManage, PermissionGroup::AnalyticsView, PermissionGroup::UsersView, PermissionGroup::UsersManage, PermissionGroup::AccountView, PermissionGroup::AccountManage, PermissionGroup::ReconOpsView, PermissionGroup::ReconOpsManage, PermissionGroup::ReconReportsView, PermissionGroup::ReconReportsManage, ], role_id: common_utils::consts::ROLE_ID_INTERNAL_ADMIN.to_string(), role_name: "internal_admin".to_string(), scope: RoleScope::Organization, entity_type: EntityType::Merchant, is_invitable: false, is_deletable: false, is_updatable: false, is_internal: true, }, ); roles.insert( common_utils::consts::ROLE_ID_INTERNAL_VIEW_ONLY_USER, RoleInfo { groups: vec![ PermissionGroup::OperationsView, PermissionGroup::ConnectorsView, PermissionGroup::WorkflowsView, PermissionGroup::AnalyticsView, PermissionGroup::UsersView, PermissionGroup::AccountView, PermissionGroup::ReconOpsView, PermissionGroup::ReconReportsView, ], role_id: common_utils::consts::ROLE_ID_INTERNAL_VIEW_ONLY_USER.to_string(), role_name: "internal_view_only".to_string(), scope: RoleScope::Organization, entity_type: EntityType::Merchant, is_invitable: false, is_deletable: false, is_updatable: false, is_internal: true, }, ); roles.insert( common_utils::consts::ROLE_ID_INTERNAL_DEMO, RoleInfo { groups: vec![ PermissionGroup::OperationsView, PermissionGroup::ConnectorsView, PermissionGroup::WorkflowsView, PermissionGroup::AnalyticsView, PermissionGroup::UsersView, PermissionGroup::AccountView, PermissionGroup::ReconOpsView, PermissionGroup::ReconReportsView, PermissionGroup::InternalManage, ], role_id: common_utils::consts::ROLE_ID_INTERNAL_DEMO.to_string(), role_name: "internal_demo".to_string(), scope: RoleScope::Organization, entity_type: EntityType::Merchant, is_invitable: false, is_deletable: false, is_updatable: false, is_internal: true, }, ); // Tenant Roles roles.insert( common_utils::consts::ROLE_ID_TENANT_ADMIN, RoleInfo { groups: vec![ PermissionGroup::OperationsView, PermissionGroup::OperationsManage, PermissionGroup::ConnectorsView, PermissionGroup::ConnectorsManage, PermissionGroup::WorkflowsView, PermissionGroup::WorkflowsManage, PermissionGroup::AnalyticsView, PermissionGroup::UsersView, PermissionGroup::UsersManage, PermissionGroup::AccountView, PermissionGroup::AccountManage, PermissionGroup::ReconOpsView, PermissionGroup::ReconOpsManage, PermissionGroup::ReconReportsView, PermissionGroup::ReconReportsManage, ], role_id: common_utils::consts::ROLE_ID_TENANT_ADMIN.to_string(), role_name: "tenant_admin".to_string(), scope: RoleScope::Organization, entity_type: EntityType::Tenant, is_invitable: false, is_deletable: false, is_updatable: false, is_internal: false, }, ); // Organization Roles roles.insert( common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN, RoleInfo { groups: vec![ PermissionGroup::OperationsView, PermissionGroup::OperationsManage, PermissionGroup::ConnectorsView, PermissionGroup::ConnectorsManage, PermissionGroup::WorkflowsView, PermissionGroup::WorkflowsManage, PermissionGroup::AnalyticsView, PermissionGroup::UsersView, PermissionGroup::UsersManage, PermissionGroup::AccountView, PermissionGroup::AccountManage, PermissionGroup::ReconOpsView, PermissionGroup::ReconOpsManage, PermissionGroup::ReconReportsView, PermissionGroup::ReconReportsManage, PermissionGroup::ThemeView, PermissionGroup::ThemeManage, ], role_id: common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(), role_name: "organization_admin".to_string(), scope: RoleScope::Organization, entity_type: EntityType::Organization, is_invitable: true, is_deletable: true, is_updatable: true, is_internal: false, }, ); // MERCHANT ROLES roles.insert( consts::user_role::ROLE_ID_MERCHANT_ADMIN, RoleInfo { groups: vec![ PermissionGroup::OperationsView, PermissionGroup::OperationsManage, PermissionGroup::ConnectorsView, PermissionGroup::ConnectorsManage, PermissionGroup::WorkflowsView, PermissionGroup::WorkflowsManage, PermissionGroup::AnalyticsView, PermissionGroup::UsersView, PermissionGroup::UsersManage, PermissionGroup::AccountView, PermissionGroup::AccountManage, PermissionGroup::ReconOpsView, PermissionGroup::ReconOpsManage, PermissionGroup::ReconReportsView, PermissionGroup::ReconReportsManage, ], role_id: consts::user_role::ROLE_ID_MERCHANT_ADMIN.to_string(), role_name: "merchant_admin".to_string(), scope: RoleScope::Organization, entity_type: EntityType::Merchant, is_invitable: true, is_deletable: true, is_updatable: true, is_internal: false, }, ); roles.insert( consts::user_role::ROLE_ID_MERCHANT_VIEW_ONLY, RoleInfo { groups: vec![ PermissionGroup::OperationsView, PermissionGroup::ConnectorsView, PermissionGroup::WorkflowsView, PermissionGroup::AnalyticsView, PermissionGroup::UsersView, PermissionGroup::AccountView, PermissionGroup::ReconOpsView, PermissionGroup::ReconReportsView, ], role_id: consts::user_role::ROLE_ID_MERCHANT_VIEW_ONLY.to_string(), role_name: "merchant_view_only".to_string(), scope: RoleScope::Organization, entity_type: EntityType::Merchant, is_invitable: true, is_deletable: true, is_updatable: true, is_internal: false, }, ); roles.insert( consts::user_role::ROLE_ID_MERCHANT_IAM_ADMIN, RoleInfo { groups: vec![ PermissionGroup::OperationsView, PermissionGroup::AnalyticsView, PermissionGroup::UsersView, PermissionGroup::UsersManage, PermissionGroup::AccountView, ], role_id: consts::user_role::ROLE_ID_MERCHANT_IAM_ADMIN.to_string(), role_name: "merchant_iam".to_string(), scope: RoleScope::Organization, entity_type: EntityType::Merchant, is_invitable: true, is_deletable: true, is_updatable: true, is_internal: false, }, ); roles.insert( consts::user_role::ROLE_ID_MERCHANT_DEVELOPER, RoleInfo { groups: vec![ PermissionGroup::OperationsView, PermissionGroup::ConnectorsView, PermissionGroup::AnalyticsView, PermissionGroup::UsersView, PermissionGroup::AccountView, PermissionGroup::AccountManage, PermissionGroup::ReconOpsView, PermissionGroup::ReconReportsView, ], role_id: consts::user_role::ROLE_ID_MERCHANT_DEVELOPER.to_string(), role_name: "merchant_developer".to_string(), scope: RoleScope::Organization, entity_type: EntityType::Merchant, is_invitable: true, is_deletable: true, is_updatable: true, is_internal: false, }, ); roles.insert( consts::user_role::ROLE_ID_MERCHANT_OPERATOR, RoleInfo { groups: vec![ PermissionGroup::OperationsView, PermissionGroup::OperationsManage, PermissionGroup::ConnectorsView, PermissionGroup::WorkflowsView, PermissionGroup::AnalyticsView, PermissionGroup::UsersView, PermissionGroup::AccountView, PermissionGroup::ReconOpsView, PermissionGroup::ReconOpsManage, PermissionGroup::ReconReportsView, ], role_id: consts::user_role::ROLE_ID_MERCHANT_OPERATOR.to_string(), role_name: "merchant_operator".to_string(), scope: RoleScope::Organization, entity_type: EntityType::Merchant, is_invitable: true, is_deletable: true, is_updatable: true, is_internal: false, }, ); roles.insert( consts::user_role::ROLE_ID_MERCHANT_CUSTOMER_SUPPORT, RoleInfo { groups: vec![ PermissionGroup::OperationsView, PermissionGroup::AnalyticsView, PermissionGroup::UsersView, PermissionGroup::AccountView, PermissionGroup::ReconOpsView, PermissionGroup::ReconReportsView, ], role_id: consts::user_role::ROLE_ID_MERCHANT_CUSTOMER_SUPPORT.to_string(), role_name: "customer_support".to_string(), scope: RoleScope::Organization, entity_type: EntityType::Merchant, is_invitable: true, is_deletable: true, is_updatable: true, is_internal: false, }, ); // Profile Roles roles.insert( consts::user_role::ROLE_ID_PROFILE_ADMIN, RoleInfo { groups: vec![ PermissionGroup::OperationsView, PermissionGroup::OperationsManage, PermissionGroup::ConnectorsView, PermissionGroup::ConnectorsManage, PermissionGroup::WorkflowsView, PermissionGroup::WorkflowsManage, PermissionGroup::AnalyticsView, PermissionGroup::UsersView, PermissionGroup::UsersManage, PermissionGroup::AccountView, PermissionGroup::AccountManage, ], role_id: consts::user_role::ROLE_ID_PROFILE_ADMIN.to_string(), role_name: "profile_admin".to_string(), scope: RoleScope::Organization, entity_type: EntityType::Profile, is_invitable: true, is_deletable: true, is_updatable: true, is_internal: false, }, ); roles.insert( consts::user_role::ROLE_ID_PROFILE_VIEW_ONLY, RoleInfo { groups: vec![ PermissionGroup::OperationsView, PermissionGroup::ConnectorsView, PermissionGroup::WorkflowsView, PermissionGroup::AnalyticsView, PermissionGroup::UsersView, PermissionGroup::AccountView, ], role_id: consts::user_role::ROLE_ID_PROFILE_VIEW_ONLY.to_string(), role_name: "profile_view_only".to_string(), scope: RoleScope::Organization, entity_type: EntityType::Profile, is_invitable: true, is_deletable: true, is_updatable: true, is_internal: false, }, ); roles.insert( consts::user_role::ROLE_ID_PROFILE_IAM_ADMIN, RoleInfo { groups: vec![ PermissionGroup::OperationsView, PermissionGroup::AnalyticsView, PermissionGroup::UsersView, PermissionGroup::UsersManage, PermissionGroup::AccountView, ], role_id: consts::user_role::ROLE_ID_PROFILE_IAM_ADMIN.to_string(), role_name: "profile_iam".to_string(), scope: RoleScope::Organization, entity_type: EntityType::Profile, is_invitable: true, is_deletable: true, is_updatable: true, is_internal: false, }, ); roles.insert( consts::user_role::ROLE_ID_PROFILE_DEVELOPER, RoleInfo { groups: vec![ PermissionGroup::OperationsView, PermissionGroup::ConnectorsView, PermissionGroup::AnalyticsView, PermissionGroup::UsersView, PermissionGroup::AccountView, PermissionGroup::AccountManage, ], role_id: consts::user_role::ROLE_ID_PROFILE_DEVELOPER.to_string(), role_name: "profile_developer".to_string(), scope: RoleScope::Organization, entity_type: EntityType::Profile, is_invitable: true, is_deletable: true, is_updatable: true, is_internal: false, }, ); roles.insert( consts::user_role::ROLE_ID_PROFILE_OPERATOR, RoleInfo { groups: vec![ PermissionGroup::OperationsView, PermissionGroup::OperationsManage, PermissionGroup::ConnectorsView, PermissionGroup::WorkflowsView, PermissionGroup::AnalyticsView, PermissionGroup::UsersView, PermissionGroup::AccountView, ], role_id: consts::user_role::ROLE_ID_PROFILE_OPERATOR.to_string(), role_name: "profile_operator".to_string(), scope: RoleScope::Organization, entity_type: EntityType::Profile, is_invitable: true, is_deletable: true, is_updatable: true, is_internal: false, }, ); roles.insert( consts::user_role::ROLE_ID_PROFILE_CUSTOMER_SUPPORT, RoleInfo { groups: vec![ PermissionGroup::OperationsView, PermissionGroup::AnalyticsView, PermissionGroup::UsersView, PermissionGroup::AccountView, ], role_id: consts::user_role::ROLE_ID_PROFILE_CUSTOMER_SUPPORT.to_string(), role_name: "profile_customer_support".to_string(), scope: RoleScope::Organization, entity_type: EntityType::Profile, is_invitable: true, is_deletable: true, is_updatable: true, is_internal: false, }, ); roles });
crates/router/src/services/authorization/roles/predefined_roles.rs
router::src::services::authorization::roles::predefined_roles
3,086
true
// File: crates/router/src/services/authentication/decision.rs // Module: router::src::services::authentication::decision use common_utils::{errors::CustomResult, request::RequestContent}; use masking::{ErasedMaskSerialize, Secret}; use serde::Serialize; use storage_impl::errors::ApiClientError; use crate::{ core::metrics, routes::{app::settings::DecisionConfig, SessionState}, }; // # Consts // const DECISION_ENDPOINT: &str = "/rule"; const RULE_ADD_METHOD: common_utils::request::Method = common_utils::request::Method::Post; const RULE_DELETE_METHOD: common_utils::request::Method = common_utils::request::Method::Delete; pub const REVOKE: &str = "REVOKE"; pub const ADD: &str = "ADD"; // # Types // /// [`RuleRequest`] is a request body used to register a new authentication method in the proxy. #[derive(Debug, Serialize)] pub struct RuleRequest { /// [`tag`] similar to a partition key, which can be used by the decision service to tag rules /// by partitioning identifiers. (e.g. `tenant_id`) pub tag: String, /// [`variant`] is the type of authentication method to be registered. #[serde(flatten)] pub variant: AuthRuleType, /// [`expiry`] is the time **in seconds** after which the rule should be removed pub expiry: Option<u64>, } #[derive(Debug, Serialize)] pub struct RuleDeleteRequest { pub tag: String, #[serde(flatten)] pub variant: AuthType, } #[derive(Debug, Serialize)] #[serde(tag = "type", rename_all = "snake_case")] pub enum AuthType { /// [`ApiKey`] is an authentication method that uses an API key. This is used with [`ApiKey`] ApiKey { api_key: Secret<String> }, } #[derive(Debug, Serialize)] #[serde(tag = "type", rename_all = "snake_case")] pub enum AuthRuleType { /// [`ApiKey`] is an authentication method that uses an API key. This is used with [`ApiKey`] /// and [`PublishableKey`] authentication methods. ApiKey { api_key: Secret<String>, identifiers: Identifiers, }, } #[allow(clippy::enum_variant_names)] #[derive(Debug, Serialize, Clone)] #[serde(tag = "type", rename_all = "snake_case")] pub enum Identifiers { /// [`ApiKey`] is an authentication method that uses an API key. This is used with [`ApiKey`] ApiKey { merchant_id: common_utils::id_type::MerchantId, key_id: common_utils::id_type::ApiKeyId, }, /// [`PublishableKey`] is an authentication method that uses a publishable key. This is used with [`PublishableKey`] PublishableKey { merchant_id: String }, } // # Decision Service // pub async fn add_api_key( state: &SessionState, api_key: Secret<String>, merchant_id: common_utils::id_type::MerchantId, key_id: common_utils::id_type::ApiKeyId, expiry: Option<u64>, ) -> CustomResult<(), ApiClientError> { let decision_config = if let Some(config) = &state.conf.decision { config } else { return Ok(()); }; let rule = RuleRequest { tag: state.tenant.schema.clone(), expiry, variant: AuthRuleType::ApiKey { api_key, identifiers: Identifiers::ApiKey { merchant_id, key_id, }, }, }; call_decision_service(state, decision_config, rule, RULE_ADD_METHOD).await } pub async fn add_publishable_key( state: &SessionState, api_key: Secret<String>, merchant_id: common_utils::id_type::MerchantId, expiry: Option<u64>, ) -> CustomResult<(), ApiClientError> { let decision_config = if let Some(config) = &state.conf.decision { config } else { return Ok(()); }; let rule = RuleRequest { tag: state.tenant.schema.clone(), expiry, variant: AuthRuleType::ApiKey { api_key, identifiers: Identifiers::PublishableKey { merchant_id: merchant_id.get_string_repr().to_owned(), }, }, }; call_decision_service(state, decision_config, rule, RULE_ADD_METHOD).await } async fn call_decision_service<T: ErasedMaskSerialize + Send + 'static>( state: &SessionState, decision_config: &DecisionConfig, rule: T, method: common_utils::request::Method, ) -> CustomResult<(), ApiClientError> { let mut request = common_utils::request::Request::new( method, &(decision_config.base_url.clone() + DECISION_ENDPOINT), ); request.set_body(RequestContent::Json(Box::new(rule))); request.add_default_headers(); let response = state .api_client .send_request(state, request, None, false) .await; match response { Err(error) => { router_env::error!("Failed while calling the decision service: {:?}", error); Err(error) } Ok(response) => { router_env::info!("Decision service response: {:?}", response); Ok(()) } } } pub async fn revoke_api_key( state: &SessionState, api_key: Secret<String>, ) -> CustomResult<(), ApiClientError> { let decision_config = if let Some(config) = &state.conf.decision { config } else { return Ok(()); }; let rule = RuleDeleteRequest { tag: state.tenant.schema.clone(), variant: AuthType::ApiKey { api_key }, }; call_decision_service(state, decision_config, rule, RULE_DELETE_METHOD).await } /// Safety: i64::MAX < u64::MAX #[allow(clippy::as_conversions)] pub fn convert_expiry(expiry: time::PrimitiveDateTime) -> u64 { let now = common_utils::date_time::now(); let duration = expiry - now; let output = duration.whole_seconds(); match output { i64::MIN..=0 => 0, _ => output as u64, } } pub fn spawn_tracked_job<E, F>(future: F, request_type: &'static str) where E: std::fmt::Debug, F: futures::Future<Output = Result<(), E>> + Send + 'static, { metrics::API_KEY_REQUEST_INITIATED .add(1, router_env::metric_attributes!(("type", request_type))); tokio::spawn(async move { match future.await { Ok(_) => { metrics::API_KEY_REQUEST_COMPLETED .add(1, router_env::metric_attributes!(("type", request_type))); } Err(e) => { router_env::error!("Error in tracked job: {:?}", e); } } }); }
crates/router/src/services/authentication/decision.rs
router::src::services::authentication::decision
1,500
true
// File: crates/router/src/services/authentication/detached.rs // Module: router::src::services::authentication::detached use std::{borrow::Cow, string::ToString}; use actix_web::http::header::HeaderMap; use common_utils::{ crypto::VerifySignature, id_type::{ApiKeyId, MerchantId}, }; use error_stack::ResultExt; use hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse; use crate::core::errors::RouterResult; const HEADER_AUTH_TYPE: &str = "x-auth-type"; const HEADER_MERCHANT_ID: &str = "x-merchant-id"; const HEADER_KEY_ID: &str = "x-key-id"; const HEADER_CHECKSUM: &str = "x-checksum"; #[derive(Debug)] pub struct ExtractedPayload { pub payload_type: PayloadType, pub merchant_id: Option<MerchantId>, pub key_id: Option<ApiKeyId>, } #[derive(strum::EnumString, strum::Display, PartialEq, Debug)] #[strum(serialize_all = "snake_case")] pub enum PayloadType { ApiKey, PublishableKey, } pub trait GetAuthType { fn get_auth_type(&self) -> PayloadType; } impl ExtractedPayload { pub fn from_headers(headers: &HeaderMap) -> RouterResult<Self> { let merchant_id = headers .get(HEADER_MERCHANT_ID) .and_then(|value| value.to_str().ok()) .ok_or_else(|| ApiErrorResponse::InvalidRequestData { message: format!("`{HEADER_MERCHANT_ID}` header is invalid or not present"), }) .map_err(error_stack::Report::from) .and_then(|merchant_id| { MerchantId::try_from(Cow::from(merchant_id.to_string())).change_context( ApiErrorResponse::InvalidRequestData { message: format!( "`{HEADER_MERCHANT_ID}` header is invalid or not present", ), }, ) })?; let auth_type: PayloadType = headers .get(HEADER_AUTH_TYPE) .and_then(|inner| inner.to_str().ok()) .ok_or_else(|| ApiErrorResponse::InvalidRequestData { message: format!("`{HEADER_AUTH_TYPE}` header not present"), })? .parse::<PayloadType>() .change_context(ApiErrorResponse::InvalidRequestData { message: format!("`{HEADER_AUTH_TYPE}` header not present"), })?; let key_id = headers .get(HEADER_KEY_ID) .and_then(|value| value.to_str().ok()) .map(|key_id| ApiKeyId::try_from(Cow::from(key_id.to_string()))) .transpose() .change_context(ApiErrorResponse::InvalidRequestData { message: format!("`{HEADER_KEY_ID}` header is invalid or not present"), })?; Ok(Self { payload_type: auth_type, merchant_id: Some(merchant_id), key_id, }) } pub fn verify_checksum( &self, headers: &HeaderMap, algo: impl VerifySignature, secret: &[u8], ) -> bool { let output = || { let checksum = headers.get(HEADER_CHECKSUM)?.to_str().ok()?; let payload = self.generate_payload(); algo.verify_signature(secret, &hex::decode(checksum).ok()?, payload.as_bytes()) .ok() }; output().unwrap_or(false) } // The payload should be `:` separated strings of all the fields fn generate_payload(&self) -> String { append_option( &self.payload_type.to_string(), &self .merchant_id .as_ref() .map(|inner| append_api_key(inner.get_string_repr(), &self.key_id)), ) } } #[inline] fn append_option(prefix: &str, data: &Option<String>) -> String { match data { Some(inner) => format!("{prefix}:{inner}"), None => prefix.to_string(), } } #[inline] fn append_api_key(prefix: &str, data: &Option<ApiKeyId>) -> String { match data { Some(inner) => format!("{}:{}", prefix, inner.get_string_repr()), None => prefix.to_string(), } }
crates/router/src/services/authentication/detached.rs
router::src::services::authentication::detached
906
true
// File: crates/router/src/services/authentication/cookies.rs // Module: router::src::services::authentication::cookies use cookie::Cookie; #[cfg(feature = "olap")] use cookie::{ time::{Duration, OffsetDateTime}, SameSite, }; use error_stack::{report, ResultExt}; #[cfg(feature = "olap")] use masking::Mask; #[cfg(feature = "olap")] use masking::{ExposeInterface, Secret}; use crate::{ consts::JWT_TOKEN_COOKIE_NAME, core::errors::{ApiErrorResponse, RouterResult}, }; #[cfg(feature = "olap")] use crate::{ consts::JWT_TOKEN_TIME_IN_SECS, core::errors::{UserErrors, UserResponse}, services::ApplicationResponse, }; #[cfg(feature = "olap")] pub fn set_cookie_response<R>(response: R, token: Secret<String>) -> UserResponse<R> { let jwt_expiry_in_seconds = JWT_TOKEN_TIME_IN_SECS .try_into() .map_err(|_| UserErrors::InternalServerError)?; let (expiry, max_age) = get_expiry_and_max_age_from_seconds(jwt_expiry_in_seconds); let header_value = create_cookie(token, expiry, max_age) .to_string() .into_masked(); let header_key = get_set_cookie_header(); let header = vec![(header_key, header_value)]; Ok(ApplicationResponse::JsonWithHeaders((response, header))) } #[cfg(feature = "olap")] pub fn remove_cookie_response() -> UserResponse<()> { let (expiry, max_age) = get_expiry_and_max_age_from_seconds(0); let header_key = get_set_cookie_header(); let header_value = create_cookie("".to_string().into(), expiry, max_age) .to_string() .into_masked(); let header = vec![(header_key, header_value)]; Ok(ApplicationResponse::JsonWithHeaders(((), header))) } pub fn get_jwt_from_cookies(cookies: &str) -> RouterResult<String> { Cookie::split_parse(cookies) .find_map(|cookie| { cookie .ok() .filter(|parsed_cookie| parsed_cookie.name() == JWT_TOKEN_COOKIE_NAME) .map(|parsed_cookie| parsed_cookie.value().to_owned()) }) .ok_or(report!(ApiErrorResponse::InvalidJwtToken)) .attach_printable("Unable to find JWT token in cookies") } #[cfg(feature = "olap")] fn create_cookie<'c>( token: Secret<String>, expires: OffsetDateTime, max_age: Duration, ) -> Cookie<'c> { Cookie::build((JWT_TOKEN_COOKIE_NAME, token.expose())) .http_only(true) .secure(true) .same_site(SameSite::Strict) .path("/") .expires(expires) .max_age(max_age) .build() } #[cfg(feature = "olap")] fn get_expiry_and_max_age_from_seconds(seconds: i64) -> (OffsetDateTime, Duration) { let max_age = Duration::seconds(seconds); let expiry = OffsetDateTime::now_utc().saturating_add(max_age); (expiry, max_age) } #[cfg(feature = "olap")] fn get_set_cookie_header() -> String { actix_http::header::SET_COOKIE.to_string() } pub fn get_cookie_header() -> String { actix_http::header::COOKIE.to_string() }
crates/router/src/services/authentication/cookies.rs
router::src::services::authentication::cookies
716
true
// File: crates/router/src/services/authentication/blacklist.rs // Module: router::src::services::authentication::blacklist use std::sync::Arc; #[cfg(feature = "olap")] use common_utils::date_time; use error_stack::ResultExt; use redis_interface::RedisConnectionPool; use super::AuthToken; #[cfg(feature = "olap")] use super::{SinglePurposeOrLoginToken, SinglePurposeToken}; #[cfg(feature = "email")] use crate::consts::{EMAIL_TOKEN_BLACKLIST_PREFIX, EMAIL_TOKEN_TIME_IN_SECS}; use crate::{ consts::{JWT_TOKEN_TIME_IN_SECS, ROLE_BLACKLIST_PREFIX, USER_BLACKLIST_PREFIX}, core::errors::{ApiErrorResponse, RouterResult}, routes::app::SessionStateInfo, }; #[cfg(feature = "olap")] use crate::{ core::errors::{UserErrors, UserResult}, routes::SessionState, services::authorization as authz, }; #[cfg(feature = "olap")] pub async fn insert_user_in_blacklist(state: &SessionState, user_id: &str) -> UserResult<()> { let user_blacklist_key = format!("{USER_BLACKLIST_PREFIX}{user_id}"); let expiry = expiry_to_i64(JWT_TOKEN_TIME_IN_SECS).change_context(UserErrors::InternalServerError)?; let redis_conn = get_redis_connection_for_global_tenant(state) .change_context(UserErrors::InternalServerError)?; redis_conn .set_key_with_expiry( &user_blacklist_key.as_str().into(), date_time::now_unix_timestamp(), expiry, ) .await .change_context(UserErrors::InternalServerError) } #[cfg(feature = "olap")] pub async fn insert_role_in_blacklist(state: &SessionState, role_id: &str) -> UserResult<()> { let role_blacklist_key = format!("{ROLE_BLACKLIST_PREFIX}{role_id}"); let expiry = expiry_to_i64(JWT_TOKEN_TIME_IN_SECS).change_context(UserErrors::InternalServerError)?; let redis_conn = get_redis_connection_for_global_tenant(state) .change_context(UserErrors::InternalServerError)?; redis_conn .set_key_with_expiry( &role_blacklist_key.as_str().into(), date_time::now_unix_timestamp(), expiry, ) .await .change_context(UserErrors::InternalServerError)?; invalidate_role_cache(state, role_id) .await .change_context(UserErrors::InternalServerError) } #[cfg(feature = "olap")] async fn invalidate_role_cache(state: &SessionState, role_id: &str) -> RouterResult<()> { let redis_conn = get_redis_connection_for_global_tenant(state)?; redis_conn .delete_key(&authz::get_cache_key_from_role_id(role_id).as_str().into()) .await .map(|_| ()) .change_context(ApiErrorResponse::InternalServerError) } pub async fn check_user_in_blacklist<A: SessionStateInfo>( state: &A, user_id: &str, token_expiry: u64, ) -> RouterResult<bool> { let token = format!("{USER_BLACKLIST_PREFIX}{user_id}"); let token_issued_at = expiry_to_i64(token_expiry - JWT_TOKEN_TIME_IN_SECS)?; let redis_conn = get_redis_connection_for_global_tenant(state)?; redis_conn .get_key::<Option<i64>>(&token.as_str().into()) .await .change_context(ApiErrorResponse::InternalServerError) .map(|timestamp| timestamp > Some(token_issued_at)) } pub async fn check_role_in_blacklist<A: SessionStateInfo>( state: &A, role_id: &str, token_expiry: u64, ) -> RouterResult<bool> { let token = format!("{ROLE_BLACKLIST_PREFIX}{role_id}"); let token_issued_at = expiry_to_i64(token_expiry - JWT_TOKEN_TIME_IN_SECS)?; let redis_conn = get_redis_connection_for_global_tenant(state)?; redis_conn .get_key::<Option<i64>>(&token.as_str().into()) .await .change_context(ApiErrorResponse::InternalServerError) .map(|timestamp| timestamp > Some(token_issued_at)) } #[cfg(feature = "email")] pub async fn insert_email_token_in_blacklist(state: &SessionState, token: &str) -> UserResult<()> { let redis_conn = get_redis_connection_for_global_tenant(state) .change_context(UserErrors::InternalServerError)?; let blacklist_key = format!("{EMAIL_TOKEN_BLACKLIST_PREFIX}{token}"); let expiry = expiry_to_i64(EMAIL_TOKEN_TIME_IN_SECS).change_context(UserErrors::InternalServerError)?; redis_conn .set_key_with_expiry(&blacklist_key.as_str().into(), true, expiry) .await .change_context(UserErrors::InternalServerError) } #[cfg(feature = "email")] pub async fn check_email_token_in_blacklist(state: &SessionState, token: &str) -> UserResult<()> { let redis_conn = get_redis_connection_for_global_tenant(state) .change_context(UserErrors::InternalServerError)?; let blacklist_key = format!("{EMAIL_TOKEN_BLACKLIST_PREFIX}{token}"); let key_exists = redis_conn .exists::<()>(&blacklist_key.as_str().into()) .await .change_context(UserErrors::InternalServerError)?; if key_exists { return Err(UserErrors::LinkInvalid.into()); } Ok(()) } fn get_redis_connection_for_global_tenant<A: SessionStateInfo>( state: &A, ) -> RouterResult<Arc<RedisConnectionPool>> { state .global_store() .get_redis_conn() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection") } fn expiry_to_i64(expiry: u64) -> RouterResult<i64> { i64::try_from(expiry).change_context(ApiErrorResponse::InternalServerError) } #[async_trait::async_trait] pub trait BlackList { async fn check_in_blacklist<A>(&self, state: &A) -> RouterResult<bool> where A: SessionStateInfo + Sync; } #[async_trait::async_trait] impl BlackList for AuthToken { async fn check_in_blacklist<A>(&self, state: &A) -> RouterResult<bool> where A: SessionStateInfo + Sync, { Ok( check_user_in_blacklist(state, &self.user_id, self.exp).await? || check_role_in_blacklist(state, &self.role_id, self.exp).await?, ) } } #[cfg(feature = "olap")] #[async_trait::async_trait] impl BlackList for SinglePurposeToken { async fn check_in_blacklist<A>(&self, state: &A) -> RouterResult<bool> where A: SessionStateInfo + Sync, { check_user_in_blacklist(state, &self.user_id, self.exp).await } } #[cfg(feature = "olap")] #[async_trait::async_trait] impl BlackList for SinglePurposeOrLoginToken { async fn check_in_blacklist<A>(&self, state: &A) -> RouterResult<bool> where A: SessionStateInfo + Sync, { check_user_in_blacklist(state, &self.user_id, self.exp).await } }
crates/router/src/services/authentication/blacklist.rs
router::src::services::authentication::blacklist
1,548
true
// File: crates/router/src/services/email/types.rs // Module: router::src::services::email::types use api_models::user::dashboard_metadata::ProdIntent; use common_enums::{EntityType, MerchantProductType}; use common_utils::{errors::CustomResult, pii, types::user::EmailThemeConfig}; use error_stack::ResultExt; use external_services::email::{EmailContents, EmailData, EmailError}; use masking::{ExposeInterface, PeekInterface, Secret}; use crate::{configs, consts, routes::SessionState}; #[cfg(feature = "olap")] use crate::{ core::errors::{UserErrors, UserResult}, services::jwt, types::domain, }; pub enum EmailBody { Verify { link: String, entity_name: String, entity_logo_url: String, primary_color: String, background_color: String, foreground_color: String, }, Reset { link: String, user_name: String, entity_name: String, entity_logo_url: String, primary_color: String, background_color: String, foreground_color: String, }, MagicLink { link: String, user_name: String, entity_name: String, entity_logo_url: String, primary_color: String, background_color: String, foreground_color: String, }, InviteUser { link: String, user_name: String, entity_name: String, entity_logo_url: String, primary_color: String, background_color: String, foreground_color: String, }, AcceptInviteFromEmail { link: String, user_name: String, entity_name: String, entity_logo_url: String, primary_color: String, background_color: String, foreground_color: String, }, BizEmailProd { user_name: String, poc_email: String, legal_business_name: String, business_location: String, business_website: String, product_type: MerchantProductType, }, ReconActivation { user_name: String, }, ProFeatureRequest { feature_name: String, merchant_id: common_utils::id_type::MerchantId, user_name: String, user_email: String, }, ApiKeyExpiryReminder { expires_in: u8, api_key_name: String, prefix: String, }, WelcomeToCommunity, } pub mod html { use crate::services::email::types::EmailBody; pub fn get_html_body(email_body: EmailBody) -> String { match email_body { EmailBody::Verify { link, entity_name, entity_logo_url, primary_color, background_color, foreground_color, } => { format!( include_str!("assets/verify.html"), link = link, entity_name = entity_name, entity_logo_url = entity_logo_url, primary_color = primary_color, background_color = background_color, foreground_color = foreground_color ) } EmailBody::Reset { link, user_name, entity_name, entity_logo_url, primary_color, background_color, foreground_color, } => { format!( include_str!("assets/reset.html"), link = link, username = user_name, entity_name = entity_name, entity_logo_url = entity_logo_url, primary_color = primary_color, background_color = background_color, foreground_color = foreground_color ) } EmailBody::MagicLink { link, user_name, entity_name, entity_logo_url, primary_color, background_color, foreground_color, } => { format!( include_str!("assets/magic_link.html"), username = user_name, link = link, entity_name = entity_name, entity_logo_url = entity_logo_url, primary_color = primary_color, background_color = background_color, foreground_color = foreground_color ) } EmailBody::InviteUser { link, user_name, entity_name, entity_logo_url, primary_color, background_color, foreground_color, } => { format!( include_str!("assets/invite.html"), username = user_name, link = link, entity_name = entity_name, entity_logo_url = entity_logo_url, primary_color = primary_color, background_color = background_color, foreground_color = foreground_color ) } // TODO: Change the linked html for accept invite from email EmailBody::AcceptInviteFromEmail { link, user_name, entity_name, entity_logo_url, primary_color, background_color, foreground_color, } => { format!( include_str!("assets/invite.html"), username = user_name, link = link, entity_name = entity_name, entity_logo_url = entity_logo_url, primary_color = primary_color, background_color = background_color, foreground_color = foreground_color ) } EmailBody::ReconActivation { user_name } => { format!( include_str!("assets/recon_activation.html"), username = user_name, ) } EmailBody::BizEmailProd { user_name, poc_email, legal_business_name, business_location, business_website, product_type, } => { format!( include_str!("assets/bizemailprod.html"), poc_email = poc_email, legal_business_name = legal_business_name, business_location = business_location, business_website = business_website, username = user_name, product_type = product_type ) } EmailBody::ProFeatureRequest { feature_name, merchant_id, user_name, user_email, } => format!( "Dear Hyperswitch Support Team, Dashboard Pro Feature Request, Feature name : {feature_name} Merchant ID : {} Merchant Name : {user_name} Email : {user_email} (note: This is an auto generated email. Use merchant email for any further communications)", merchant_id.get_string_repr() ), EmailBody::ApiKeyExpiryReminder { expires_in, api_key_name, prefix, } => format!( include_str!("assets/api_key_expiry_reminder.html"), api_key_name = api_key_name, prefix = prefix, expires_in = expires_in, ), EmailBody::WelcomeToCommunity => { include_str!("assets/welcome_to_community.html").to_string() } } } } #[derive(serde::Serialize, serde::Deserialize)] pub struct EmailToken { email: String, flow: domain::Origin, exp: u64, entity: Option<Entity>, } #[derive(serde::Serialize, serde::Deserialize, Clone)] pub struct Entity { pub entity_id: String, pub entity_type: EntityType, } impl Entity { pub fn get_entity_type(&self) -> EntityType { self.entity_type } pub fn get_entity_id(&self) -> &str { &self.entity_id } } impl EmailToken { pub async fn new_token( email: domain::UserEmail, entity: Option<Entity>, flow: domain::Origin, settings: &configs::Settings, ) -> UserResult<String> { let expiration_duration = std::time::Duration::from_secs(consts::EMAIL_TOKEN_TIME_IN_SECS); let exp = jwt::generate_exp(expiration_duration)?.as_secs(); let token_payload = Self { email: email.get_secret().expose(), flow, exp, entity, }; jwt::generate_jwt(&token_payload, settings).await } pub fn get_email(&self) -> UserResult<domain::UserEmail> { pii::Email::try_from(self.email.clone()) .change_context(UserErrors::InternalServerError) .and_then(domain::UserEmail::from_pii_email) } pub fn get_entity(&self) -> Option<&Entity> { self.entity.as_ref() } pub fn get_flow(&self) -> domain::Origin { self.flow.clone() } } pub fn get_link_with_token( base_url: impl std::fmt::Display, token: impl std::fmt::Display, action: impl std::fmt::Display, auth_id: &Option<impl std::fmt::Display>, theme_id: &Option<impl std::fmt::Display>, ) -> String { let mut email_url = format!("{base_url}/user/{action}?token={token}"); if let Some(auth_id) = auth_id { email_url = format!("{email_url}&auth_id={auth_id}"); } if let Some(theme_id) = theme_id { email_url = format!("{email_url}&theme_id={theme_id}"); } email_url } pub struct VerifyEmail { pub recipient_email: domain::UserEmail, pub settings: std::sync::Arc<configs::Settings>, pub auth_id: Option<String>, pub theme_id: Option<String>, pub theme_config: EmailThemeConfig, } /// Currently only HTML is supported #[async_trait::async_trait] impl EmailData for VerifyEmail { async fn get_email_data(&self, base_url: &str) -> CustomResult<EmailContents, EmailError> { let token = EmailToken::new_token( self.recipient_email.clone(), None, domain::Origin::VerifyEmail, &self.settings, ) .await .change_context(EmailError::TokenGenerationFailure)?; let verify_email_link = get_link_with_token( base_url, token, "verify_email", &self.auth_id, &self.theme_id, ); let body = html::get_html_body(EmailBody::Verify { link: verify_email_link, entity_name: self.theme_config.entity_name.clone(), entity_logo_url: self.theme_config.entity_logo_url.clone(), primary_color: self.theme_config.primary_color.clone(), background_color: self.theme_config.background_color.clone(), foreground_color: self.theme_config.foreground_color.clone(), }); Ok(EmailContents { subject: format!( "Welcome to the {} community!", self.theme_config.entity_name ), body: external_services::email::IntermediateString::new(body), recipient: self.recipient_email.clone().into_inner(), }) } } pub struct ResetPassword { pub recipient_email: domain::UserEmail, pub user_name: domain::UserName, pub settings: std::sync::Arc<configs::Settings>, pub auth_id: Option<String>, pub theme_id: Option<String>, pub theme_config: EmailThemeConfig, } #[async_trait::async_trait] impl EmailData for ResetPassword { async fn get_email_data(&self, base_url: &str) -> CustomResult<EmailContents, EmailError> { let token = EmailToken::new_token( self.recipient_email.clone(), None, domain::Origin::ResetPassword, &self.settings, ) .await .change_context(EmailError::TokenGenerationFailure)?; let reset_password_link = get_link_with_token( base_url, token, "set_password", &self.auth_id, &self.theme_id, ); let body = html::get_html_body(EmailBody::Reset { link: reset_password_link, user_name: self.user_name.clone().get_secret().expose(), entity_name: self.theme_config.entity_name.clone(), entity_logo_url: self.theme_config.entity_logo_url.clone(), primary_color: self.theme_config.primary_color.clone(), background_color: self.theme_config.background_color.clone(), foreground_color: self.theme_config.foreground_color.clone(), }); Ok(EmailContents { subject: format!( "Get back to {} - Reset Your Password Now!", self.theme_config.entity_name ), body: external_services::email::IntermediateString::new(body), recipient: self.recipient_email.clone().into_inner(), }) } } pub struct MagicLink { pub recipient_email: domain::UserEmail, pub user_name: domain::UserName, pub settings: std::sync::Arc<configs::Settings>, pub auth_id: Option<String>, pub theme_id: Option<String>, pub theme_config: EmailThemeConfig, } #[async_trait::async_trait] impl EmailData for MagicLink { async fn get_email_data(&self, base_url: &str) -> CustomResult<EmailContents, EmailError> { let token = EmailToken::new_token( self.recipient_email.clone(), None, domain::Origin::MagicLink, &self.settings, ) .await .change_context(EmailError::TokenGenerationFailure)?; let magic_link_login = get_link_with_token( base_url, token, "verify_email", &self.auth_id, &self.theme_id, ); let body = html::get_html_body(EmailBody::MagicLink { link: magic_link_login, user_name: self.user_name.clone().get_secret().expose(), entity_name: self.theme_config.entity_name.clone(), entity_logo_url: self.theme_config.entity_logo_url.clone(), primary_color: self.theme_config.primary_color.clone(), background_color: self.theme_config.background_color.clone(), foreground_color: self.theme_config.foreground_color.clone(), }); Ok(EmailContents { subject: format!( "Unlock {}: Use Your Magic Link to Sign In", self.theme_config.entity_name ), body: external_services::email::IntermediateString::new(body), recipient: self.recipient_email.clone().into_inner(), }) } } pub struct InviteUser { pub recipient_email: domain::UserEmail, pub user_name: domain::UserName, pub settings: std::sync::Arc<configs::Settings>, pub entity: Entity, pub auth_id: Option<String>, pub theme_id: Option<String>, pub theme_config: EmailThemeConfig, } #[async_trait::async_trait] impl EmailData for InviteUser { async fn get_email_data(&self, base_url: &str) -> CustomResult<EmailContents, EmailError> { let token = EmailToken::new_token( self.recipient_email.clone(), Some(self.entity.clone()), domain::Origin::AcceptInvitationFromEmail, &self.settings, ) .await .change_context(EmailError::TokenGenerationFailure)?; let invite_user_link = get_link_with_token( base_url, token, "accept_invite_from_email", &self.auth_id, &self.theme_id, ); let body = html::get_html_body(EmailBody::AcceptInviteFromEmail { link: invite_user_link, user_name: self.user_name.clone().get_secret().expose(), entity_name: self.theme_config.entity_name.clone(), entity_logo_url: self.theme_config.entity_logo_url.clone(), primary_color: self.theme_config.primary_color.clone(), background_color: self.theme_config.background_color.clone(), foreground_color: self.theme_config.foreground_color.clone(), }); Ok(EmailContents { subject: format!( "You have been invited to join {} Community!", self.theme_config.entity_name ), body: external_services::email::IntermediateString::new(body), recipient: self.recipient_email.clone().into_inner(), }) } } pub struct ReconActivation { pub recipient_email: domain::UserEmail, pub user_name: domain::UserName, pub subject: &'static str, pub theme_id: Option<String>, pub theme_config: EmailThemeConfig, } #[async_trait::async_trait] impl EmailData for ReconActivation { async fn get_email_data(&self, _base_url: &str) -> CustomResult<EmailContents, EmailError> { let body = html::get_html_body(EmailBody::ReconActivation { user_name: self.user_name.clone().get_secret().expose(), }); Ok(EmailContents { subject: self.subject.to_string(), body: external_services::email::IntermediateString::new(body), recipient: self.recipient_email.clone().into_inner(), }) } } pub struct BizEmailProd { pub recipient_email: domain::UserEmail, pub user_name: Secret<String>, pub poc_email: Secret<String>, pub legal_business_name: String, pub business_location: String, pub business_website: String, pub settings: std::sync::Arc<configs::Settings>, pub theme_id: Option<String>, pub theme_config: EmailThemeConfig, pub product_type: MerchantProductType, } impl BizEmailProd { pub fn new( state: &SessionState, data: ProdIntent, theme_id: Option<String>, theme_config: EmailThemeConfig, ) -> UserResult<Self> { Ok(Self { recipient_email: domain::UserEmail::from_pii_email( state.conf.email.prod_intent_recipient_email.clone(), )?, settings: state.conf.clone(), user_name: data .poc_name .map(|s| Secret::new(s.peek().clone().into_inner())) .unwrap_or_default(), poc_email: data .poc_email .map(|s| Secret::new(s.peek().clone())) .unwrap_or_default(), legal_business_name: data .legal_business_name .map(|s| s.into_inner()) .unwrap_or_default(), business_location: data .business_location .unwrap_or(common_enums::CountryAlpha2::AD) .to_string(), business_website: data .business_website .map(|s| s.into_inner()) .unwrap_or_default(), theme_id, theme_config, product_type: data.product_type, }) } } #[async_trait::async_trait] impl EmailData for BizEmailProd { async fn get_email_data(&self, _base_url: &str) -> CustomResult<EmailContents, EmailError> { let body = html::get_html_body(EmailBody::BizEmailProd { user_name: self.user_name.clone().expose(), poc_email: self.poc_email.clone().expose(), legal_business_name: self.legal_business_name.clone(), business_location: self.business_location.clone(), business_website: self.business_website.clone(), product_type: self.product_type, }); Ok(EmailContents { subject: "New Prod Intent".to_string(), body: external_services::email::IntermediateString::new(body), recipient: self.recipient_email.clone().into_inner(), }) } } pub struct ProFeatureRequest { pub recipient_email: domain::UserEmail, pub feature_name: String, pub merchant_id: common_utils::id_type::MerchantId, pub user_name: domain::UserName, pub user_email: domain::UserEmail, pub subject: String, pub theme_id: Option<String>, pub theme_config: EmailThemeConfig, } #[async_trait::async_trait] impl EmailData for ProFeatureRequest { async fn get_email_data(&self, _base_url: &str) -> CustomResult<EmailContents, EmailError> { let recipient = self.recipient_email.clone().into_inner(); let body = html::get_html_body(EmailBody::ProFeatureRequest { user_name: self.user_name.clone().get_secret().expose(), feature_name: self.feature_name.clone(), merchant_id: self.merchant_id.clone(), user_email: self.user_email.clone().get_secret().expose(), }); Ok(EmailContents { subject: self.subject.clone(), body: external_services::email::IntermediateString::new(body), recipient, }) } } pub struct ApiKeyExpiryReminder { pub recipient_email: domain::UserEmail, pub subject: &'static str, pub expires_in: u8, pub api_key_name: String, pub prefix: String, pub theme_id: Option<String>, pub theme_config: EmailThemeConfig, } #[async_trait::async_trait] impl EmailData for ApiKeyExpiryReminder { async fn get_email_data(&self, _base_url: &str) -> CustomResult<EmailContents, EmailError> { let recipient = self.recipient_email.clone().into_inner(); let body = html::get_html_body(EmailBody::ApiKeyExpiryReminder { expires_in: self.expires_in, api_key_name: self.api_key_name.clone(), prefix: self.prefix.clone(), }); Ok(EmailContents { subject: self.subject.to_string(), body: external_services::email::IntermediateString::new(body), recipient, }) } } pub struct WelcomeToCommunity { pub recipient_email: domain::UserEmail, } #[async_trait::async_trait] impl EmailData for WelcomeToCommunity { async fn get_email_data(&self, _base_url: &str) -> CustomResult<EmailContents, EmailError> { let body = html::get_html_body(EmailBody::WelcomeToCommunity); Ok(EmailContents { subject: "Thank you for signing up on Hyperswitch Dashboard!".to_string(), body: external_services::email::IntermediateString::new(body), recipient: self.recipient_email.clone().into_inner(), }) } }
crates/router/src/services/email/types.rs
router::src::services::email::types
4,557
true
// File: connector-template/test.rs // Module: connector-template::test use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData}; use masking::Secret; use router::{ types::{self, api, storage::enums, }}; use crate::utils::{self, ConnectorActions}; use test_utils::connector_auth; #[derive(Clone, Copy)] struct {{project-name | downcase | pascal_case}}Test; impl ConnectorActions for {{project-name | downcase | pascal_case}}Test {} impl utils::Connector for {{project-name | downcase | pascal_case}}Test { fn get_data(&self) -> api::ConnectorData { use router::connector::{{project-name | downcase | pascal_case}}; utils::construct_connector_data_old( Box::new({{project-name | downcase | pascal_case}}::new()), types::Connector::Plaid, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .{{project-name | downcase}} .expect("Missing connector authentication configuration").into(), ) } fn get_name(&self) -> String { "{{project-name | downcase}}".to_string() } } static CONNECTOR: {{project-name | downcase | pascal_case}}Test = {{project-name | downcase | pascal_case}}Test {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund(payment_method_details(), None, None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund(payment_method_details(), None, None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR.make_payment(payment_method_details(), get_default_payment_info()).await.unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR.make_payment(payment_method_details(), get_default_payment_info()).await.unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR.make_payment(payment_method_details(), get_default_payment_info()).await.unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
connector-template/test.rs
connector-template::test
2,964
true
// File: connector-template/transformers.rs // Module: connector-template::transformers use common_enums::enums; use serde::{Deserialize, Serialize}; use masking::Secret; use common_utils::types::{StringMinorUnit}; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, router_data::{ConnectorAuthType, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::ResponseId, router_response_types::{PaymentsResponseData, RefundsResponseData}, types::{PaymentsAuthorizeRouterData, RefundsRouterData}, }; use hyperswitch_interfaces::errors; use crate::types::{RefundsResponseRouterData, ResponseRouterData}; //TODO: Fill the struct with respective fields pub struct {{project-name | downcase | pascal_case}}RouterData<T> { pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. pub router_data: T, } impl<T> From<( StringMinorUnit, T, )> for {{project-name | downcase | pascal_case}}RouterData<T> { fn from( (amount, item): ( StringMinorUnit, T, ), ) -> Self { //Todo : use utils to convert the amount to the type of amount that a connector accepts Self { amount, router_data: item, } } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Serialize, PartialEq)] pub struct {{project-name | downcase | pascal_case}}PaymentsRequest { amount: StringMinorUnit, card: {{project-name | downcase | pascal_case}}Card } #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct {{project-name | downcase | pascal_case}}Card { number: cards::CardNumber, expiry_month: Secret<String>, expiry_year: Secret<String>, cvc: Secret<String>, complete: bool, } impl TryFrom<&{{project-name | downcase | pascal_case}}RouterData<&PaymentsAuthorizeRouterData>> for {{project-name | downcase | pascal_case}}PaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &{{project-name | downcase | pascal_case}}RouterData<&PaymentsAuthorizeRouterData>) -> Result<Self,Self::Error> { match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Card(_) => { Err(errors::ConnectorError::NotImplemented("Card payment method not implemented".to_string()).into()) }, _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), } } } //TODO: Fill the struct with respective fields // Auth Struct pub struct {{project-name | downcase | pascal_case}}AuthType { pub(super) api_key: Secret<String> } impl TryFrom<&ConnectorAuthType> for {{project-name | downcase | pascal_case}}AuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::HeaderKey { api_key } => Ok(Self { api_key: api_key.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } // PaymentsResponse //TODO: Append the remaining status flags #[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "lowercase")] pub enum {{project-name | downcase | pascal_case}}PaymentStatus { Succeeded, Failed, #[default] Processing, } impl From<{{project-name | downcase | pascal_case}}PaymentStatus> for common_enums::AttemptStatus { fn from(item: {{project-name | downcase | pascal_case}}PaymentStatus) -> Self { match item { {{project-name | downcase | pascal_case}}PaymentStatus::Succeeded => Self::Charged, {{project-name | downcase | pascal_case}}PaymentStatus::Failed => Self::Failure, {{project-name | downcase | pascal_case}}PaymentStatus::Processing => Self::Authorizing, } } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct {{project-name | downcase | pascal_case}}PaymentsResponse { status: {{project-name | downcase | pascal_case}}PaymentStatus, id: String, } impl<F,T> TryFrom<ResponseRouterData<F, {{project-name | downcase | pascal_case}}PaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: ResponseRouterData<F, {{project-name | downcase | pascal_case}}PaymentsResponse, T, PaymentsResponseData>) -> Result<Self,Self::Error> { Ok(Self { status: common_enums::AttemptStatus::from(item.response.status), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }) } } //TODO: Fill the struct with respective fields // REFUND : // Type definition for RefundRequest #[derive(Default, Debug, Serialize)] pub struct {{project-name | downcase | pascal_case}}RefundRequest { pub amount: StringMinorUnit } impl<F> TryFrom<&{{project-name | downcase | pascal_case}}RouterData<&RefundsRouterData<F>>> for {{project-name | downcase | pascal_case}}RefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &{{project-name | downcase | pascal_case}}RouterData<&RefundsRouterData<F>>) -> Result<Self,Self::Error> { Ok(Self { amount: item.amount.to_owned(), }) } } // Type definition for Refund Response #[allow(dead_code)] #[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)] pub enum RefundStatus { Succeeded, Failed, #[default] Processing, } impl From<RefundStatus> for enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { RefundStatus::Succeeded => Self::Success, RefundStatus::Failed => Self::Failure, RefundStatus::Processing => Self::Pending, //TODO: Review mapping } } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct RefundResponse { id: String, status: RefundStatus } impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: RefundsResponseRouterData<RSync, RefundResponse>) -> Result<Self,Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct {{project-name | downcase | pascal_case}}ErrorResponse { pub status_code: u16, pub code: String, pub message: String, pub reason: Option<String>, pub network_advice_code: Option<String>, pub network_decline_code: Option<String>, pub network_error_message: Option<String>, }
connector-template/transformers.rs
connector-template::transformers
1,878
true
// File: connector-template/mod.rs // Module: connector-template::mod pub mod transformers; use error_stack::{report, ResultExt}; use masking::{ExposeInterface, Mask}; use common_utils::{ errors::CustomResult, ext_traits::BytesExt, types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector}, request::{Method, Request, RequestBuilder, RequestContent}, }; use hyperswitch_domain_models::{ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::{ access_token_auth::AccessTokenAuth, payments::{ Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void, }, refunds::{Execute, RSync}, }, router_request_types::{ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, router_response_types::{PaymentsResponseData, RefundsResponseData}, types::{ PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{ api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation, ConnectorSpecifications}, configs::Connectors, errors, events::connector_api_logs::ConnectorEvent, types::{self, Response}, webhooks, }; use std::sync::LazyLock; use common_enums::enums; use hyperswitch_interfaces::api::ConnectorSpecifications; use hyperswitch_domain_models::router_response_types::{ConnectorInfo, SupportedPaymentMethods}; use crate::{ constants::headers, types::ResponseRouterData, utils, }; use hyperswitch_domain_models::payment_method_data::PaymentMethodData; use transformers as {{project-name | downcase}}; #[derive(Clone)] pub struct {{project-name | downcase | pascal_case}} { amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync) } impl {{project-name | downcase | pascal_case}} { pub fn new() -> &'static Self { &Self { amount_converter: &StringMinorUnitForConnector } } } impl api::Payment for {{project-name | downcase | pascal_case}} {} impl api::PaymentSession for {{project-name | downcase | pascal_case}} {} impl api::ConnectorAccessToken for {{project-name | downcase | pascal_case}} {} impl api::MandateSetup for {{project-name | downcase | pascal_case}} {} impl api::PaymentAuthorize for {{project-name | downcase | pascal_case}} {} impl api::PaymentSync for {{project-name | downcase | pascal_case}} {} impl api::PaymentCapture for {{project-name | downcase | pascal_case}} {} impl api::PaymentVoid for {{project-name | downcase | pascal_case}} {} impl api::Refund for {{project-name | downcase | pascal_case}} {} impl api::RefundExecute for {{project-name | downcase | pascal_case}} {} impl api::RefundSync for {{project-name | downcase | pascal_case}} {} impl api::PaymentToken for {{project-name | downcase | pascal_case}} {} impl ConnectorIntegration< PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData, > for {{project-name | downcase | pascal_case}} { // Not Implemented (R) } impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for {{project-name | downcase | pascal_case}} where Self: ConnectorIntegration<Flow, Request, Response>,{ fn build_headers( &self, req: &RouterData<Flow, Request, Response>, _connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), self.get_content_type().to_string().into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); Ok(header) } } impl ConnectorCommon for {{project-name | downcase | pascal_case}} { fn id(&self) -> &'static str { "{{project-name | downcase}}" } fn get_currency_unit(&self) -> api::CurrencyUnit { todo!() // TODO! Check connector documentation, on which unit they are processing the currency. // If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor, // if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.{{project-name}}.base_url.as_ref() } fn get_auth_header(&self, auth_type:&ConnectorAuthType)-> CustomResult<Vec<(String,masking::Maskable<String>)>,errors::ConnectorError> { let auth = {{project-name | downcase}}::{{project-name | downcase | pascal_case}}AuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![(headers::AUTHORIZATION.to_string(), auth.api_key.expose().into_masked())]) } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: {{project-name | downcase}}::{{project-name | downcase | pascal_case}}ErrorResponse = res .response .parse_struct("{{project-name | downcase | pascal_case}}ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(ErrorResponse { status_code: res.status_code, code: response.code, message: response.message, reason: response.reason, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, }) } } impl ConnectorValidation for {{project-name | downcase | pascal_case}} { fn validate_mandate_payment( &self, _pm_type: Option<enums::PaymentMethodType>, pm_data: PaymentMethodData, ) -> CustomResult<(), errors::ConnectorError> { match pm_data { PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented( "validate_mandate_payment does not support cards".to_string(), ) .into()), _ => Ok(()), } } fn validate_psync_reference_id( &self, _data: &PaymentsSyncData, _is_three_ds: bool, _status: enums::AttemptStatus, _connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, ) -> CustomResult<(), errors::ConnectorError> { Ok(()) } } impl ConnectorIntegration< Session, PaymentsSessionData, PaymentsResponseData, > for {{project-name | downcase | pascal_case}} { //TODO: implement sessions flow } impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for {{project-name | downcase | pascal_case}} { } impl ConnectorIntegration< SetupMandate, SetupMandateRequestData, PaymentsResponseData, > for {{project-name | downcase | pascal_case}} { } impl ConnectorIntegration< Authorize, PaymentsAuthorizeData, PaymentsResponseData, > for {{project-name | downcase | pascal_case}} { fn get_headers(&self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors,) -> CustomResult<Vec<(String, masking::Maskable<String>)>,errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsAuthorizeRouterData, _connectors: &Connectors,) -> CustomResult<String,errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn get_request_body(&self, req: &PaymentsAuthorizeRouterData, _connectors: &Connectors,) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = utils::convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, )?; let connector_router_data = {{project-name | downcase}}::{{project-name | downcase | pascal_case}}RouterData::from(( amount, req, )); let connector_req = {{project-name | downcase}}::{{project-name | downcase | pascal_case}}PaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsAuthorizeType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(types::PaymentsAuthorizeType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsAuthorizeType::get_request_body(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsAuthorizeRouterData,errors::ConnectorError> { let response: {{project-name | downcase}}::{{project-name | downcase | pascal_case}}PaymentsResponse = res.response.parse_struct("{{project-name | downcase | pascal_case}} PaymentsAuthorizeResponse").change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response(&self, res: Response, event_builder: Option<&mut ConnectorEvent>) -> CustomResult<ErrorResponse,errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for {{project-name | downcase | pascal_case}} { fn get_headers( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsSyncRouterData, _connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn build_request( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: {{project-name | downcase}}:: {{project-name | downcase | pascal_case}}PaymentsResponse = res .response .parse_struct("{{project-name | downcase}} PaymentsSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent> ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration< Capture, PaymentsCaptureData, PaymentsResponseData, > for {{project-name | downcase | pascal_case}} { fn get_headers( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn get_request_body( &self, _req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into()) } fn build_request( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsCaptureType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsCaptureType::get_request_body(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &PaymentsCaptureRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { let response: {{project-name | downcase }}::{{project-name | downcase | pascal_case}}PaymentsResponse = res .response .parse_struct("{{project-name | downcase | pascal_case}} PaymentsCaptureResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent> ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration< Void, PaymentsCancelData, PaymentsResponseData, > for {{project-name | downcase | pascal_case}} {} impl ConnectorIntegration< Execute, RefundsData, RefundsResponseData, > for {{project-name | downcase | pascal_case}} { fn get_headers(&self, req: &RefundsRouterData<Execute>, connectors: &Connectors,) -> CustomResult<Vec<(String,masking::Maskable<String>)>,errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &RefundsRouterData<Execute>, _connectors: &Connectors,) -> CustomResult<String,errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn get_request_body(&self, req: &RefundsRouterData<Execute>, _connectors: &Connectors,) -> CustomResult<RequestContent, errors::ConnectorError> { let refund_amount = utils::convert_amount( self.amount_converter, req.request.minor_refund_amount, req.request.currency, )?; let connector_router_data = {{project-name | downcase}}::{{project-name | downcase | pascal_case}}RouterData::from(( refund_amount, req, )); let connector_req = {{project-name | downcase}}::{{project-name | downcase | pascal_case}}RefundRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request(&self, req: &RefundsRouterData<Execute>, connectors: &Connectors,) -> CustomResult<Option<Request>,errors::ConnectorError> { let request = RequestBuilder::new() .method(Method::Post) .url(&types::RefundExecuteType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundExecuteType::get_headers(self, req, connectors)?) .set_body(types::RefundExecuteType::get_request_body(self, req, connectors)?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &RefundsRouterData<Execute>, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundsRouterData<Execute>,errors::ConnectorError> { let response: {{project-name| downcase}}::RefundResponse = res.response.parse_struct("{{project-name | downcase}} RefundResponse").change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response(&self, res: Response, event_builder: Option<&mut ConnectorEvent>) -> CustomResult<ErrorResponse,errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for {{project-name | downcase | pascal_case}} { fn get_headers(&self, req: &RefundSyncRouterData,connectors: &Connectors,) -> CustomResult<Vec<(String, masking::Maskable<String>)>,errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &RefundSyncRouterData,_connectors: &Connectors,) -> CustomResult<String,errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn build_request( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&types::RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundSyncType::get_headers(self, req, connectors)?) .set_body(types::RefundSyncType::get_request_body(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &RefundSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundSyncRouterData,errors::ConnectorError,> { let response: {{project-name | downcase}}::RefundResponse = res.response.parse_struct("{{project-name | downcase}} RefundSyncResponse").change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response(&self, res: Response, event_builder: Option<&mut ConnectorEvent>) -> CustomResult<ErrorResponse,errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[async_trait::async_trait] impl webhooks::IncomingWebhook for {{project-name | downcase | pascal_case}} { fn get_webhook_object_reference_id( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_event_type( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_resource_object( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } } static {{project-name | upcase}}_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(SupportedPaymentMethods::new); static {{project-name | upcase}}_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "{{project-name | downcase | pascal_case}}", description: "{{project-name | downcase | pascal_case}} connector", connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, }; static {{project-name | upcase}}_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; impl ConnectorSpecifications for {{project-name | downcase | pascal_case}} { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&{{project-name | upcase}}_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { Some(&*{{project-name | upcase}}_SUPPORTED_PAYMENT_METHODS) } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { Some(&{{project-name | upcase}}_SUPPORTED_WEBHOOK_FLOWS) } }
connector-template/mod.rs
connector-template::mod
5,160
true