repo stringclasses 4 values | file_path stringlengths 6 193 | extension stringclasses 23 values | content stringlengths 0 1.73M | token_count int64 0 724k | __index_level_0__ int64 0 10.8k |
|---|---|---|---|---|---|
hyperswitch | crates/router/src/middleware.rs | .rs | use common_utils::consts::TENANT_HEADER;
use futures::StreamExt;
use router_env::{
logger,
tracing::{field::Empty, Instrument},
};
use crate::headers;
/// Middleware to include request ID in response header.
pub struct RequestId;
impl<S, B> actix_web::dev::Transform<S, actix_web::dev::ServiceRequest> for RequestId
where
S: actix_web::dev::Service<
actix_web::dev::ServiceRequest,
Response = actix_web::dev::ServiceResponse<B>,
Error = actix_web::Error,
>,
S::Future: 'static,
B: 'static,
{
type Response = actix_web::dev::ServiceResponse<B>;
type Error = actix_web::Error;
type Transform = RequestIdMiddleware<S>;
type InitError = ();
type Future = std::future::Ready<Result<Self::Transform, Self::InitError>>;
fn new_transform(&self, service: S) -> Self::Future {
std::future::ready(Ok(RequestIdMiddleware { service }))
}
}
pub struct RequestIdMiddleware<S> {
service: S,
}
impl<S, B> actix_web::dev::Service<actix_web::dev::ServiceRequest> for RequestIdMiddleware<S>
where
S: actix_web::dev::Service<
actix_web::dev::ServiceRequest,
Response = actix_web::dev::ServiceResponse<B>,
Error = actix_web::Error,
>,
S::Future: 'static,
B: 'static,
{
type Response = actix_web::dev::ServiceResponse<B>;
type Error = actix_web::Error;
type Future = futures::future::LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
actix_web::dev::forward_ready!(service);
fn call(&self, req: actix_web::dev::ServiceRequest) -> Self::Future {
let old_x_request_id = req.headers().get("x-request-id").cloned();
let mut req = req;
let request_id_fut = req.extract::<router_env::tracing_actix_web::RequestId>();
let response_fut = self.service.call(req);
Box::pin(
async move {
let request_id = request_id_fut.await?;
let request_id = request_id.as_hyphenated().to_string();
if let Some(upstream_request_id) = old_x_request_id {
router_env::logger::info!(?upstream_request_id);
}
let mut response = response_fut.await?;
response.headers_mut().append(
http::header::HeaderName::from_static("x-request-id"),
http::HeaderValue::from_str(&request_id)?,
);
Ok(response)
}
.in_current_span(),
)
}
}
/// Middleware for attaching default response headers. Headers with the same key already set in a
/// response will not be overwritten.
pub fn default_response_headers() -> actix_web::middleware::DefaultHeaders {
use actix_web::http::header;
let default_headers_middleware = actix_web::middleware::DefaultHeaders::new();
#[cfg(feature = "vergen")]
let default_headers_middleware =
default_headers_middleware.add(("x-hyperswitch-version", router_env::git_tag!()));
default_headers_middleware
// Max age of 1 year in seconds, equal to `60 * 60 * 24 * 365` seconds.
.add((header::STRICT_TRANSPORT_SECURITY, "max-age=31536000"))
.add((header::VIA, "HyperSwitch"))
}
/// Middleware to build a TOP level domain span for each request.
pub struct LogSpanInitializer;
impl<S, B> actix_web::dev::Transform<S, actix_web::dev::ServiceRequest> for LogSpanInitializer
where
S: actix_web::dev::Service<
actix_web::dev::ServiceRequest,
Response = actix_web::dev::ServiceResponse<B>,
Error = actix_web::Error,
>,
S::Future: 'static,
B: 'static,
{
type Response = actix_web::dev::ServiceResponse<B>;
type Error = actix_web::Error;
type Transform = LogSpanInitializerMiddleware<S>;
type InitError = ();
type Future = std::future::Ready<Result<Self::Transform, Self::InitError>>;
fn new_transform(&self, service: S) -> Self::Future {
std::future::ready(Ok(LogSpanInitializerMiddleware { service }))
}
}
pub struct LogSpanInitializerMiddleware<S> {
service: S,
}
impl<S, B> actix_web::dev::Service<actix_web::dev::ServiceRequest>
for LogSpanInitializerMiddleware<S>
where
S: actix_web::dev::Service<
actix_web::dev::ServiceRequest,
Response = actix_web::dev::ServiceResponse<B>,
Error = actix_web::Error,
>,
S::Future: 'static,
B: 'static,
{
type Response = actix_web::dev::ServiceResponse<B>;
type Error = actix_web::Error;
type Future = futures::future::LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
actix_web::dev::forward_ready!(service);
// TODO: have a common source of truth for the list of top level fields
// /crates/router_env/src/logger/storage.rs also has a list of fields called PERSISTENT_KEYS
fn call(&self, req: actix_web::dev::ServiceRequest) -> Self::Future {
let tenant_id = req
.headers()
.get(TENANT_HEADER)
.and_then(|i| i.to_str().ok())
.map(|s| s.to_owned());
let response_fut = self.service.call(req);
let tenant_id_clone = tenant_id.clone();
Box::pin(
async move {
if let Some(tenant) = tenant_id_clone {
router_env::tracing::Span::current().record("tenant_id", tenant);
}
let response = response_fut.await;
router_env::tracing::Span::current().record("golden_log_line", true);
response
}
.instrument(
router_env::tracing::info_span!(
"ROOT_SPAN",
payment_id = Empty,
merchant_id = Empty,
connector_name = Empty,
payment_method = Empty,
status_code = Empty,
flow = "UNKNOWN",
golden_log_line = Empty,
tenant_id = &tenant_id
)
.or_current(),
),
)
}
}
fn get_request_details_from_value(json_value: &serde_json::Value, parent_key: &str) -> String {
match json_value {
serde_json::Value::Null => format!("{}: null", parent_key),
serde_json::Value::Bool(b) => format!("{}: {}", parent_key, b),
serde_json::Value::Number(num) => format!("{}: {}", parent_key, num.to_string().len()),
serde_json::Value::String(s) => format!("{}: {}", parent_key, s.len()),
serde_json::Value::Array(arr) => {
let mut result = String::new();
for (index, value) in arr.iter().enumerate() {
let child_key = format!("{}[{}]", parent_key, index);
result.push_str(&get_request_details_from_value(value, &child_key));
if index < arr.len() - 1 {
result.push_str(", ");
}
}
result
}
serde_json::Value::Object(obj) => {
let mut result = String::new();
for (index, (key, value)) in obj.iter().enumerate() {
let child_key = format!("{}[{}]", parent_key, key);
result.push_str(&get_request_details_from_value(value, &child_key));
if index < obj.len() - 1 {
result.push_str(", ");
}
}
result
}
}
}
/// Middleware for Logging request_details of HTTP 400 Bad Requests
pub struct Http400RequestDetailsLogger;
impl<S: 'static, B> actix_web::dev::Transform<S, actix_web::dev::ServiceRequest>
for Http400RequestDetailsLogger
where
S: actix_web::dev::Service<
actix_web::dev::ServiceRequest,
Response = actix_web::dev::ServiceResponse<B>,
Error = actix_web::Error,
>,
S::Future: 'static,
B: 'static,
{
type Response = actix_web::dev::ServiceResponse<B>;
type Error = actix_web::Error;
type Transform = Http400RequestDetailsLoggerMiddleware<S>;
type InitError = ();
type Future = std::future::Ready<Result<Self::Transform, Self::InitError>>;
fn new_transform(&self, service: S) -> Self::Future {
std::future::ready(Ok(Http400RequestDetailsLoggerMiddleware {
service: std::rc::Rc::new(service),
}))
}
}
pub struct Http400RequestDetailsLoggerMiddleware<S> {
service: std::rc::Rc<S>,
}
impl<S, B> actix_web::dev::Service<actix_web::dev::ServiceRequest>
for Http400RequestDetailsLoggerMiddleware<S>
where
S: actix_web::dev::Service<
actix_web::dev::ServiceRequest,
Response = actix_web::dev::ServiceResponse<B>,
Error = actix_web::Error,
> + 'static,
S::Future: 'static,
B: 'static,
{
type Response = actix_web::dev::ServiceResponse<B>;
type Error = actix_web::Error;
type Future = futures::future::LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
actix_web::dev::forward_ready!(service);
fn call(&self, mut req: actix_web::dev::ServiceRequest) -> Self::Future {
let svc = self.service.clone();
let request_id_fut = req.extract::<router_env::tracing_actix_web::RequestId>();
Box::pin(async move {
let (http_req, payload) = req.into_parts();
let result_payload: Vec<Result<bytes::Bytes, actix_web::error::PayloadError>> =
payload.collect().await;
let payload = result_payload
.into_iter()
.collect::<Result<Vec<bytes::Bytes>, actix_web::error::PayloadError>>()?;
let bytes = payload.clone().concat().to_vec();
let bytes_length = bytes.len();
// we are creating h1 payload manually from bytes, currently there's no way to create http2 payload with actix
let (_, mut new_payload) = actix_http::h1::Payload::create(true);
new_payload.unread_data(bytes.to_vec().clone().into());
let new_req = actix_web::dev::ServiceRequest::from_parts(http_req, new_payload.into());
let content_length_header = new_req
.headers()
.get(headers::CONTENT_LENGTH)
.map(ToOwned::to_owned);
let response_fut = svc.call(new_req);
let response = response_fut.await?;
// Log the request_details when we receive 400 status from the application
if response.status() == 400 {
let request_id = request_id_fut.await?.as_hyphenated().to_string();
let content_length_header_string = content_length_header
.map(|content_length_header| {
content_length_header.to_str().map(ToOwned::to_owned)
})
.transpose()
.inspect_err(|error| {
logger::warn!("Could not convert content length to string {error:?}");
})
.ok()
.flatten();
logger::info!("Content length from header: {content_length_header_string:?}, Bytes length: {bytes_length}");
if !bytes.is_empty() {
let value_result: Result<serde_json::Value, serde_json::Error> =
serde_json::from_slice(&bytes);
match value_result {
Ok(value) => {
logger::info!(
"request_id: {request_id}, request_details: {}",
get_request_details_from_value(&value, "")
);
}
Err(err) => {
logger::warn!("error while parsing the request in json value: {err}");
}
}
} else {
logger::info!("request_id: {request_id}, request_details: Empty Body");
}
}
Ok(response)
})
}
}
/// Middleware for Adding Accept-Language header based on query params
pub struct AddAcceptLanguageHeader;
impl<S: 'static, B> actix_web::dev::Transform<S, actix_web::dev::ServiceRequest>
for AddAcceptLanguageHeader
where
S: actix_web::dev::Service<
actix_web::dev::ServiceRequest,
Response = actix_web::dev::ServiceResponse<B>,
Error = actix_web::Error,
>,
S::Future: 'static,
B: 'static,
{
type Response = actix_web::dev::ServiceResponse<B>;
type Error = actix_web::Error;
type Transform = AddAcceptLanguageHeaderMiddleware<S>;
type InitError = ();
type Future = std::future::Ready<Result<Self::Transform, Self::InitError>>;
fn new_transform(&self, service: S) -> Self::Future {
std::future::ready(Ok(AddAcceptLanguageHeaderMiddleware {
service: std::rc::Rc::new(service),
}))
}
}
pub struct AddAcceptLanguageHeaderMiddleware<S> {
service: std::rc::Rc<S>,
}
impl<S, B> actix_web::dev::Service<actix_web::dev::ServiceRequest>
for AddAcceptLanguageHeaderMiddleware<S>
where
S: actix_web::dev::Service<
actix_web::dev::ServiceRequest,
Response = actix_web::dev::ServiceResponse<B>,
Error = actix_web::Error,
> + 'static,
S::Future: 'static,
B: 'static,
{
type Response = actix_web::dev::ServiceResponse<B>;
type Error = actix_web::Error;
type Future = futures::future::LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
actix_web::dev::forward_ready!(service);
fn call(&self, mut req: actix_web::dev::ServiceRequest) -> Self::Future {
let svc = self.service.clone();
Box::pin(async move {
#[derive(serde::Deserialize)]
struct LocaleQueryParam {
locale: Option<String>,
}
let query_params = req.query_string();
let locale_param =
serde_qs::from_str::<LocaleQueryParam>(query_params).map_err(|error| {
actix_web::error::ErrorBadRequest(format!(
"Could not convert query params to locale query parmas: {:?}",
error
))
})?;
let accept_language_header = req.headers().get(http::header::ACCEPT_LANGUAGE);
if let Some(locale) = locale_param.locale {
req.headers_mut().insert(
http::header::ACCEPT_LANGUAGE,
http::HeaderValue::from_str(&locale)?,
);
} else if accept_language_header.is_none() {
req.headers_mut().insert(
http::header::ACCEPT_LANGUAGE,
http::HeaderValue::from_static("en"),
);
}
let response_fut = svc.call(req);
let response = response_fut.await?;
Ok(response)
})
}
}
| 3,408 | 1,205 |
hyperswitch | crates/router/src/connection.rs | .rs | use bb8::PooledConnection;
use diesel::PgConnection;
use error_stack::ResultExt;
use storage_impl::errors as storage_errors;
use crate::errors;
pub type PgPool = bb8::Pool<async_bb8_diesel::ConnectionManager<PgConnection>>;
pub type PgPooledConn = async_bb8_diesel::Connection<PgConnection>;
/// Creates a Redis connection pool for the specified Redis settings
/// # Panics
///
/// Panics if failed to create a redis pool
#[allow(clippy::expect_used)]
pub async fn redis_connection(
conf: &crate::configs::Settings,
) -> redis_interface::RedisConnectionPool {
redis_interface::RedisConnectionPool::new(&conf.redis)
.await
.expect("Failed to create Redis Connection Pool")
}
pub async fn pg_connection_read<T: storage_impl::DatabaseStore>(
store: &T,
) -> errors::CustomResult<
PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>,
storage_errors::StorageError,
> {
// If only OLAP is enabled get replica pool.
#[cfg(all(feature = "olap", not(feature = "oltp")))]
let pool = store.get_replica_pool();
// If either one of these are true we need to get master pool.
// 1. Only OLTP is enabled.
// 2. Both OLAP and OLTP is enabled.
// 3. Both OLAP and OLTP is disabled.
#[cfg(any(
all(not(feature = "olap"), feature = "oltp"),
all(feature = "olap", feature = "oltp"),
all(not(feature = "olap"), not(feature = "oltp"))
))]
let pool = store.get_master_pool();
pool.get()
.await
.change_context(storage_errors::StorageError::DatabaseConnectionError)
}
pub async fn pg_accounts_connection_read<T: storage_impl::DatabaseStore>(
store: &T,
) -> errors::CustomResult<
PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>,
storage_errors::StorageError,
> {
// If only OLAP is enabled get replica pool.
#[cfg(all(feature = "olap", not(feature = "oltp")))]
let pool = store.get_accounts_replica_pool();
// If either one of these are true we need to get master pool.
// 1. Only OLTP is enabled.
// 2. Both OLAP and OLTP is enabled.
// 3. Both OLAP and OLTP is disabled.
#[cfg(any(
all(not(feature = "olap"), feature = "oltp"),
all(feature = "olap", feature = "oltp"),
all(not(feature = "olap"), not(feature = "oltp"))
))]
let pool = store.get_accounts_master_pool();
pool.get()
.await
.change_context(storage_errors::StorageError::DatabaseConnectionError)
}
pub async fn pg_connection_write<T: storage_impl::DatabaseStore>(
store: &T,
) -> errors::CustomResult<
PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>,
storage_errors::StorageError,
> {
// Since all writes should happen to master DB only choose master DB.
let pool = store.get_master_pool();
pool.get()
.await
.change_context(storage_errors::StorageError::DatabaseConnectionError)
}
pub async fn pg_accounts_connection_write<T: storage_impl::DatabaseStore>(
store: &T,
) -> errors::CustomResult<
PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>,
storage_errors::StorageError,
> {
// Since all writes should happen to master DB only choose master DB.
let pool = store.get_accounts_master_pool();
pool.get()
.await
.change_context(storage_errors::StorageError::DatabaseConnectionError)
}
| 848 | 1,206 |
hyperswitch | crates/router/src/utils.rs | .rs | #[cfg(feature = "olap")]
pub mod connector_onboarding;
pub mod currency;
pub mod db_utils;
pub mod ext_traits;
#[cfg(feature = "kv_store")]
pub mod storage_partitioning;
#[cfg(feature = "olap")]
pub mod user;
#[cfg(feature = "olap")]
pub mod user_role;
#[cfg(feature = "olap")]
pub mod verify_connector;
use std::fmt::Debug;
use api_models::{
enums,
payments::{self},
webhooks,
};
use common_utils::types::keymanager::KeyManagerState;
pub use common_utils::{
crypto::{self, Encryptable},
ext_traits::{ByteSliceExt, BytesExt, Encode, StringExt, ValueExt},
fp_utils::when,
id_type, pii,
validation::validate_email,
};
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
use common_utils::{
type_name,
types::keymanager::{Identifier, ToEncryptable},
};
use error_stack::ResultExt;
pub use hyperswitch_connectors::utils::QrImage;
use hyperswitch_domain_models::payments::PaymentIntent;
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
use hyperswitch_domain_models::type_encryption::{crypto_operation, CryptoOperation};
use masking::{ExposeInterface, SwitchStrategy};
use nanoid::nanoid;
use serde::de::DeserializeOwned;
use serde_json::Value;
use tracing_futures::Instrument;
use uuid::Uuid;
pub use self::ext_traits::{OptionExt, ValidateCall};
#[cfg(feature = "v1")]
use crate::core::webhooks as webhooks_core;
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
use crate::types::storage;
use crate::{
consts,
core::{
authentication::types::ExternalThreeDSConnectorMetadata,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
payments as payments_core,
},
headers::ACCEPT_LANGUAGE,
logger,
routes::{metrics, SessionState},
services::{self, authentication::get_header_value_by_key},
types::{
self, domain,
transformers::{ForeignFrom, ForeignInto},
},
};
pub mod error_parser {
use std::fmt::Display;
use actix_web::{
error::{Error, JsonPayloadError},
http::StatusCode,
HttpRequest, ResponseError,
};
#[derive(Debug)]
struct CustomJsonError {
err: JsonPayloadError,
}
// Display is a requirement defined by the actix crate for implementing ResponseError trait
impl Display for CustomJsonError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(
serde_json::to_string(&serde_json::json!({
"error": {
"error_type": "invalid_request",
"message": self.err.to_string(),
"code": "IR_06",
}
}))
.as_deref()
.unwrap_or("Invalid Json Error"),
)
}
}
impl ResponseError for CustomJsonError {
fn status_code(&self) -> StatusCode {
StatusCode::BAD_REQUEST
}
fn error_response(&self) -> actix_web::HttpResponse<actix_web::body::BoxBody> {
use actix_web::http::header;
actix_web::HttpResponseBuilder::new(self.status_code())
.insert_header((header::CONTENT_TYPE, mime::APPLICATION_JSON))
.body(self.to_string())
}
}
pub fn custom_json_error_handler(err: JsonPayloadError, _req: &HttpRequest) -> Error {
Error::from(CustomJsonError { err })
}
}
#[inline]
pub fn generate_id(length: usize, prefix: &str) -> String {
format!("{}_{}", prefix, nanoid!(length, &consts::ALPHABETS))
}
#[inline]
pub fn generate_uuid() -> String {
Uuid::new_v4().to_string()
}
pub trait ConnectorResponseExt: Sized {
fn get_response(self) -> RouterResult<types::Response>;
fn get_error_response(self) -> RouterResult<types::Response>;
fn get_response_inner<T: DeserializeOwned>(self, type_name: &'static str) -> RouterResult<T> {
self.get_response()?
.response
.parse_struct(type_name)
.change_context(errors::ApiErrorResponse::InternalServerError)
}
}
impl<E> ConnectorResponseExt
for Result<Result<types::Response, types::Response>, error_stack::Report<E>>
{
fn get_error_response(self) -> RouterResult<types::Response> {
self.map_err(|error| error.change_context(errors::ApiErrorResponse::InternalServerError))
.attach_printable("Error while receiving response")
.and_then(|inner| match inner {
Ok(res) => {
logger::error!(response=?res);
Err(errors::ApiErrorResponse::InternalServerError).attach_printable(format!(
"Expecting error response, received response: {res:?}"
))
}
Err(err_res) => Ok(err_res),
})
}
fn get_response(self) -> RouterResult<types::Response> {
self.map_err(|error| error.change_context(errors::ApiErrorResponse::InternalServerError))
.attach_printable("Error while receiving response")
.and_then(|inner| match inner {
Err(err_res) => {
logger::error!(error_response=?err_res);
Err(errors::ApiErrorResponse::InternalServerError).attach_printable(format!(
"Expecting response, received error response: {err_res:?}"
))
}
Ok(res) => Ok(res),
})
}
}
#[inline]
pub fn get_payout_attempt_id(payout_id: impl std::fmt::Display, attempt_count: i16) -> String {
format!("{payout_id}_{attempt_count}")
}
#[cfg(feature = "v1")]
pub async fn find_payment_intent_from_payment_id_type(
state: &SessionState,
payment_id_type: payments::PaymentIdType,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<PaymentIntent, errors::ApiErrorResponse> {
let key_manager_state: KeyManagerState = state.into();
let db = &*state.store;
match payment_id_type {
payments::PaymentIdType::PaymentIntentId(payment_id) => db
.find_payment_intent_by_payment_id_merchant_id(
&key_manager_state,
&payment_id,
merchant_account.get_id(),
key_store,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound),
payments::PaymentIdType::ConnectorTransactionId(connector_transaction_id) => {
let attempt = db
.find_payment_attempt_by_merchant_id_connector_txn_id(
merchant_account.get_id(),
&connector_transaction_id,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
db.find_payment_intent_by_payment_id_merchant_id(
&key_manager_state,
&attempt.payment_id,
merchant_account.get_id(),
key_store,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
}
payments::PaymentIdType::PaymentAttemptId(attempt_id) => {
let attempt = db
.find_payment_attempt_by_attempt_id_merchant_id(
&attempt_id,
merchant_account.get_id(),
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
db.find_payment_intent_by_payment_id_merchant_id(
&key_manager_state,
&attempt.payment_id,
merchant_account.get_id(),
key_store,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
}
payments::PaymentIdType::PreprocessingId(_) => {
Err(errors::ApiErrorResponse::PaymentNotFound)?
}
}
}
#[cfg(feature = "v1")]
pub async fn find_payment_intent_from_refund_id_type(
state: &SessionState,
refund_id_type: webhooks::RefundIdType,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
connector_name: &str,
) -> CustomResult<PaymentIntent, errors::ApiErrorResponse> {
let db = &*state.store;
let refund = match refund_id_type {
webhooks::RefundIdType::RefundId(id) => db
.find_refund_by_merchant_id_refund_id(
merchant_account.get_id(),
&id,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?,
webhooks::RefundIdType::ConnectorRefundId(id) => db
.find_refund_by_merchant_id_connector_refund_id_connector(
merchant_account.get_id(),
&id,
connector_name,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?,
};
let attempt = db
.find_payment_attempt_by_attempt_id_merchant_id(
&refund.attempt_id,
merchant_account.get_id(),
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
db.find_payment_intent_by_payment_id_merchant_id(
&state.into(),
&attempt.payment_id,
merchant_account.get_id(),
key_store,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
}
#[cfg(feature = "v1")]
pub async fn find_payment_intent_from_mandate_id_type(
state: &SessionState,
mandate_id_type: webhooks::MandateIdType,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<PaymentIntent, errors::ApiErrorResponse> {
let db = &*state.store;
let mandate = match mandate_id_type {
webhooks::MandateIdType::MandateId(mandate_id) => db
.find_mandate_by_merchant_id_mandate_id(
merchant_account.get_id(),
mandate_id.as_str(),
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?,
webhooks::MandateIdType::ConnectorMandateId(connector_mandate_id) => db
.find_mandate_by_merchant_id_connector_mandate_id(
merchant_account.get_id(),
connector_mandate_id.as_str(),
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?,
};
db.find_payment_intent_by_payment_id_merchant_id(
&state.into(),
&mandate
.original_payment_id
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("original_payment_id not present in mandate record")?,
merchant_account.get_id(),
key_store,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
}
#[cfg(feature = "v1")]
pub async fn find_mca_from_authentication_id_type(
state: &SessionState,
authentication_id_type: webhooks::AuthenticationIdType,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> {
let db = &*state.store;
let authentication = match authentication_id_type {
webhooks::AuthenticationIdType::AuthenticationId(authentication_id) => db
.find_authentication_by_merchant_id_authentication_id(
merchant_account.get_id(),
authentication_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?,
webhooks::AuthenticationIdType::ConnectorAuthenticationId(connector_authentication_id) => {
db.find_authentication_by_merchant_id_connector_authentication_id(
merchant_account.get_id().clone(),
connector_authentication_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?
}
};
#[cfg(feature = "v1")]
{
db.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
&state.into(),
merchant_account.get_id(),
&authentication.merchant_connector_id,
key_store,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: authentication
.merchant_connector_id
.get_string_repr()
.to_string(),
},
)
}
#[cfg(feature = "v2")]
//get mca using id
{
let _ = key_store;
let _ = authentication;
todo!()
}
}
#[cfg(feature = "v1")]
pub async fn get_mca_from_payment_intent(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
payment_intent: PaymentIntent,
key_store: &domain::MerchantKeyStore,
connector_name: &str,
) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> {
let db = &*state.store;
let key_manager_state: &KeyManagerState = &state.into();
#[cfg(feature = "v1")]
let payment_attempt = db
.find_payment_attempt_by_attempt_id_merchant_id(
&payment_intent.active_attempt.get_id(),
merchant_account.get_id(),
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
#[cfg(feature = "v2")]
let payment_attempt = db
.find_payment_attempt_by_attempt_id_merchant_id(
key_manager_state,
key_store,
&payment_intent.active_attempt.get_id(),
merchant_account.get_id(),
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
match payment_attempt.merchant_connector_id {
Some(merchant_connector_id) => {
#[cfg(feature = "v1")]
{
db.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
merchant_account.get_id(),
&merchant_connector_id,
key_store,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_connector_id.get_string_repr().to_string(),
},
)
}
#[cfg(feature = "v2")]
{
//get mca using id
let _id = merchant_connector_id;
let _ = key_store;
let _ = key_manager_state;
let _ = connector_name;
todo!()
}
}
None => {
let profile_id = payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("profile_id is not set in payment_intent")?
.clone();
#[cfg(feature = "v1")]
{
db.find_merchant_connector_account_by_profile_id_connector_name(
key_manager_state,
&profile_id,
connector_name,
key_store,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: format!(
"profile_id {} and connector_name {connector_name}",
profile_id.get_string_repr()
),
},
)
}
#[cfg(feature = "v2")]
{
//get mca using id
let _ = profile_id;
todo!()
}
}
}
}
#[cfg(feature = "payouts")]
pub async fn get_mca_from_payout_attempt(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
payout_id_type: webhooks::PayoutIdType,
connector_name: &str,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> {
let db = &*state.store;
let payout = match payout_id_type {
webhooks::PayoutIdType::PayoutAttemptId(payout_attempt_id) => db
.find_payout_attempt_by_merchant_id_payout_attempt_id(
merchant_account.get_id(),
&payout_attempt_id,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?,
webhooks::PayoutIdType::ConnectorPayoutId(connector_payout_id) => db
.find_payout_attempt_by_merchant_id_connector_payout_id(
merchant_account.get_id(),
&connector_payout_id,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?,
};
let key_manager_state: &KeyManagerState = &state.into();
match payout.merchant_connector_id {
Some(merchant_connector_id) => {
#[cfg(feature = "v1")]
{
db.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
merchant_account.get_id(),
&merchant_connector_id,
key_store,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_connector_id.get_string_repr().to_string(),
},
)
}
#[cfg(feature = "v2")]
{
//get mca using id
let _id = merchant_connector_id;
let _ = key_store;
let _ = connector_name;
let _ = key_manager_state;
todo!()
}
}
None => {
#[cfg(feature = "v1")]
{
db.find_merchant_connector_account_by_profile_id_connector_name(
key_manager_state,
&payout.profile_id,
connector_name,
key_store,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: format!(
"profile_id {} and connector_name {}",
payout.profile_id.get_string_repr(),
connector_name
),
},
)
}
#[cfg(feature = "v2")]
{
todo!()
}
}
}
}
#[cfg(feature = "v1")]
pub async fn get_mca_from_object_reference_id(
state: &SessionState,
object_reference_id: webhooks::ObjectReferenceId,
merchant_account: &domain::MerchantAccount,
connector_name: &str,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> {
let db = &*state.store;
#[cfg(feature = "v1")]
let default_profile_id = merchant_account.default_profile.as_ref();
#[cfg(feature = "v2")]
let default_profile_id = Option::<&String>::None;
match default_profile_id {
Some(profile_id) => {
#[cfg(feature = "v1")]
{
db.find_merchant_connector_account_by_profile_id_connector_name(
&state.into(),
profile_id,
connector_name,
key_store,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: format!(
"profile_id {} and connector_name {connector_name}",
profile_id.get_string_repr()
),
},
)
}
#[cfg(feature = "v2")]
{
let _db = db;
let _profile_id = profile_id;
todo!()
}
}
_ => match object_reference_id {
webhooks::ObjectReferenceId::PaymentId(payment_id_type) => {
get_mca_from_payment_intent(
state,
merchant_account,
find_payment_intent_from_payment_id_type(
state,
payment_id_type,
merchant_account,
key_store,
)
.await?,
key_store,
connector_name,
)
.await
}
webhooks::ObjectReferenceId::RefundId(refund_id_type) => {
get_mca_from_payment_intent(
state,
merchant_account,
find_payment_intent_from_refund_id_type(
state,
refund_id_type,
merchant_account,
key_store,
connector_name,
)
.await?,
key_store,
connector_name,
)
.await
}
webhooks::ObjectReferenceId::MandateId(mandate_id_type) => {
get_mca_from_payment_intent(
state,
merchant_account,
find_payment_intent_from_mandate_id_type(
state,
mandate_id_type,
merchant_account,
key_store,
)
.await?,
key_store,
connector_name,
)
.await
}
webhooks::ObjectReferenceId::ExternalAuthenticationID(authentication_id_type) => {
find_mca_from_authentication_id_type(
state,
authentication_id_type,
merchant_account,
key_store,
)
.await
}
#[cfg(feature = "payouts")]
webhooks::ObjectReferenceId::PayoutId(payout_id_type) => {
get_mca_from_payout_attempt(
state,
merchant_account,
payout_id_type,
connector_name,
key_store,
)
.await
}
},
}
}
// validate json format for the error
pub fn handle_json_response_deserialization_failure(
res: types::Response,
connector: &'static str,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
metrics::RESPONSE_DESERIALIZATION_FAILURE
.add(1, router_env::metric_attributes!(("connector", connector)));
let response_data = String::from_utf8(res.response.to_vec())
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
// check for whether the response is in json format
match serde_json::from_str::<Value>(&response_data) {
// in case of unexpected response but in json format
Ok(_) => Err(errors::ConnectorError::ResponseDeserializationFailed)?,
// in case of unexpected response but in html or string format
Err(error_msg) => {
logger::error!(deserialization_error=?error_msg);
logger::error!("UNEXPECTED RESPONSE FROM CONNECTOR: {}", response_data);
Ok(types::ErrorResponse {
status_code: res.status_code,
code: consts::NO_ERROR_CODE.to_string(),
message: consts::UNSUPPORTED_ERROR_MESSAGE.to_string(),
reason: Some(response_data),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
}
}
pub fn get_http_status_code_type(
status_code: u16,
) -> CustomResult<String, errors::ApiErrorResponse> {
let status_code_type = match status_code {
100..=199 => "1xx",
200..=299 => "2xx",
300..=399 => "3xx",
400..=499 => "4xx",
500..=599 => "5xx",
_ => Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid http status code")?,
};
Ok(status_code_type.to_string())
}
pub fn add_connector_http_status_code_metrics(option_status_code: Option<u16>) {
if let Some(status_code) = option_status_code {
let status_code_type = get_http_status_code_type(status_code).ok();
match status_code_type.as_deref() {
Some("1xx") => metrics::CONNECTOR_HTTP_STATUS_CODE_1XX_COUNT.add(1, &[]),
Some("2xx") => metrics::CONNECTOR_HTTP_STATUS_CODE_2XX_COUNT.add(1, &[]),
Some("3xx") => metrics::CONNECTOR_HTTP_STATUS_CODE_3XX_COUNT.add(1, &[]),
Some("4xx") => metrics::CONNECTOR_HTTP_STATUS_CODE_4XX_COUNT.add(1, &[]),
Some("5xx") => metrics::CONNECTOR_HTTP_STATUS_CODE_5XX_COUNT.add(1, &[]),
_ => logger::info!("Skip metrics as invalid http status code received from connector"),
};
} else {
logger::info!("Skip metrics as no http status code received from connector")
}
}
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
#[async_trait::async_trait]
pub trait CustomerAddress {
async fn get_address_update(
&self,
state: &SessionState,
address_details: payments::AddressDetails,
key: &[u8],
storage_scheme: storage::enums::MerchantStorageScheme,
merchant_id: id_type::MerchantId,
) -> CustomResult<storage::AddressUpdate, common_utils::errors::CryptoError>;
async fn get_domain_address(
&self,
state: &SessionState,
address_details: payments::AddressDetails,
merchant_id: &id_type::MerchantId,
customer_id: &id_type::CustomerId,
key: &[u8],
storage_scheme: storage::enums::MerchantStorageScheme,
) -> CustomResult<domain::CustomerAddress, common_utils::errors::CryptoError>;
}
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
#[async_trait::async_trait]
impl CustomerAddress for api_models::customers::CustomerRequest {
async fn get_address_update(
&self,
state: &SessionState,
address_details: payments::AddressDetails,
key: &[u8],
storage_scheme: storage::enums::MerchantStorageScheme,
merchant_id: id_type::MerchantId,
) -> CustomResult<storage::AddressUpdate, common_utils::errors::CryptoError> {
let encrypted_data = crypto_operation(
&state.into(),
type_name!(storage::Address),
CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableAddress::to_encryptable(
domain::FromRequestEncryptableAddress {
line1: address_details.line1.clone(),
line2: address_details.line2.clone(),
line3: address_details.line3.clone(),
state: address_details.state.clone(),
first_name: address_details.first_name.clone(),
last_name: address_details.last_name.clone(),
zip: address_details.zip.clone(),
phone_number: self.phone.clone(),
email: self
.email
.as_ref()
.map(|a| a.clone().expose().switch_strategy()),
},
)),
Identifier::Merchant(merchant_id.to_owned()),
key,
)
.await
.and_then(|val| val.try_into_batchoperation())?;
let encryptable_address =
domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data)
.change_context(common_utils::errors::CryptoError::EncodingFailed)?;
Ok(storage::AddressUpdate::Update {
city: address_details.city,
country: address_details.country,
line1: encryptable_address.line1,
line2: encryptable_address.line2,
line3: encryptable_address.line3,
zip: encryptable_address.zip,
state: encryptable_address.state,
first_name: encryptable_address.first_name,
last_name: encryptable_address.last_name,
phone_number: encryptable_address.phone_number,
country_code: self.phone_country_code.clone(),
updated_by: storage_scheme.to_string(),
email: encryptable_address.email.map(|email| {
let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> =
Encryptable::new(
email.clone().into_inner().switch_strategy(),
email.into_encrypted(),
);
encryptable
}),
})
}
async fn get_domain_address(
&self,
state: &SessionState,
address_details: payments::AddressDetails,
merchant_id: &id_type::MerchantId,
customer_id: &id_type::CustomerId,
key: &[u8],
storage_scheme: storage::enums::MerchantStorageScheme,
) -> CustomResult<domain::CustomerAddress, common_utils::errors::CryptoError> {
let encrypted_data = crypto_operation(
&state.into(),
type_name!(storage::Address),
CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableAddress::to_encryptable(
domain::FromRequestEncryptableAddress {
line1: address_details.line1.clone(),
line2: address_details.line2.clone(),
line3: address_details.line3.clone(),
state: address_details.state.clone(),
first_name: address_details.first_name.clone(),
last_name: address_details.last_name.clone(),
zip: address_details.zip.clone(),
phone_number: self.phone.clone(),
email: self
.email
.as_ref()
.map(|a| a.clone().expose().switch_strategy()),
},
)),
Identifier::Merchant(merchant_id.to_owned()),
key,
)
.await
.and_then(|val| val.try_into_batchoperation())?;
let encryptable_address =
domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data)
.change_context(common_utils::errors::CryptoError::EncodingFailed)?;
let address = domain::Address {
city: address_details.city,
country: address_details.country,
line1: encryptable_address.line1,
line2: encryptable_address.line2,
line3: encryptable_address.line3,
zip: encryptable_address.zip,
state: encryptable_address.state,
first_name: encryptable_address.first_name,
last_name: encryptable_address.last_name,
phone_number: encryptable_address.phone_number,
country_code: self.phone_country_code.clone(),
merchant_id: merchant_id.to_owned(),
address_id: generate_id(consts::ID_LENGTH, "add"),
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
updated_by: storage_scheme.to_string(),
email: encryptable_address.email.map(|email| {
let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> =
Encryptable::new(
email.clone().into_inner().switch_strategy(),
email.into_encrypted(),
);
encryptable
}),
};
Ok(domain::CustomerAddress {
address,
customer_id: customer_id.to_owned(),
})
}
}
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
#[async_trait::async_trait]
impl CustomerAddress for api_models::customers::CustomerUpdateRequest {
async fn get_address_update(
&self,
state: &SessionState,
address_details: payments::AddressDetails,
key: &[u8],
storage_scheme: storage::enums::MerchantStorageScheme,
merchant_id: id_type::MerchantId,
) -> CustomResult<storage::AddressUpdate, common_utils::errors::CryptoError> {
let encrypted_data = crypto_operation(
&state.into(),
type_name!(storage::Address),
CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableAddress::to_encryptable(
domain::FromRequestEncryptableAddress {
line1: address_details.line1.clone(),
line2: address_details.line2.clone(),
line3: address_details.line3.clone(),
state: address_details.state.clone(),
first_name: address_details.first_name.clone(),
last_name: address_details.last_name.clone(),
zip: address_details.zip.clone(),
phone_number: self.phone.clone(),
email: self
.email
.as_ref()
.map(|a| a.clone().expose().switch_strategy()),
},
)),
Identifier::Merchant(merchant_id.to_owned()),
key,
)
.await
.and_then(|val| val.try_into_batchoperation())?;
let encryptable_address =
domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data)
.change_context(common_utils::errors::CryptoError::EncodingFailed)?;
Ok(storage::AddressUpdate::Update {
city: address_details.city,
country: address_details.country,
line1: encryptable_address.line1,
line2: encryptable_address.line2,
line3: encryptable_address.line3,
zip: encryptable_address.zip,
state: encryptable_address.state,
first_name: encryptable_address.first_name,
last_name: encryptable_address.last_name,
phone_number: encryptable_address.phone_number,
country_code: self.phone_country_code.clone(),
updated_by: storage_scheme.to_string(),
email: encryptable_address.email.map(|email| {
let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> =
Encryptable::new(
email.clone().into_inner().switch_strategy(),
email.into_encrypted(),
);
encryptable
}),
})
}
async fn get_domain_address(
&self,
state: &SessionState,
address_details: payments::AddressDetails,
merchant_id: &id_type::MerchantId,
customer_id: &id_type::CustomerId,
key: &[u8],
storage_scheme: storage::enums::MerchantStorageScheme,
) -> CustomResult<domain::CustomerAddress, common_utils::errors::CryptoError> {
let encrypted_data = crypto_operation(
&state.into(),
type_name!(storage::Address),
CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableAddress::to_encryptable(
domain::FromRequestEncryptableAddress {
line1: address_details.line1.clone(),
line2: address_details.line2.clone(),
line3: address_details.line3.clone(),
state: address_details.state.clone(),
first_name: address_details.first_name.clone(),
last_name: address_details.last_name.clone(),
zip: address_details.zip.clone(),
phone_number: self.phone.clone(),
email: self
.email
.as_ref()
.map(|a| a.clone().expose().switch_strategy()),
},
)),
Identifier::Merchant(merchant_id.to_owned()),
key,
)
.await
.and_then(|val| val.try_into_batchoperation())?;
let encryptable_address =
domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data)
.change_context(common_utils::errors::CryptoError::EncodingFailed)?;
let address = domain::Address {
city: address_details.city,
country: address_details.country,
line1: encryptable_address.line1,
line2: encryptable_address.line2,
line3: encryptable_address.line3,
zip: encryptable_address.zip,
state: encryptable_address.state,
first_name: encryptable_address.first_name,
last_name: encryptable_address.last_name,
phone_number: encryptable_address.phone_number,
country_code: self.phone_country_code.clone(),
merchant_id: merchant_id.to_owned(),
address_id: generate_id(consts::ID_LENGTH, "add"),
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
updated_by: storage_scheme.to_string(),
email: encryptable_address.email.map(|email| {
let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> =
Encryptable::new(
email.clone().into_inner().switch_strategy(),
email.into_encrypted(),
);
encryptable
}),
};
Ok(domain::CustomerAddress {
address,
customer_id: customer_id.to_owned(),
})
}
}
pub fn add_apple_pay_flow_metrics(
apple_pay_flow: &Option<domain::ApplePayFlow>,
connector: Option<String>,
merchant_id: id_type::MerchantId,
) {
if let Some(flow) = apple_pay_flow {
match flow {
domain::ApplePayFlow::Simplified(_) => metrics::APPLE_PAY_SIMPLIFIED_FLOW.add(
1,
router_env::metric_attributes!(
(
"connector",
connector.to_owned().unwrap_or("null".to_string()),
),
("merchant_id", merchant_id.clone()),
),
),
domain::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW.add(
1,
router_env::metric_attributes!(
(
"connector",
connector.to_owned().unwrap_or("null".to_string()),
),
("merchant_id", merchant_id.clone()),
),
),
}
}
}
pub fn add_apple_pay_payment_status_metrics(
payment_attempt_status: enums::AttemptStatus,
apple_pay_flow: Option<domain::ApplePayFlow>,
connector: Option<String>,
merchant_id: id_type::MerchantId,
) {
if payment_attempt_status == enums::AttemptStatus::Charged {
if let Some(flow) = apple_pay_flow {
match flow {
domain::ApplePayFlow::Simplified(_) => {
metrics::APPLE_PAY_SIMPLIFIED_FLOW_SUCCESSFUL_PAYMENT.add(
1,
router_env::metric_attributes!(
(
"connector",
connector.to_owned().unwrap_or("null".to_string()),
),
("merchant_id", merchant_id.clone()),
),
)
}
domain::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW_SUCCESSFUL_PAYMENT
.add(
1,
router_env::metric_attributes!(
(
"connector",
connector.to_owned().unwrap_or("null".to_string()),
),
("merchant_id", merchant_id.clone()),
),
),
}
}
} else if payment_attempt_status == enums::AttemptStatus::Failure {
if let Some(flow) = apple_pay_flow {
match flow {
domain::ApplePayFlow::Simplified(_) => {
metrics::APPLE_PAY_SIMPLIFIED_FLOW_FAILED_PAYMENT.add(
1,
router_env::metric_attributes!(
(
"connector",
connector.to_owned().unwrap_or("null".to_string()),
),
("merchant_id", merchant_id.clone()),
),
)
}
domain::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW_FAILED_PAYMENT.add(
1,
router_env::metric_attributes!(
(
"connector",
connector.to_owned().unwrap_or("null".to_string()),
),
("merchant_id", merchant_id.clone()),
),
),
}
}
}
}
pub fn check_if_pull_mechanism_for_external_3ds_enabled_from_connector_metadata(
metadata: Option<Value>,
) -> bool {
let external_three_ds_connector_metadata: Option<ExternalThreeDSConnectorMetadata> = metadata
.parse_value("ExternalThreeDSConnectorMetadata")
.map_err(|err| logger::warn!(parsing_error=?err,"Error while parsing ExternalThreeDSConnectorMetadata"))
.ok();
external_three_ds_connector_metadata
.and_then(|metadata| metadata.pull_mechanism_for_external_3ds_enabled)
.unwrap_or(true)
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
pub async fn trigger_payments_webhook<F, Op, D>(
merchant_account: domain::MerchantAccount,
business_profile: domain::Profile,
key_store: &domain::MerchantKeyStore,
payment_data: D,
customer: Option<domain::Customer>,
state: &SessionState,
operation: Op,
) -> RouterResult<()>
where
F: Send + Clone + Sync,
Op: Debug,
D: payments_core::OperationSessionGetters<F>,
{
todo!()
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
pub async fn trigger_payments_webhook<F, Op, D>(
merchant_account: domain::MerchantAccount,
business_profile: domain::Profile,
key_store: &domain::MerchantKeyStore,
payment_data: D,
customer: Option<domain::Customer>,
state: &SessionState,
operation: Op,
) -> RouterResult<()>
where
F: Send + Clone + Sync,
Op: Debug,
D: payments_core::OperationSessionGetters<F>,
{
let status = payment_data.get_payment_intent().status;
let payment_id = payment_data.get_payment_intent().get_id().to_owned();
let captures = payment_data
.get_multiple_capture_data()
.map(|multiple_capture_data| {
multiple_capture_data
.get_all_captures()
.into_iter()
.cloned()
.collect()
});
if matches!(
status,
enums::IntentStatus::Succeeded
| enums::IntentStatus::Failed
| enums::IntentStatus::PartiallyCaptured
| enums::IntentStatus::RequiresMerchantAction
) {
let payments_response = crate::core::payments::transformers::payments_to_payments_response(
payment_data,
captures,
customer,
services::AuthFlow::Merchant,
&state.base_url,
&operation,
&state.conf.connector_request_reference_id_config,
None,
None,
None,
)?;
let event_type = ForeignFrom::foreign_from(status);
if let services::ApplicationResponse::JsonWithHeaders((payments_response_json, _)) =
payments_response
{
let cloned_state = state.clone();
let cloned_key_store = key_store.clone();
// This spawns this futures in a background thread, the exception inside this future won't affect
// the current thread and the lifecycle of spawn thread is not handled by runtime.
// So when server shutdown won't wait for this thread's completion.
if let Some(event_type) = event_type {
tokio::spawn(
async move {
let primary_object_created_at = payments_response_json.created;
Box::pin(webhooks_core::create_event_and_trigger_outgoing_webhook(
cloned_state,
merchant_account,
business_profile,
&cloned_key_store,
event_type,
diesel_models::enums::EventClass::Payments,
payment_id.get_string_repr().to_owned(),
diesel_models::enums::EventObjectType::PaymentDetails,
webhooks::OutgoingWebhookContent::PaymentDetails(Box::new(
payments_response_json,
)),
primary_object_created_at,
))
.await
}
.in_current_span(),
);
} else {
logger::warn!(
"Outgoing webhook not sent because of missing event type status mapping"
);
}
}
}
Ok(())
}
type Handle<T> = tokio::task::JoinHandle<RouterResult<T>>;
pub async fn flatten_join_error<T>(handle: Handle<T>) -> RouterResult<T> {
match handle.await {
Ok(Ok(t)) => Ok(t),
Ok(Err(err)) => Err(err),
Err(err) => Err(err)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Join Error"),
}
}
#[cfg(feature = "v1")]
pub async fn trigger_refund_outgoing_webhook(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
refund: &diesel_models::Refund,
profile_id: id_type::ProfileId,
key_store: &domain::MerchantKeyStore,
) -> RouterResult<()> {
let refund_status = refund.refund_status;
if matches!(
refund_status,
enums::RefundStatus::Success
| enums::RefundStatus::Failure
| enums::RefundStatus::TransactionFailure
) {
let event_type = ForeignFrom::foreign_from(refund_status);
let refund_response: api_models::refunds::RefundResponse = refund.clone().foreign_into();
let key_manager_state = &(state).into();
let refund_id = refund_response.refund_id.clone();
let business_profile = state
.store
.find_business_profile_by_profile_id(key_manager_state, key_store, &profile_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let cloned_state = state.clone();
let cloned_key_store = key_store.clone();
let cloned_merchant_account = merchant_account.clone();
let primary_object_created_at = refund_response.created_at;
if let Some(outgoing_event_type) = event_type {
tokio::spawn(
async move {
Box::pin(webhooks_core::create_event_and_trigger_outgoing_webhook(
cloned_state,
cloned_merchant_account,
business_profile,
&cloned_key_store,
outgoing_event_type,
diesel_models::enums::EventClass::Refunds,
refund_id.to_string(),
diesel_models::enums::EventObjectType::RefundDetails,
webhooks::OutgoingWebhookContent::RefundDetails(Box::new(refund_response)),
primary_object_created_at,
))
.await
}
.in_current_span(),
);
} else {
logger::warn!("Outgoing webhook not sent because of missing event type status mapping");
};
}
Ok(())
}
#[cfg(feature = "v2")]
pub async fn trigger_refund_outgoing_webhook(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
refund: &diesel_models::Refund,
profile_id: id_type::ProfileId,
key_store: &domain::MerchantKeyStore,
) -> RouterResult<()> {
todo!()
}
pub fn get_locale_from_header(headers: &actix_web::http::header::HeaderMap) -> String {
get_header_value_by_key(ACCEPT_LANGUAGE.into(), headers)
.ok()
.flatten()
.map(|val| val.to_string())
.unwrap_or(common_utils::consts::DEFAULT_LOCALE.to_string())
}
| 9,852 | 1,207 |
hyperswitch | crates/router/src/locale.rs | .rs | use rust_i18n::i18n;
i18n!("locales", fallback = "en");
| 24 | 1,208 |
hyperswitch | crates/router/src/analytics.rs | .rs | pub use analytics::*;
pub mod routes {
use std::{
collections::{HashMap, HashSet},
sync::Arc,
};
use actix_web::{web, Responder, Scope};
use analytics::{
api_event::api_events_core, connector_events::connector_events_core, enums::AuthInfo,
errors::AnalyticsError, lambda_utils::invoke_lambda, opensearch::OpenSearchError,
outgoing_webhook_event::outgoing_webhook_events_core, sdk_events::sdk_events_core,
AnalyticsFlow,
};
use api_models::analytics::{
api_event::QueryType,
search::{
GetGlobalSearchRequest, GetSearchRequest, GetSearchRequestWithIndex, SearchIndex,
},
AnalyticsRequest, GenerateReportRequest, GetActivePaymentsMetricRequest,
GetApiEventFiltersRequest, GetApiEventMetricRequest, GetAuthEventFilterRequest,
GetAuthEventMetricRequest, GetDisputeMetricRequest, GetFrmFilterRequest,
GetFrmMetricRequest, GetPaymentFiltersRequest, GetPaymentIntentFiltersRequest,
GetPaymentIntentMetricRequest, GetPaymentMetricRequest, GetRefundFilterRequest,
GetRefundMetricRequest, GetSdkEventFiltersRequest, GetSdkEventMetricRequest, ReportRequest,
};
use common_enums::EntityType;
use common_utils::types::TimeRange;
use error_stack::{report, ResultExt};
use futures::{stream::FuturesUnordered, StreamExt};
use crate::{
analytics_validator::request_validator,
consts::opensearch::SEARCH_INDEXES,
core::{api_locking, errors::user::UserErrors, verification::utils},
db::{user::UserInterface, user_role::ListUserRolesByUserIdPayload},
routes::AppState,
services::{
api,
authentication::{self as auth, AuthenticationData, UserFromToken},
authorization::{permissions::Permission, roles::RoleInfo},
ApplicationResponse,
},
types::{domain::UserEmail, storage::UserRole},
};
pub struct Analytics;
impl Analytics {
#[cfg(feature = "v2")]
pub fn server(state: AppState) -> Scope {
web::scope("/analytics").app_data(web::Data::new(state))
}
#[cfg(feature = "v1")]
pub fn server(state: AppState) -> Scope {
web::scope("/analytics")
.app_data(web::Data::new(state))
.service(
web::scope("/v1")
.service(
web::resource("metrics/payments")
.route(web::post().to(get_merchant_payment_metrics)),
)
.service(
web::resource("metrics/refunds")
.route(web::post().to(get_merchant_refund_metrics)),
)
.service(
web::resource("filters/payments")
.route(web::post().to(get_merchant_payment_filters)),
)
.service(
web::resource("filters/frm").route(web::post().to(get_frm_filters)),
)
.service(
web::resource("filters/refunds")
.route(web::post().to(get_merchant_refund_filters)),
)
.service(web::resource("{domain}/info").route(web::get().to(get_info)))
.service(
web::resource("report/dispute")
.route(web::post().to(generate_merchant_dispute_report)),
)
.service(
web::resource("report/refunds")
.route(web::post().to(generate_merchant_refund_report)),
)
.service(
web::resource("report/payments")
.route(web::post().to(generate_merchant_payment_report)),
)
.service(
web::resource("report/authentications")
.route(web::post().to(generate_merchant_authentication_report)),
)
.service(
web::resource("metrics/sdk_events")
.route(web::post().to(get_sdk_event_metrics)),
)
.service(
web::resource("metrics/active_payments")
.route(web::post().to(get_active_payments_metrics)),
)
.service(
web::resource("filters/sdk_events")
.route(web::post().to(get_sdk_event_filters)),
)
.service(
web::resource("metrics/auth_events")
.route(web::post().to(get_auth_event_metrics)),
)
.service(
web::resource("filters/auth_events")
.route(web::post().to(get_merchant_auth_events_filters)),
)
.service(
web::resource("metrics/frm").route(web::post().to(get_frm_metrics)),
)
.service(
web::resource("api_event_logs")
.route(web::get().to(get_profile_api_events)),
)
.service(
web::resource("sdk_event_logs")
.route(web::post().to(get_profile_sdk_events)),
)
.service(
web::resource("connector_event_logs")
.route(web::get().to(get_profile_connector_events)),
)
.service(
web::resource("outgoing_webhook_event_logs")
.route(web::get().to(get_profile_outgoing_webhook_events)),
)
.service(
web::resource("metrics/api_events")
.route(web::post().to(get_merchant_api_events_metrics)),
)
.service(
web::resource("filters/api_events")
.route(web::post().to(get_merchant_api_event_filters)),
)
.service(
web::resource("search")
.route(web::post().to(get_global_search_results)),
)
.service(
web::resource("search/{domain}")
.route(web::post().to(get_search_results)),
)
.service(
web::resource("metrics/disputes")
.route(web::post().to(get_merchant_dispute_metrics)),
)
.service(
web::resource("filters/disputes")
.route(web::post().to(get_merchant_dispute_filters)),
)
.service(
web::resource("metrics/sankey")
.route(web::post().to(get_merchant_sankey)),
)
.service(
web::scope("/merchant")
.service(
web::resource("metrics/payments")
.route(web::post().to(get_merchant_payment_metrics)),
)
.service(
web::resource("metrics/refunds")
.route(web::post().to(get_merchant_refund_metrics)),
)
.service(
web::resource("filters/payments")
.route(web::post().to(get_merchant_payment_filters)),
)
.service(
web::resource("filters/refunds")
.route(web::post().to(get_merchant_refund_filters)),
)
.service(
web::resource("{domain}/info").route(web::get().to(get_info)),
)
.service(
web::resource("report/dispute")
.route(web::post().to(generate_merchant_dispute_report)),
)
.service(
web::resource("report/refunds")
.route(web::post().to(generate_merchant_refund_report)),
)
.service(
web::resource("report/payments")
.route(web::post().to(generate_merchant_payment_report)),
)
.service(
web::resource("report/authentications").route(
web::post().to(generate_merchant_authentication_report),
),
)
.service(
web::resource("metrics/api_events")
.route(web::post().to(get_merchant_api_events_metrics)),
)
.service(
web::resource("filters/api_events")
.route(web::post().to(get_merchant_api_event_filters)),
)
.service(
web::resource("metrics/disputes")
.route(web::post().to(get_merchant_dispute_metrics)),
)
.service(
web::resource("filters/disputes")
.route(web::post().to(get_merchant_dispute_filters)),
)
.service(
web::resource("metrics/sankey")
.route(web::post().to(get_merchant_sankey)),
),
)
.service(
web::scope("/org")
.service(
web::resource("{domain}/info").route(web::get().to(get_info)),
)
.service(
web::resource("metrics/payments")
.route(web::post().to(get_org_payment_metrics)),
)
.service(
web::resource("filters/payments")
.route(web::post().to(get_org_payment_filters)),
)
.service(
web::resource("metrics/refunds")
.route(web::post().to(get_org_refund_metrics)),
)
.service(
web::resource("filters/refunds")
.route(web::post().to(get_org_refund_filters)),
)
.service(
web::resource("metrics/disputes")
.route(web::post().to(get_org_dispute_metrics)),
)
.service(
web::resource("filters/disputes")
.route(web::post().to(get_org_dispute_filters)),
)
.service(
web::resource("report/dispute")
.route(web::post().to(generate_org_dispute_report)),
)
.service(
web::resource("report/refunds")
.route(web::post().to(generate_org_refund_report)),
)
.service(
web::resource("report/payments")
.route(web::post().to(generate_org_payment_report)),
)
.service(
web::resource("report/authentications")
.route(web::post().to(generate_org_authentication_report)),
)
.service(
web::resource("metrics/sankey")
.route(web::post().to(get_org_sankey)),
),
)
.service(
web::scope("/profile")
.service(
web::resource("{domain}/info").route(web::get().to(get_info)),
)
.service(
web::resource("metrics/payments")
.route(web::post().to(get_profile_payment_metrics)),
)
.service(
web::resource("filters/payments")
.route(web::post().to(get_profile_payment_filters)),
)
.service(
web::resource("metrics/refunds")
.route(web::post().to(get_profile_refund_metrics)),
)
.service(
web::resource("filters/refunds")
.route(web::post().to(get_profile_refund_filters)),
)
.service(
web::resource("metrics/disputes")
.route(web::post().to(get_profile_dispute_metrics)),
)
.service(
web::resource("filters/disputes")
.route(web::post().to(get_profile_dispute_filters)),
)
.service(
web::resource("connector_event_logs")
.route(web::get().to(get_profile_connector_events)),
)
.service(
web::resource("outgoing_webhook_event_logs")
.route(web::get().to(get_profile_outgoing_webhook_events)),
)
.service(
web::resource("report/dispute")
.route(web::post().to(generate_profile_dispute_report)),
)
.service(
web::resource("report/refunds")
.route(web::post().to(generate_profile_refund_report)),
)
.service(
web::resource("report/payments")
.route(web::post().to(generate_profile_payment_report)),
)
.service(
web::resource("report/authentications").route(
web::post().to(generate_profile_authentication_report),
),
)
.service(
web::resource("api_event_logs")
.route(web::get().to(get_profile_api_events)),
)
.service(
web::resource("sdk_event_logs")
.route(web::post().to(get_profile_sdk_events)),
)
.service(
web::resource("metrics/sankey")
.route(web::post().to(get_profile_sankey)),
),
),
)
.service(
web::scope("/v2")
.service(
web::resource("/metrics/payments")
.route(web::post().to(get_merchant_payment_intent_metrics)),
)
.service(
web::resource("/filters/payments")
.route(web::post().to(get_payment_intents_filters)),
)
.service(
web::scope("/merchant")
.service(
web::resource("/metrics/payments")
.route(web::post().to(get_merchant_payment_intent_metrics)),
)
.service(
web::resource("/filters/payments")
.route(web::post().to(get_payment_intents_filters)),
),
)
.service(
web::scope("/org").service(
web::resource("/metrics/payments")
.route(web::post().to(get_org_payment_intent_metrics)),
),
)
.service(
web::scope("/profile").service(
web::resource("/metrics/payments")
.route(web::post().to(get_profile_payment_intent_metrics)),
),
),
)
}
}
pub async fn get_info(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
domain: web::Path<analytics::AnalyticsDomain>,
) -> impl Responder {
let flow = AnalyticsFlow::GetInfo;
Box::pin(api::server_wrap(
flow,
state,
&req,
domain.into_inner(),
|_, _: (), domain: analytics::AnalyticsDomain, _| async {
analytics::core::get_domain_info(domain)
.await
.map(ApplicationResponse::Json)
},
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
/// # Panics
///
/// Panics if `json_payload` array does not contain one `GetPaymentMetricRequest` element.
pub async fn get_merchant_payment_metrics(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<[GetPaymentMetricRequest; 1]>,
) -> impl Responder {
// safety: This shouldn't panic owing to the data type
#[allow(clippy::expect_used)]
let payload = json_payload
.into_inner()
.to_vec()
.pop()
.expect("Couldn't get GetPaymentMetricRequest");
let flow = AnalyticsFlow::GetPaymentMetrics;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: AuthenticationData, req, _| async move {
let org_id = auth.merchant_account.get_org_id();
let merchant_id = auth.merchant_account.get_id();
let auth: AuthInfo = AuthInfo::MerchantLevel {
org_id: org_id.clone(),
merchant_ids: vec![merchant_id.clone()],
};
let validator_response = request_validator(
AnalyticsRequest {
payment_attempt: Some(req.clone()),
..Default::default()
},
&state,
)
.await?;
let ex_rates = validator_response;
analytics::payments::get_metrics(&state.pool, &ex_rates, &auth, req)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
/// # Panics
///
/// Panics if `json_payload` array does not contain one `GetPaymentMetricRequest` element.
pub async fn get_org_payment_metrics(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<[GetPaymentMetricRequest; 1]>,
) -> impl Responder {
// safety: This shouldn't panic owing to the data type
#[allow(clippy::expect_used)]
let payload = json_payload
.into_inner()
.to_vec()
.pop()
.expect("Couldn't get GetPaymentMetricRequest");
let flow = AnalyticsFlow::GetPaymentMetrics;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: AuthenticationData, req, _| async move {
let org_id = auth.merchant_account.get_org_id();
let auth: AuthInfo = AuthInfo::OrgLevel {
org_id: org_id.clone(),
};
let validator_response = request_validator(
AnalyticsRequest {
payment_attempt: Some(req.clone()),
..Default::default()
},
&state,
)
.await?;
let ex_rates = validator_response;
analytics::payments::get_metrics(&state.pool, &ex_rates, &auth, req)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::OrganizationAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// # Panics
///
/// Panics if `json_payload` array does not contain one `GetPaymentMetricRequest` element.
pub async fn get_profile_payment_metrics(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<[GetPaymentMetricRequest; 1]>,
) -> impl Responder {
// safety: This shouldn't panic owing to the data type
#[allow(clippy::expect_used)]
let payload = json_payload
.into_inner()
.to_vec()
.pop()
.expect("Couldn't get GetPaymentMetricRequest");
let flow = AnalyticsFlow::GetPaymentMetrics;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: AuthenticationData, req, _| async move {
let org_id = auth.merchant_account.get_org_id();
let merchant_id = auth.merchant_account.get_id();
let profile_id = auth
.profile_id
.ok_or(report!(UserErrors::JwtProfileIdMissing))
.change_context(AnalyticsError::AccessForbiddenError)?;
let auth: AuthInfo = AuthInfo::ProfileLevel {
org_id: org_id.clone(),
merchant_id: merchant_id.clone(),
profile_ids: vec![profile_id.clone()],
};
let validator_response = request_validator(
AnalyticsRequest {
payment_attempt: Some(req.clone()),
..Default::default()
},
&state,
)
.await?;
let ex_rates = validator_response;
analytics::payments::get_metrics(&state.pool, &ex_rates, &auth, req)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
/// # Panics
///
/// Panics if `json_payload` array does not contain one `GetPaymentIntentMetricRequest` element.
pub async fn get_merchant_payment_intent_metrics(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<[GetPaymentIntentMetricRequest; 1]>,
) -> impl Responder {
// safety: This shouldn't panic owing to the data type
#[allow(clippy::expect_used)]
let payload = json_payload
.into_inner()
.to_vec()
.pop()
.expect("Couldn't get GetPaymentIntentMetricRequest");
let flow = AnalyticsFlow::GetPaymentIntentMetrics;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: AuthenticationData, req, _| async move {
let org_id = auth.merchant_account.get_org_id();
let merchant_id = auth.merchant_account.get_id();
let auth: AuthInfo = AuthInfo::MerchantLevel {
org_id: org_id.clone(),
merchant_ids: vec![merchant_id.clone()],
};
let validator_response = request_validator(
AnalyticsRequest {
payment_intent: Some(req.clone()),
..Default::default()
},
&state,
)
.await?;
let ex_rates = validator_response;
analytics::payment_intents::get_metrics(&state.pool, &ex_rates, &auth, req)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
/// # Panics
///
/// Panics if `json_payload` array does not contain one `GetPaymentIntentMetricRequest` element.
pub async fn get_org_payment_intent_metrics(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<[GetPaymentIntentMetricRequest; 1]>,
) -> impl Responder {
// safety: This shouldn't panic owing to the data type
#[allow(clippy::expect_used)]
let payload = json_payload
.into_inner()
.to_vec()
.pop()
.expect("Couldn't get GetPaymentIntentMetricRequest");
let flow = AnalyticsFlow::GetPaymentIntentMetrics;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: AuthenticationData, req, _| async move {
let org_id = auth.merchant_account.get_org_id();
let auth: AuthInfo = AuthInfo::OrgLevel {
org_id: org_id.clone(),
};
let validator_response = request_validator(
AnalyticsRequest {
payment_intent: Some(req.clone()),
..Default::default()
},
&state,
)
.await?;
let ex_rates = validator_response;
analytics::payment_intents::get_metrics(&state.pool, &ex_rates, &auth, req)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::OrganizationAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// # Panics
///
/// Panics if `json_payload` array does not contain one `GetPaymentIntentMetricRequest` element.
pub async fn get_profile_payment_intent_metrics(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<[GetPaymentIntentMetricRequest; 1]>,
) -> impl Responder {
// safety: This shouldn't panic owing to the data type
#[allow(clippy::expect_used)]
let payload = json_payload
.into_inner()
.to_vec()
.pop()
.expect("Couldn't get GetPaymentIntentMetricRequest");
let flow = AnalyticsFlow::GetPaymentIntentMetrics;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: AuthenticationData, req, _| async move {
let org_id = auth.merchant_account.get_org_id();
let merchant_id = auth.merchant_account.get_id();
let profile_id = auth
.profile_id
.ok_or(report!(UserErrors::JwtProfileIdMissing))
.change_context(AnalyticsError::AccessForbiddenError)?;
let auth: AuthInfo = AuthInfo::ProfileLevel {
org_id: org_id.clone(),
merchant_id: merchant_id.clone(),
profile_ids: vec![profile_id.clone()],
};
let validator_response = request_validator(
AnalyticsRequest {
payment_intent: Some(req.clone()),
..Default::default()
},
&state,
)
.await?;
let ex_rates = validator_response;
analytics::payment_intents::get_metrics(&state.pool, &ex_rates, &auth, req)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
/// # Panics
///
/// Panics if `json_payload` array does not contain one `GetRefundMetricRequest` element.
pub async fn get_merchant_refund_metrics(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<[GetRefundMetricRequest; 1]>,
) -> impl Responder {
#[allow(clippy::expect_used)]
// safety: This shouldn't panic owing to the data type
let payload = json_payload
.into_inner()
.to_vec()
.pop()
.expect("Couldn't get GetRefundMetricRequest");
let flow = AnalyticsFlow::GetRefundsMetrics;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: AuthenticationData, req, _| async move {
let org_id = auth.merchant_account.get_org_id();
let merchant_id = auth.merchant_account.get_id();
let auth: AuthInfo = AuthInfo::MerchantLevel {
org_id: org_id.clone(),
merchant_ids: vec![merchant_id.clone()],
};
let validator_response = request_validator(
AnalyticsRequest {
refund: Some(req.clone()),
..Default::default()
},
&state,
)
.await?;
let ex_rates = validator_response;
analytics::refunds::get_metrics(&state.pool, &ex_rates, &auth, req)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
/// # Panics
///
/// Panics if `json_payload` array does not contain one `GetRefundMetricRequest` element.
pub async fn get_org_refund_metrics(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<[GetRefundMetricRequest; 1]>,
) -> impl Responder {
#[allow(clippy::expect_used)]
// safety: This shouldn't panic owing to the data type
let payload = json_payload
.into_inner()
.to_vec()
.pop()
.expect("Couldn't get GetRefundMetricRequest");
let flow = AnalyticsFlow::GetRefundsMetrics;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: AuthenticationData, req, _| async move {
let org_id = auth.merchant_account.get_org_id();
let auth: AuthInfo = AuthInfo::OrgLevel {
org_id: org_id.clone(),
};
let validator_response = request_validator(
AnalyticsRequest {
refund: Some(req.clone()),
..Default::default()
},
&state,
)
.await?;
let ex_rates = validator_response;
analytics::refunds::get_metrics(&state.pool, &ex_rates, &auth, req)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::OrganizationAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// # Panics
///
/// Panics if `json_payload` array does not contain one `GetRefundMetricRequest` element.
pub async fn get_profile_refund_metrics(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<[GetRefundMetricRequest; 1]>,
) -> impl Responder {
#[allow(clippy::expect_used)]
// safety: This shouldn't panic owing to the data type
let payload = json_payload
.into_inner()
.to_vec()
.pop()
.expect("Couldn't get GetRefundMetricRequest");
let flow = AnalyticsFlow::GetRefundsMetrics;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: AuthenticationData, req, _| async move {
let org_id = auth.merchant_account.get_org_id();
let merchant_id = auth.merchant_account.get_id();
let profile_id = auth
.profile_id
.ok_or(report!(UserErrors::JwtProfileIdMissing))
.change_context(AnalyticsError::AccessForbiddenError)?;
let auth: AuthInfo = AuthInfo::ProfileLevel {
org_id: org_id.clone(),
merchant_id: merchant_id.clone(),
profile_ids: vec![profile_id.clone()],
};
let validator_response = request_validator(
AnalyticsRequest {
refund: Some(req.clone()),
..Default::default()
},
&state,
)
.await?;
let ex_rates = validator_response;
analytics::refunds::get_metrics(&state.pool, &ex_rates, &auth, req)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
/// # Panics
///
/// Panics if `json_payload` array does not contain one `GetFrmMetricRequest` element.
pub async fn get_frm_metrics(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<[GetFrmMetricRequest; 1]>,
) -> impl Responder {
#[allow(clippy::expect_used)]
// safety: This shouldn't panic owing to the data type
let payload = json_payload
.into_inner()
.to_vec()
.pop()
.expect("Couldn't get GetFrmMetricRequest");
let flow = AnalyticsFlow::GetFrmMetrics;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: AuthenticationData, req, _| async move {
analytics::frm::get_metrics(&state.pool, auth.merchant_account.get_id(), req)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// # Panics
///
/// Panics if `json_payload` array does not contain one `GetSdkEventMetricRequest` element.
pub async fn get_sdk_event_metrics(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<[GetSdkEventMetricRequest; 1]>,
) -> impl Responder {
// safety: This shouldn't panic owing to the data type
#[allow(clippy::expect_used)]
let payload = json_payload
.into_inner()
.to_vec()
.pop()
.expect("Couldn't get GetSdkEventMetricRequest");
let flow = AnalyticsFlow::GetSdkMetrics;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: AuthenticationData, req, _| async move {
analytics::sdk_events::get_metrics(
&state.pool,
&auth.merchant_account.publishable_key,
req,
)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// # Panics
///
/// Panics if `json_payload` array does not contain one `GetActivePaymentsMetricRequest` element.
pub async fn get_active_payments_metrics(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<[GetActivePaymentsMetricRequest; 1]>,
) -> impl Responder {
// safety: This shouldn't panic owing to the data type
#[allow(clippy::expect_used)]
let payload = json_payload
.into_inner()
.to_vec()
.pop()
.expect("Couldn't get GetActivePaymentsMetricRequest");
let flow = AnalyticsFlow::GetActivePaymentsMetrics;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: AuthenticationData, req, _| async move {
analytics::active_payments::get_metrics(
&state.pool,
&auth.merchant_account.publishable_key,
auth.merchant_account.get_id(),
req,
)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// # Panics
///
/// Panics if `json_payload` array does not contain one `GetAuthEventMetricRequest` element.
pub async fn get_auth_event_metrics(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<[GetAuthEventMetricRequest; 1]>,
) -> impl Responder {
// safety: This shouldn't panic owing to the data type
#[allow(clippy::expect_used)]
let payload = json_payload
.into_inner()
.to_vec()
.pop()
.expect("Couldn't get GetAuthEventMetricRequest");
let flow = AnalyticsFlow::GetAuthMetrics;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: AuthenticationData, req, _| async move {
analytics::auth_events::get_metrics(
&state.pool,
auth.merchant_account.get_id(),
req,
)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn get_merchant_payment_filters(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<GetPaymentFiltersRequest>,
) -> impl Responder {
let flow = AnalyticsFlow::GetPaymentFilters;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: AuthenticationData, req, _| async move {
let org_id = auth.merchant_account.get_org_id();
let merchant_id = auth.merchant_account.get_id();
let auth: AuthInfo = AuthInfo::MerchantLevel {
org_id: org_id.clone(),
merchant_ids: vec![merchant_id.clone()],
};
analytics::payments::get_filters(&state.pool, req, &auth)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn get_merchant_auth_events_filters(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<GetAuthEventFilterRequest>,
) -> impl Responder {
let flow = AnalyticsFlow::GetAuthEventFilters;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: AuthenticationData, req, _| async move {
analytics::auth_events::get_filters(
&state.pool,
req,
auth.merchant_account.get_id(),
)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn get_org_payment_filters(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<GetPaymentFiltersRequest>,
) -> impl Responder {
let flow = AnalyticsFlow::GetPaymentFilters;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: AuthenticationData, req, _| async move {
let org_id = auth.merchant_account.get_org_id();
let auth: AuthInfo = AuthInfo::OrgLevel {
org_id: org_id.clone(),
};
analytics::payments::get_filters(&state.pool, req, &auth)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::OrganizationAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
pub async fn get_profile_payment_filters(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<GetPaymentFiltersRequest>,
) -> impl Responder {
let flow = AnalyticsFlow::GetPaymentFilters;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: AuthenticationData, req, _| async move {
let org_id = auth.merchant_account.get_org_id();
let merchant_id = auth.merchant_account.get_id();
let profile_id = auth
.profile_id
.ok_or(report!(UserErrors::JwtProfileIdMissing))
.change_context(AnalyticsError::AccessForbiddenError)?;
let auth: AuthInfo = AuthInfo::ProfileLevel {
org_id: org_id.clone(),
merchant_id: merchant_id.clone(),
profile_ids: vec![profile_id.clone()],
};
analytics::payments::get_filters(&state.pool, req, &auth)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn get_payment_intents_filters(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<GetPaymentIntentFiltersRequest>,
) -> impl Responder {
let flow = AnalyticsFlow::GetPaymentIntentFilters;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: AuthenticationData, req, _| async move {
analytics::payment_intents::get_filters(
&state.pool,
req,
auth.merchant_account.get_id(),
)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn get_merchant_refund_filters(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<GetRefundFilterRequest>,
) -> impl Responder {
let flow = AnalyticsFlow::GetRefundFilters;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: AuthenticationData, req: GetRefundFilterRequest, _| async move {
let org_id = auth.merchant_account.get_org_id();
let merchant_id = auth.merchant_account.get_id();
let auth: AuthInfo = AuthInfo::MerchantLevel {
org_id: org_id.clone(),
merchant_ids: vec![merchant_id.clone()],
};
analytics::refunds::get_filters(&state.pool, req, &auth)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn get_org_refund_filters(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<GetRefundFilterRequest>,
) -> impl Responder {
let flow = AnalyticsFlow::GetRefundFilters;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: AuthenticationData, req: GetRefundFilterRequest, _| async move {
let org_id = auth.merchant_account.get_org_id();
let auth: AuthInfo = AuthInfo::OrgLevel {
org_id: org_id.clone(),
};
analytics::refunds::get_filters(&state.pool, req, &auth)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::OrganizationAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
pub async fn get_profile_refund_filters(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<GetRefundFilterRequest>,
) -> impl Responder {
let flow = AnalyticsFlow::GetRefundFilters;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: AuthenticationData, req: GetRefundFilterRequest, _| async move {
let org_id = auth.merchant_account.get_org_id();
let merchant_id = auth.merchant_account.get_id();
let profile_id = auth
.profile_id
.ok_or(report!(UserErrors::JwtProfileIdMissing))
.change_context(AnalyticsError::AccessForbiddenError)?;
let auth: AuthInfo = AuthInfo::ProfileLevel {
org_id: org_id.clone(),
merchant_id: merchant_id.clone(),
profile_ids: vec![profile_id.clone()],
};
analytics::refunds::get_filters(&state.pool, req, &auth)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn get_frm_filters(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<GetFrmFilterRequest>,
) -> impl Responder {
let flow = AnalyticsFlow::GetFrmFilters;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: AuthenticationData, req: GetFrmFilterRequest, _| async move {
analytics::frm::get_filters(&state.pool, req, auth.merchant_account.get_id())
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
pub async fn get_sdk_event_filters(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<GetSdkEventFiltersRequest>,
) -> impl Responder {
let flow = AnalyticsFlow::GetSdkEventFilters;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: AuthenticationData, req, _| async move {
analytics::sdk_events::get_filters(
&state.pool,
req,
&auth.merchant_account.publishable_key,
)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn get_profile_api_events(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Query<api_models::analytics::api_event::ApiLogsRequest>,
) -> impl Responder {
let flow = AnalyticsFlow::GetApiEvents;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: AuthenticationData, req, _| async move {
let payment_id = match req.query_param.clone() {
QueryType::Payment { payment_id } => payment_id,
QueryType::Refund { payment_id, .. } => payment_id,
QueryType::Dispute { payment_id, .. } => payment_id,
};
utils::check_if_profile_id_is_present_in_payment_intent(payment_id, &state, &auth)
.await
.change_context(AnalyticsError::AccessForbiddenError)?;
api_events_core(&state.pool, req, auth.merchant_account.get_id())
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn get_profile_outgoing_webhook_events(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Query<
api_models::analytics::outgoing_webhook_event::OutgoingWebhookLogsRequest,
>,
) -> impl Responder {
let flow = AnalyticsFlow::GetOutgoingWebhookEvents;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: AuthenticationData, req, _| async move {
utils::check_if_profile_id_is_present_in_payment_intent(
req.payment_id.clone(),
&state,
&auth,
)
.await
.change_context(AnalyticsError::AccessForbiddenError)?;
outgoing_webhook_events_core(&state.pool, req, auth.merchant_account.get_id())
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
pub async fn get_profile_sdk_events(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<api_models::analytics::sdk_events::SdkEventsRequest>,
) -> impl Responder {
let flow = AnalyticsFlow::GetSdkEvents;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: AuthenticationData, req, _| async move {
utils::check_if_profile_id_is_present_in_payment_intent(
req.payment_id.clone(),
&state,
&auth,
)
.await
.change_context(AnalyticsError::AccessForbiddenError)?;
sdk_events_core(&state.pool, req, &auth.merchant_account.publishable_key)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
pub async fn generate_merchant_refund_report(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<ReportRequest>,
) -> impl Responder {
let flow = AnalyticsFlow::GenerateRefundReport;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
json_payload.into_inner(),
|state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move {
let user = UserInterface::find_user_by_id(&*state.global_store, &user_id)
.await
.change_context(AnalyticsError::UnknownError)?;
let user_email = UserEmail::from_pii_email(user.email)
.change_context(AnalyticsError::UnknownError)?
.get_secret();
let org_id = auth.merchant_account.get_org_id();
let merchant_id = auth.merchant_account.get_id();
let lambda_req = GenerateReportRequest {
request: payload,
merchant_id: Some(merchant_id.clone()),
auth: AuthInfo::MerchantLevel {
org_id: org_id.clone(),
merchant_ids: vec![merchant_id.clone()],
},
email: user_email,
};
let json_bytes =
serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?;
invoke_lambda(
&state.conf.report_download_config.refund_function,
&state.conf.report_download_config.region,
&json_bytes,
)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::MerchantReportRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
pub async fn generate_org_refund_report(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<ReportRequest>,
) -> impl Responder {
let flow = AnalyticsFlow::GenerateRefundReport;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
json_payload.into_inner(),
|state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move {
let user = UserInterface::find_user_by_id(&*state.global_store, &user_id)
.await
.change_context(AnalyticsError::UnknownError)?;
let user_email = UserEmail::from_pii_email(user.email)
.change_context(AnalyticsError::UnknownError)?
.get_secret();
let org_id = auth.merchant_account.get_org_id();
let lambda_req = GenerateReportRequest {
request: payload,
merchant_id: None,
auth: AuthInfo::OrgLevel {
org_id: org_id.clone(),
},
email: user_email,
};
let json_bytes =
serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?;
invoke_lambda(
&state.conf.report_download_config.refund_function,
&state.conf.report_download_config.region,
&json_bytes,
)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::OrganizationReportRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
pub async fn generate_profile_refund_report(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<ReportRequest>,
) -> impl Responder {
let flow = AnalyticsFlow::GenerateRefundReport;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
json_payload.into_inner(),
|state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move {
let user = UserInterface::find_user_by_id(&*state.global_store, &user_id)
.await
.change_context(AnalyticsError::UnknownError)?;
let user_email = UserEmail::from_pii_email(user.email)
.change_context(AnalyticsError::UnknownError)?
.get_secret();
let org_id = auth.merchant_account.get_org_id();
let merchant_id = auth.merchant_account.get_id();
let profile_id = auth
.profile_id
.ok_or(report!(UserErrors::JwtProfileIdMissing))
.change_context(AnalyticsError::AccessForbiddenError)?;
let lambda_req = GenerateReportRequest {
request: payload,
merchant_id: Some(merchant_id.clone()),
auth: AuthInfo::ProfileLevel {
org_id: org_id.clone(),
merchant_id: merchant_id.clone(),
profile_ids: vec![profile_id.clone()],
},
email: user_email,
};
let json_bytes =
serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?;
invoke_lambda(
&state.conf.report_download_config.refund_function,
&state.conf.report_download_config.region,
&json_bytes,
)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::ProfileReportRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
pub async fn generate_merchant_dispute_report(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<ReportRequest>,
) -> impl Responder {
let flow = AnalyticsFlow::GenerateDisputeReport;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
json_payload.into_inner(),
|state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move {
let user = UserInterface::find_user_by_id(&*state.global_store, &user_id)
.await
.change_context(AnalyticsError::UnknownError)?;
let user_email = UserEmail::from_pii_email(user.email)
.change_context(AnalyticsError::UnknownError)?
.get_secret();
let org_id = auth.merchant_account.get_org_id();
let merchant_id = auth.merchant_account.get_id();
let lambda_req = GenerateReportRequest {
request: payload,
merchant_id: Some(merchant_id.clone()),
auth: AuthInfo::MerchantLevel {
org_id: org_id.clone(),
merchant_ids: vec![merchant_id.clone()],
},
email: user_email,
};
let json_bytes =
serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?;
invoke_lambda(
&state.conf.report_download_config.dispute_function,
&state.conf.report_download_config.region,
&json_bytes,
)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::MerchantReportRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
pub async fn generate_org_dispute_report(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<ReportRequest>,
) -> impl Responder {
let flow = AnalyticsFlow::GenerateDisputeReport;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
json_payload.into_inner(),
|state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move {
let user = UserInterface::find_user_by_id(&*state.global_store, &user_id)
.await
.change_context(AnalyticsError::UnknownError)?;
let user_email = UserEmail::from_pii_email(user.email)
.change_context(AnalyticsError::UnknownError)?
.get_secret();
let org_id = auth.merchant_account.get_org_id();
let lambda_req = GenerateReportRequest {
request: payload,
merchant_id: None,
auth: AuthInfo::OrgLevel {
org_id: org_id.clone(),
},
email: user_email,
};
let json_bytes =
serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?;
invoke_lambda(
&state.conf.report_download_config.dispute_function,
&state.conf.report_download_config.region,
&json_bytes,
)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::OrganizationReportRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
pub async fn generate_profile_dispute_report(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<ReportRequest>,
) -> impl Responder {
let flow = AnalyticsFlow::GenerateDisputeReport;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
json_payload.into_inner(),
|state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move {
let user = UserInterface::find_user_by_id(&*state.global_store, &user_id)
.await
.change_context(AnalyticsError::UnknownError)?;
let user_email = UserEmail::from_pii_email(user.email)
.change_context(AnalyticsError::UnknownError)?
.get_secret();
let org_id = auth.merchant_account.get_org_id();
let merchant_id = auth.merchant_account.get_id();
let profile_id = auth
.profile_id
.ok_or(report!(UserErrors::JwtProfileIdMissing))
.change_context(AnalyticsError::AccessForbiddenError)?;
let lambda_req = GenerateReportRequest {
request: payload,
merchant_id: Some(merchant_id.clone()),
auth: AuthInfo::ProfileLevel {
org_id: org_id.clone(),
merchant_id: merchant_id.clone(),
profile_ids: vec![profile_id.clone()],
},
email: user_email,
};
let json_bytes =
serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?;
invoke_lambda(
&state.conf.report_download_config.dispute_function,
&state.conf.report_download_config.region,
&json_bytes,
)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::ProfileReportRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
pub async fn generate_merchant_payment_report(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<ReportRequest>,
) -> impl Responder {
let flow = AnalyticsFlow::GeneratePaymentReport;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
json_payload.into_inner(),
|state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move {
let user = UserInterface::find_user_by_id(&*state.global_store, &user_id)
.await
.change_context(AnalyticsError::UnknownError)?;
let user_email = UserEmail::from_pii_email(user.email)
.change_context(AnalyticsError::UnknownError)?
.get_secret();
let org_id = auth.merchant_account.get_org_id();
let merchant_id = auth.merchant_account.get_id();
let lambda_req = GenerateReportRequest {
request: payload,
merchant_id: Some(merchant_id.clone()),
auth: AuthInfo::MerchantLevel {
org_id: org_id.clone(),
merchant_ids: vec![merchant_id.clone()],
},
email: user_email,
};
let json_bytes =
serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?;
invoke_lambda(
&state.conf.report_download_config.payment_function,
&state.conf.report_download_config.region,
&json_bytes,
)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::MerchantReportRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
pub async fn generate_org_payment_report(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<ReportRequest>,
) -> impl Responder {
let flow = AnalyticsFlow::GeneratePaymentReport;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
json_payload.into_inner(),
|state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move {
let user = UserInterface::find_user_by_id(&*state.global_store, &user_id)
.await
.change_context(AnalyticsError::UnknownError)?;
let user_email = UserEmail::from_pii_email(user.email)
.change_context(AnalyticsError::UnknownError)?
.get_secret();
let org_id = auth.merchant_account.get_org_id();
let lambda_req = GenerateReportRequest {
request: payload,
merchant_id: None,
auth: AuthInfo::OrgLevel {
org_id: org_id.clone(),
},
email: user_email,
};
let json_bytes =
serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?;
invoke_lambda(
&state.conf.report_download_config.payment_function,
&state.conf.report_download_config.region,
&json_bytes,
)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::OrganizationReportRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
pub async fn generate_profile_payment_report(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<ReportRequest>,
) -> impl Responder {
let flow = AnalyticsFlow::GeneratePaymentReport;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
json_payload.into_inner(),
|state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move {
let user = UserInterface::find_user_by_id(&*state.global_store, &user_id)
.await
.change_context(AnalyticsError::UnknownError)?;
let user_email = UserEmail::from_pii_email(user.email)
.change_context(AnalyticsError::UnknownError)?
.get_secret();
let org_id = auth.merchant_account.get_org_id();
let merchant_id = auth.merchant_account.get_id();
let profile_id = auth
.profile_id
.ok_or(report!(UserErrors::JwtProfileIdMissing))
.change_context(AnalyticsError::AccessForbiddenError)?;
let lambda_req = GenerateReportRequest {
request: payload,
merchant_id: Some(merchant_id.clone()),
auth: AuthInfo::ProfileLevel {
org_id: org_id.clone(),
merchant_id: merchant_id.clone(),
profile_ids: vec![profile_id.clone()],
},
email: user_email,
};
let json_bytes =
serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?;
invoke_lambda(
&state.conf.report_download_config.payment_function,
&state.conf.report_download_config.region,
&json_bytes,
)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::ProfileReportRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
pub async fn generate_merchant_authentication_report(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<ReportRequest>,
) -> impl Responder {
let flow = AnalyticsFlow::GenerateAuthenticationReport;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
json_payload.into_inner(),
|state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move {
let user = UserInterface::find_user_by_id(&*state.global_store, &user_id)
.await
.change_context(AnalyticsError::UnknownError)?;
let user_email = UserEmail::from_pii_email(user.email)
.change_context(AnalyticsError::UnknownError)?
.get_secret();
let org_id = auth.merchant_account.get_org_id();
let merchant_id = auth.merchant_account.get_id();
let lambda_req = GenerateReportRequest {
request: payload,
merchant_id: Some(merchant_id.clone()),
auth: AuthInfo::MerchantLevel {
org_id: org_id.clone(),
merchant_ids: vec![merchant_id.clone()],
},
email: user_email,
};
let json_bytes =
serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?;
invoke_lambda(
&state.conf.report_download_config.authentication_function,
&state.conf.report_download_config.region,
&json_bytes,
)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::MerchantReportRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
pub async fn generate_org_authentication_report(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<ReportRequest>,
) -> impl Responder {
let flow = AnalyticsFlow::GenerateAuthenticationReport;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
json_payload.into_inner(),
|state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move {
let user = UserInterface::find_user_by_id(&*state.global_store, &user_id)
.await
.change_context(AnalyticsError::UnknownError)?;
let user_email = UserEmail::from_pii_email(user.email)
.change_context(AnalyticsError::UnknownError)?
.get_secret();
let org_id = auth.merchant_account.get_org_id();
let lambda_req = GenerateReportRequest {
request: payload,
merchant_id: None,
auth: AuthInfo::OrgLevel {
org_id: org_id.clone(),
},
email: user_email,
};
let json_bytes =
serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?;
invoke_lambda(
&state.conf.report_download_config.authentication_function,
&state.conf.report_download_config.region,
&json_bytes,
)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::OrganizationReportRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
pub async fn generate_profile_authentication_report(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<ReportRequest>,
) -> impl Responder {
let flow = AnalyticsFlow::GenerateAuthenticationReport;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
json_payload.into_inner(),
|state, (auth, user_id): auth::AuthenticationDataWithUserId, payload, _| async move {
let user = UserInterface::find_user_by_id(&*state.global_store, &user_id)
.await
.change_context(AnalyticsError::UnknownError)?;
let user_email = UserEmail::from_pii_email(user.email)
.change_context(AnalyticsError::UnknownError)?
.get_secret();
let org_id = auth.merchant_account.get_org_id();
let merchant_id = auth.merchant_account.get_id();
let profile_id = auth
.profile_id
.ok_or(report!(UserErrors::JwtProfileIdMissing))
.change_context(AnalyticsError::AccessForbiddenError)?;
let lambda_req = GenerateReportRequest {
request: payload,
merchant_id: Some(merchant_id.clone()),
auth: AuthInfo::ProfileLevel {
org_id: org_id.clone(),
merchant_id: merchant_id.clone(),
profile_ids: vec![profile_id.clone()],
},
email: user_email,
};
let json_bytes =
serde_json::to_vec(&lambda_req).map_err(|_| AnalyticsError::UnknownError)?;
invoke_lambda(
&state.conf.report_download_config.authentication_function,
&state.conf.report_download_config.region,
&json_bytes,
)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::ProfileReportRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
/// # Panics
///
/// Panics if `json_payload` array does not contain one `GetApiEventMetricRequest` element.
pub async fn get_merchant_api_events_metrics(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<[GetApiEventMetricRequest; 1]>,
) -> impl Responder {
// safety: This shouldn't panic owing to the data type
#[allow(clippy::expect_used)]
let payload = json_payload
.into_inner()
.to_vec()
.pop()
.expect("Couldn't get GetApiEventMetricRequest");
let flow = AnalyticsFlow::GetApiEventMetrics;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
payload,
|state, auth: AuthenticationData, req, _| async move {
analytics::api_event::get_api_event_metrics(
&state.pool,
auth.merchant_account.get_id(),
req,
)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn get_merchant_api_event_filters(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<GetApiEventFiltersRequest>,
) -> impl Responder {
let flow = AnalyticsFlow::GetApiEventFilters;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
json_payload.into_inner(),
|state, auth: AuthenticationData, req, _| async move {
analytics::api_event::get_filters(&state.pool, req, auth.merchant_account.get_id())
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn get_profile_connector_events(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Query<api_models::analytics::connector_events::ConnectorEventsRequest>,
) -> impl Responder {
let flow = AnalyticsFlow::GetConnectorEvents;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: AuthenticationData, req, _| async move {
utils::check_if_profile_id_is_present_in_payment_intent(
req.payment_id.clone(),
&state,
&auth,
)
.await
.change_context(AnalyticsError::AccessForbiddenError)?;
connector_events_core(&state.pool, req, auth.merchant_account.get_id())
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn get_global_search_results(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<GetGlobalSearchRequest>,
) -> impl Responder {
let flow = AnalyticsFlow::GetGlobalSearchResults;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
json_payload.into_inner(),
|state, auth: UserFromToken, req, _| async move {
let role_id = auth.role_id;
let role_info = RoleInfo::from_role_id_org_id_tenant_id(
&state,
&role_id,
&auth.org_id,
auth.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id),
)
.await
.change_context(UserErrors::InternalServerError)
.change_context(OpenSearchError::UnknownError)?;
let permission_groups = role_info.get_permission_groups();
if !permission_groups.contains(&common_enums::PermissionGroup::OperationsView) {
return Err(OpenSearchError::AccessForbiddenError)?;
}
let user_roles: HashSet<UserRole> = match role_info.get_entity_type() {
EntityType::Tenant => state
.global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id: &auth.user_id,
tenant_id: auth.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id),
org_id: None,
merchant_id: None,
profile_id: None,
entity_id: None,
version: None,
status: None,
limit: None,
})
.await
.change_context(UserErrors::InternalServerError)
.change_context(OpenSearchError::UnknownError)?
.into_iter()
.collect(),
EntityType::Organization | EntityType::Merchant | EntityType::Profile => state
.global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id: &auth.user_id,
tenant_id: auth.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id),
org_id: Some(&auth.org_id),
merchant_id: None,
profile_id: None,
entity_id: None,
version: None,
status: None,
limit: None,
})
.await
.change_context(UserErrors::InternalServerError)
.change_context(OpenSearchError::UnknownError)?
.into_iter()
.collect(),
};
let state = Arc::new(state);
let role_info_map: HashMap<String, RoleInfo> = user_roles
.iter()
.map(|user_role| {
let state = Arc::clone(&state);
let role_id = user_role.role_id.clone();
let org_id = user_role.org_id.clone().unwrap_or_default();
let tenant_id = &user_role.tenant_id;
async move {
RoleInfo::from_role_id_org_id_tenant_id(
&state, &role_id, &org_id, tenant_id,
)
.await
.change_context(UserErrors::InternalServerError)
.change_context(OpenSearchError::UnknownError)
.map(|role_info| (role_id, role_info))
}
})
.collect::<FuturesUnordered<_>>()
.collect::<Vec<_>>()
.await
.into_iter()
.collect::<Result<HashMap<_, _>, _>>()?;
let filtered_user_roles: Vec<&UserRole> = user_roles
.iter()
.filter(|user_role| {
let user_role_id = &user_role.role_id;
if let Some(role_info) = role_info_map.get(user_role_id) {
let permissions = role_info.get_permission_groups();
permissions.contains(&common_enums::PermissionGroup::OperationsView)
} else {
false
}
})
.collect();
let search_params: Vec<AuthInfo> = filtered_user_roles
.iter()
.filter_map(|user_role| {
user_role
.get_entity_id_and_type()
.and_then(|(_, entity_type)| match entity_type {
EntityType::Profile => Some(AuthInfo::ProfileLevel {
org_id: user_role.org_id.clone()?,
merchant_id: user_role.merchant_id.clone()?,
profile_ids: vec![user_role.profile_id.clone()?],
}),
EntityType::Merchant => Some(AuthInfo::MerchantLevel {
org_id: user_role.org_id.clone()?,
merchant_ids: vec![user_role.merchant_id.clone()?],
}),
EntityType::Organization => Some(AuthInfo::OrgLevel {
org_id: user_role.org_id.clone()?,
}),
EntityType::Tenant => Some(AuthInfo::OrgLevel {
org_id: auth.org_id.clone(),
}),
})
})
.collect();
analytics::search::msearch_results(
state
.opensearch_client
.as_ref()
.ok_or_else(|| error_stack::report!(OpenSearchError::NotEnabled))?,
req,
search_params,
SEARCH_INDEXES.to_vec(),
)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn get_search_results(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<GetSearchRequest>,
index: web::Path<SearchIndex>,
) -> impl Responder {
let index = index.into_inner();
let flow = AnalyticsFlow::GetSearchResults;
let indexed_req = GetSearchRequestWithIndex {
search_req: json_payload.into_inner(),
index,
};
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
indexed_req,
|state, auth: UserFromToken, req, _| async move {
let role_id = auth.role_id;
let role_info = RoleInfo::from_role_id_org_id_tenant_id(
&state,
&role_id,
&auth.org_id,
auth.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id),
)
.await
.change_context(UserErrors::InternalServerError)
.change_context(OpenSearchError::UnknownError)?;
let permission_groups = role_info.get_permission_groups();
if !permission_groups.contains(&common_enums::PermissionGroup::OperationsView) {
return Err(OpenSearchError::AccessForbiddenError)?;
}
let user_roles: HashSet<UserRole> = match role_info.get_entity_type() {
EntityType::Tenant => state
.global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id: &auth.user_id,
tenant_id: auth.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id),
org_id: None,
merchant_id: None,
profile_id: None,
entity_id: None,
version: None,
status: None,
limit: None,
})
.await
.change_context(UserErrors::InternalServerError)
.change_context(OpenSearchError::UnknownError)?
.into_iter()
.collect(),
EntityType::Organization | EntityType::Merchant | EntityType::Profile => state
.global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id: &auth.user_id,
tenant_id: auth.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id),
org_id: Some(&auth.org_id),
merchant_id: None,
profile_id: None,
entity_id: None,
version: None,
status: None,
limit: None,
})
.await
.change_context(UserErrors::InternalServerError)
.change_context(OpenSearchError::UnknownError)?
.into_iter()
.collect(),
};
let state = Arc::new(state);
let role_info_map: HashMap<String, RoleInfo> = user_roles
.iter()
.map(|user_role| {
let state = Arc::clone(&state);
let role_id = user_role.role_id.clone();
let org_id = user_role.org_id.clone().unwrap_or_default();
let tenant_id = &user_role.tenant_id;
async move {
RoleInfo::from_role_id_org_id_tenant_id(
&state, &role_id, &org_id, tenant_id,
)
.await
.change_context(UserErrors::InternalServerError)
.change_context(OpenSearchError::UnknownError)
.map(|role_info| (role_id, role_info))
}
})
.collect::<FuturesUnordered<_>>()
.collect::<Vec<_>>()
.await
.into_iter()
.collect::<Result<HashMap<_, _>, _>>()?;
let filtered_user_roles: Vec<&UserRole> = user_roles
.iter()
.filter(|user_role| {
let user_role_id = &user_role.role_id;
if let Some(role_info) = role_info_map.get(user_role_id) {
let permissions = role_info.get_permission_groups();
permissions.contains(&common_enums::PermissionGroup::OperationsView)
} else {
false
}
})
.collect();
let search_params: Vec<AuthInfo> = filtered_user_roles
.iter()
.filter_map(|user_role| {
user_role
.get_entity_id_and_type()
.and_then(|(_, entity_type)| match entity_type {
EntityType::Profile => Some(AuthInfo::ProfileLevel {
org_id: user_role.org_id.clone()?,
merchant_id: user_role.merchant_id.clone()?,
profile_ids: vec![user_role.profile_id.clone()?],
}),
EntityType::Merchant => Some(AuthInfo::MerchantLevel {
org_id: user_role.org_id.clone()?,
merchant_ids: vec![user_role.merchant_id.clone()?],
}),
EntityType::Organization => Some(AuthInfo::OrgLevel {
org_id: user_role.org_id.clone()?,
}),
EntityType::Tenant => Some(AuthInfo::OrgLevel {
org_id: auth.org_id.clone(),
}),
})
})
.collect();
analytics::search::search_results(
state
.opensearch_client
.as_ref()
.ok_or_else(|| error_stack::report!(OpenSearchError::NotEnabled))?,
req,
search_params,
)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn get_merchant_dispute_filters(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<api_models::analytics::GetDisputeFilterRequest>,
) -> impl Responder {
let flow = AnalyticsFlow::GetDisputeFilters;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: AuthenticationData, req, _| async move {
let org_id = auth.merchant_account.get_org_id();
let merchant_id = auth.merchant_account.get_id();
let auth: AuthInfo = AuthInfo::MerchantLevel {
org_id: org_id.clone(),
merchant_ids: vec![merchant_id.clone()],
};
analytics::disputes::get_filters(&state.pool, req, &auth)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
pub async fn get_profile_dispute_filters(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<api_models::analytics::GetDisputeFilterRequest>,
) -> impl Responder {
let flow = AnalyticsFlow::GetDisputeFilters;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: AuthenticationData, req, _| async move {
let org_id = auth.merchant_account.get_org_id();
let merchant_id = auth.merchant_account.get_id();
let profile_id = auth
.profile_id
.ok_or(report!(UserErrors::JwtProfileIdMissing))
.change_context(AnalyticsError::AccessForbiddenError)?;
let auth: AuthInfo = AuthInfo::ProfileLevel {
org_id: org_id.clone(),
merchant_id: merchant_id.clone(),
profile_ids: vec![profile_id.clone()],
};
analytics::disputes::get_filters(&state.pool, req, &auth)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn get_org_dispute_filters(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<api_models::analytics::GetDisputeFilterRequest>,
) -> impl Responder {
let flow = AnalyticsFlow::GetDisputeFilters;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: AuthenticationData, req, _| async move {
let org_id = auth.merchant_account.get_org_id();
let auth: AuthInfo = AuthInfo::OrgLevel {
org_id: org_id.clone(),
};
analytics::disputes::get_filters(&state.pool, req, &auth)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::OrganizationAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
/// # Panics
///
/// Panics if `json_payload` array does not contain one `GetDisputeMetricRequest` element.
pub async fn get_merchant_dispute_metrics(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<[GetDisputeMetricRequest; 1]>,
) -> impl Responder {
// safety: This shouldn't panic owing to the data type
#[allow(clippy::expect_used)]
let payload = json_payload
.into_inner()
.to_vec()
.pop()
.expect("Couldn't get GetDisputeMetricRequest");
let flow = AnalyticsFlow::GetDisputeMetrics;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: AuthenticationData, req, _| async move {
let org_id = auth.merchant_account.get_org_id();
let merchant_id = auth.merchant_account.get_id();
let auth: AuthInfo = AuthInfo::MerchantLevel {
org_id: org_id.clone(),
merchant_ids: vec![merchant_id.clone()],
};
analytics::disputes::get_metrics(&state.pool, &auth, req)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// # Panics
///
/// Panics if `json_payload` array does not contain one `GetDisputeMetricRequest` element.
pub async fn get_profile_dispute_metrics(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<[GetDisputeMetricRequest; 1]>,
) -> impl Responder {
// safety: This shouldn't panic owing to the data type
#[allow(clippy::expect_used)]
let payload = json_payload
.into_inner()
.to_vec()
.pop()
.expect("Couldn't get GetDisputeMetricRequest");
let flow = AnalyticsFlow::GetDisputeMetrics;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: AuthenticationData, req, _| async move {
let org_id = auth.merchant_account.get_org_id();
let merchant_id = auth.merchant_account.get_id();
let profile_id = auth
.profile_id
.ok_or(report!(UserErrors::JwtProfileIdMissing))
.change_context(AnalyticsError::AccessForbiddenError)?;
let auth: AuthInfo = AuthInfo::ProfileLevel {
org_id: org_id.clone(),
merchant_id: merchant_id.clone(),
profile_ids: vec![profile_id.clone()],
};
analytics::disputes::get_metrics(&state.pool, &auth, req)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
/// # Panics
///
/// Panics if `json_payload` array does not contain one `GetDisputeMetricRequest` element.
pub async fn get_org_dispute_metrics(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<[GetDisputeMetricRequest; 1]>,
) -> impl Responder {
// safety: This shouldn't panic owing to the data type
#[allow(clippy::expect_used)]
let payload = json_payload
.into_inner()
.to_vec()
.pop()
.expect("Couldn't get GetDisputeMetricRequest");
let flow = AnalyticsFlow::GetDisputeMetrics;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: AuthenticationData, req, _| async move {
let org_id = auth.merchant_account.get_org_id();
let auth: AuthInfo = AuthInfo::OrgLevel {
org_id: org_id.clone(),
};
analytics::disputes::get_metrics(&state.pool, &auth, req)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::OrganizationAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn get_merchant_sankey(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<TimeRange>,
) -> impl Responder {
let flow = AnalyticsFlow::GetSankey;
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: AuthenticationData, req, _| async move {
let org_id = auth.merchant_account.get_org_id();
let merchant_id = auth.merchant_account.get_id();
let auth: AuthInfo = AuthInfo::MerchantLevel {
org_id: org_id.clone(),
merchant_ids: vec![merchant_id.clone()],
};
analytics::payment_intents::get_sankey(&state.pool, &auth, req)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn get_org_sankey(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<TimeRange>,
) -> impl Responder {
let flow = AnalyticsFlow::GetSankey;
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: AuthenticationData, req, _| async move {
let org_id = auth.merchant_account.get_org_id();
let auth: AuthInfo = AuthInfo::OrgLevel {
org_id: org_id.clone(),
};
analytics::payment_intents::get_sankey(&state.pool, &auth, req)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::OrganizationAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
pub async fn get_profile_sankey(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<TimeRange>,
) -> impl Responder {
let flow = AnalyticsFlow::GetSankey;
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state: crate::routes::SessionState, auth: AuthenticationData, req, _| async move {
let org_id = auth.merchant_account.get_org_id();
let merchant_id = auth.merchant_account.get_id();
let profile_id = auth
.profile_id
.ok_or(report!(UserErrors::JwtProfileIdMissing))
.change_context(AnalyticsError::AccessForbiddenError)?;
let auth: AuthInfo = AuthInfo::ProfileLevel {
org_id: org_id.clone(),
merchant_id: merchant_id.clone(),
profile_ids: vec![profile_id.clone()],
};
analytics::payment_intents::get_sankey(&state.pool, &auth, req)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
}
| 20,342 | 1,209 |
hyperswitch | crates/router/src/workflows.rs | .rs | #[cfg(feature = "email")]
pub mod api_key_expiry;
#[cfg(feature = "payouts")]
pub mod attach_payout_account_workflow;
pub mod outgoing_webhook_retry;
pub mod payment_method_status_update;
pub mod payment_sync;
pub mod refund_router;
pub mod tokenized_data;
pub mod revenue_recovery;
| 65 | 1,210 |
hyperswitch | crates/router/src/cors.rs | .rs | // use actix_web::http::header;
use crate::configs::settings;
pub fn cors(config: settings::CorsSettings) -> actix_cors::Cors {
let allowed_methods = config.allowed_methods.iter().map(|s| s.as_str());
let mut cors = actix_cors::Cors::default()
.allowed_methods(allowed_methods)
.allow_any_header()
.expose_any_header()
.max_age(config.max_age);
if config.wildcard_origin {
cors = cors.allow_any_origin()
} else {
for origin in &config.origins {
cors = cors.allowed_origin(origin);
}
// Only allow this in case if it's not wildcard origins. ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
cors = cors.supports_credentials();
}
cors
}
| 185 | 1,211 |
hyperswitch | crates/router/src/consts.rs | .rs | pub mod opensearch;
#[cfg(feature = "olap")]
pub mod user;
pub mod user_role;
use std::collections::HashSet;
use common_utils::consts;
pub use hyperswitch_domain_models::consts::{
CONNECTOR_MANDATE_REQUEST_REFERENCE_ID_LENGTH, ROUTING_ENABLED_PAYMENT_METHODS,
ROUTING_ENABLED_PAYMENT_METHOD_TYPES,
};
pub use hyperswitch_interfaces::consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE};
// ID generation
pub(crate) const ID_LENGTH: usize = 20;
pub(crate) const MAX_ID_LENGTH: usize = 64;
#[rustfmt::skip]
pub(crate) const ALPHABETS: [char; 62] = [
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
];
/// API client request timeout (in seconds)
pub const REQUEST_TIME_OUT: u64 = 30;
pub const REQUEST_TIMEOUT_ERROR_CODE: &str = "TIMEOUT";
pub const REQUEST_TIMEOUT_ERROR_MESSAGE: &str = "Connector did not respond in specified time";
pub const REQUEST_TIMEOUT_PAYMENT_NOT_FOUND: &str = "Timed out ,payment not found";
pub const REQUEST_TIMEOUT_ERROR_MESSAGE_FROM_PSYNC: &str =
"This Payment has been moved to failed as there is no response from the connector";
///Payment intent fulfillment default timeout (in seconds)
pub const DEFAULT_FULFILLMENT_TIME: i64 = 15 * 60;
/// Payment intent default client secret expiry (in seconds)
pub const DEFAULT_SESSION_EXPIRY: i64 = 15 * 60;
/// The length of a merchant fingerprint secret
pub const FINGERPRINT_SECRET_LENGTH: usize = 64;
pub const DEFAULT_LIST_API_LIMIT: u16 = 10;
// String literals
pub(crate) const UNSUPPORTED_ERROR_MESSAGE: &str = "Unsupported response type";
// General purpose base64 engines
pub(crate) const BASE64_ENGINE: base64::engine::GeneralPurpose = consts::BASE64_ENGINE;
pub(crate) const API_KEY_LENGTH: usize = 64;
// OID (Object Identifier) for the merchant ID field extension.
pub(crate) const MERCHANT_ID_FIELD_EXTENSION_ID: &str = "1.2.840.113635.100.6.32";
pub(crate) const METRICS_HOST_TAG_NAME: &str = "host";
pub const MAX_ROUTING_CONFIGS_PER_MERCHANT: usize = 100;
pub const ROUTING_CONFIG_ID_LENGTH: usize = 10;
pub const LOCKER_REDIS_PREFIX: &str = "LOCKER_PM_TOKEN";
pub const LOCKER_REDIS_EXPIRY_SECONDS: u32 = 60 * 15; // 15 minutes
pub const JWT_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24 * 2; // 2 days
// This should be one day, but it is causing issue while checking token in blacklist.
// TODO: This should be fixed in future.
pub const SINGLE_PURPOSE_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24 * 2; // 2 days
pub const JWT_TOKEN_COOKIE_NAME: &str = "login_token";
pub const USER_BLACKLIST_PREFIX: &str = "BU_";
pub const ROLE_BLACKLIST_PREFIX: &str = "BR_";
#[cfg(feature = "email")]
pub const EMAIL_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24; // 1 day
#[cfg(feature = "email")]
pub const EMAIL_TOKEN_BLACKLIST_PREFIX: &str = "BET_";
pub const EMAIL_SUBJECT_API_KEY_EXPIRY: &str = "API Key Expiry Notice";
pub const EMAIL_SUBJECT_DASHBOARD_FEATURE_REQUEST: &str = "Dashboard Pro Feature Request by";
pub const EMAIL_SUBJECT_APPROVAL_RECON_REQUEST: &str =
"Approval of Recon Request - Access Granted to Recon Dashboard";
pub const ROLE_INFO_CACHE_PREFIX: &str = "CR_INFO_";
pub const CARD_IP_BLOCKING_CACHE_KEY_PREFIX: &str = "CARD_IP_BLOCKING";
pub const GUEST_USER_CARD_BLOCKING_CACHE_KEY_PREFIX: &str = "GUEST_USER_CARD_BLOCKING";
pub const CUSTOMER_ID_BLOCKING_PREFIX: &str = "CUSTOMER_ID_BLOCKING";
#[cfg(feature = "olap")]
pub const VERIFY_CONNECTOR_ID_PREFIX: &str = "conn_verify";
#[cfg(feature = "olap")]
pub const VERIFY_CONNECTOR_MERCHANT_ID: &str = "test_merchant";
#[cfg(feature = "olap")]
pub const CONNECTOR_ONBOARDING_CONFIG_PREFIX: &str = "onboarding";
/// Max payment session expiry
pub const MAX_SESSION_EXPIRY: u32 = 7890000;
/// Min payment session expiry
pub const MIN_SESSION_EXPIRY: u32 = 60;
/// Max payment intent fulfillment expiry
pub const MAX_INTENT_FULFILLMENT_EXPIRY: u32 = 1800;
/// Min payment intent fulfillment expiry
pub const MIN_INTENT_FULFILLMENT_EXPIRY: u32 = 60;
pub const LOCKER_HEALTH_CALL_PATH: &str = "/health";
pub const AUTHENTICATION_ID_PREFIX: &str = "authn";
// URL for checking the outgoing call
pub const OUTGOING_CALL_URL: &str = "https://api.stripe.com/healthcheck";
// 15 minutes = 900 seconds
pub const POLL_ID_TTL: i64 = 900;
// Default Poll Config
pub const DEFAULT_POLL_DELAY_IN_SECS: i8 = 2;
pub const DEFAULT_POLL_FREQUENCY: i8 = 5;
// Number of seconds to subtract from access token expiry
pub(crate) const REDUCE_ACCESS_TOKEN_EXPIRY_TIME: u8 = 15;
pub const CONNECTOR_CREDS_TOKEN_TTL: i64 = 900;
//max_amount allowed is 999999999 in minor units
pub const MAX_ALLOWED_AMOUNT: i64 = 999999999;
//payment attempt default unified error code and unified error message
pub const DEFAULT_UNIFIED_ERROR_CODE: &str = "UE_9000";
pub const DEFAULT_UNIFIED_ERROR_MESSAGE: &str = "Something went wrong";
// Recon's feature tag
pub const RECON_FEATURE_TAG: &str = "RECONCILIATION AND SETTLEMENT";
/// Default allowed domains for payment links
pub const DEFAULT_ALLOWED_DOMAINS: Option<HashSet<String>> = None;
/// Default hide card nickname field
pub const DEFAULT_HIDE_CARD_NICKNAME_FIELD: bool = false;
/// Show card form by default for payment links
pub const DEFAULT_SHOW_CARD_FORM: bool = true;
/// Default bool for Display sdk only
pub const DEFAULT_DISPLAY_SDK_ONLY: bool = false;
/// Default bool to enable saved payment method
pub const DEFAULT_ENABLE_SAVED_PAYMENT_METHOD: bool = false;
/// [PaymentLink] Default bool for enabling button only when form is ready
pub const DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY: bool = false;
/// Default Merchant Logo Link
pub const DEFAULT_MERCHANT_LOGO: &str =
"https://live.hyperswitch.io/payment-link-assets/Merchant_placeholder.png";
/// Default Payment Link Background color
pub const DEFAULT_BACKGROUND_COLOR: &str = "#212E46";
/// Default product Img Link
pub const DEFAULT_PRODUCT_IMG: &str =
"https://live.hyperswitch.io/payment-link-assets/cart_placeholder.png";
/// Default SDK Layout
pub const DEFAULT_SDK_LAYOUT: &str = "tabs";
/// Vault Add request url
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
pub const ADD_VAULT_REQUEST_URL: &str = "/api/v2/vault/add";
/// Vault Get Fingerprint request url
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
pub const VAULT_FINGERPRINT_REQUEST_URL: &str = "/api/v2/vault/fingerprint";
/// Vault Retrieve request url
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
pub const VAULT_RETRIEVE_REQUEST_URL: &str = "/api/v2/vault/retrieve";
/// Vault Delete request url
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
pub const VAULT_DELETE_REQUEST_URL: &str = "/api/v2/vault/delete";
/// Vault Header content type
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
pub const VAULT_HEADER_CONTENT_TYPE: &str = "application/json";
/// Vault Add flow type
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
pub const VAULT_ADD_FLOW_TYPE: &str = "add_to_vault";
/// Vault Retrieve flow type
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
pub const VAULT_RETRIEVE_FLOW_TYPE: &str = "retrieve_from_vault";
/// Vault Delete flow type
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
pub const VAULT_DELETE_FLOW_TYPE: &str = "delete_from_vault";
/// Vault Fingerprint fetch flow type
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
pub const VAULT_GET_FINGERPRINT_FLOW_TYPE: &str = "get_fingerprint_vault";
/// Max volume split for Dynamic routing
pub const DYNAMIC_ROUTING_MAX_VOLUME: u8 = 100;
/// Click To Pay
pub const CLICK_TO_PAY: &str = "click_to_pay";
/// Merchant eligible for authentication service config
pub const AUTHENTICATION_SERVICE_ELIGIBLE_CONFIG: &str =
"merchants_eligible_for_authentication_service";
/// Refund flow identifier used for performing GSM operations
pub const REFUND_FLOW_STR: &str = "refund_flow";
/// Default payment method session expiry
pub const DEFAULT_PAYMENT_METHOD_SESSION_EXPIRY: u32 = 15 * 60; // 15 minutes
/// Authorize flow identifier used for performing GSM operations
pub const AUTHORIZE_FLOW_STR: &str = "Authorize";
/// Protocol Version for encrypted Google Pay Token
pub(crate) const PROTOCOL: &str = "ECv2";
/// Sender ID for Google Pay Decryption
pub(crate) const SENDER_ID: &[u8] = b"Google";
/// Default value for the number of attempts to retry fetching forex rates
pub const DEFAULT_ANALYTICS_FOREX_RETRY_ATTEMPTS: u64 = 3;
/// Default payment intent id
pub const IRRELEVANT_PAYMENT_INTENT_ID: &str = "irrelevant_payment_intent_id";
/// Default payment attempt id
pub const IRRELEVANT_PAYMENT_ATTEMPT_ID: &str = "irrelevant_payment_attempt_id";
// Default payment method storing TTL in redis in seconds
pub const DEFAULT_PAYMENT_METHOD_STORE_TTL: i64 = 86400; // 1 day
| 2,524 | 1,212 |
hyperswitch | crates/router/src/types.rs | .rs | // FIXME: Why were these data types grouped this way?
//
// Folder `types` is strange for Rust ecosystem, nevertheless it might be okay.
// But folder `enum` is even more strange I unlikely okay. Why should not we introduce folders `type`, `structs` and `traits`? :)
// Is it better to split data types according to business logic instead.
// For example, customers/address/dispute/mandate is "models".
// Separation of concerns instead of separation of forms.
pub mod api;
pub mod authentication;
pub mod domain;
#[cfg(feature = "frm")]
pub mod fraud_check;
pub mod payment_methods;
pub mod pm_auth;
use masking::Secret;
pub mod storage;
pub mod transformers;
use std::marker::PhantomData;
pub use api_models::{enums::Connector, mandates};
#[cfg(feature = "payouts")]
pub use api_models::{enums::PayoutConnectors, payouts as payout_types};
#[cfg(feature = "v2")]
use common_utils::errors::CustomResult;
pub use common_utils::{pii, pii::Email, request::RequestContent, types::MinorUnit};
#[cfg(feature = "v2")]
use error_stack::ResultExt;
#[cfg(feature = "frm")]
pub use hyperswitch_domain_models::router_data_v2::FrmFlowData;
use hyperswitch_domain_models::router_flow_types::{
self,
access_token_auth::AccessTokenAuth,
dispute::{Accept, Defend, Evidence},
files::{Retrieve, Upload},
mandate_revoke::MandateRevoke,
payments::{
Approve, Authorize, AuthorizeSessionToken, Balance, CalculateTax, Capture,
CompleteAuthorize, CreateConnectorCustomer, IncrementalAuthorization, InitPayment, PSync,
PostProcessing, PostSessionTokens, PreProcessing, Reject, SdkSessionUpdate, Session,
SetupMandate, Void,
},
refunds::{Execute, RSync},
webhooks::VerifyWebhookSource,
};
pub use hyperswitch_domain_models::{
payment_address::PaymentAddress,
router_data::{
AccessToken, AdditionalPaymentMethodConnectorResponse, ApplePayCryptogramData,
ApplePayPredecryptData, ConnectorAuthType, ConnectorResponseData, ErrorResponse,
GooglePayDecryptedData, GooglePayPaymentMethodDetails, PaymentMethodBalance,
PaymentMethodToken, RecurringMandatePaymentData, RouterData,
},
router_data_v2::{
AccessTokenFlowData, DisputesFlowData, ExternalAuthenticationFlowData, FilesFlowData,
MandateRevokeFlowData, PaymentFlowData, RefundFlowData, RouterDataV2, UasFlowData,
WebhookSourceVerifyData,
},
router_request_types::{
revenue_recovery::{BillingConnectorPaymentsSyncRequest, RevenueRecoveryRecordBackRequest},
unified_authentication_service::{
UasAuthenticationRequestData, UasAuthenticationResponseData,
UasConfirmationRequestData, UasPostAuthenticationRequestData,
UasPreAuthenticationRequestData,
},
AcceptDisputeRequestData, AccessTokenRequestData, AuthorizeSessionTokenData,
BrowserInformation, ChargeRefunds, ChargeRefundsOptions, CompleteAuthorizeData,
CompleteAuthorizeRedirectResponse, ConnectorCustomerData, DefendDisputeRequestData,
DestinationChargeRefund, DirectChargeRefund, MandateRevokeRequestData,
MultipleCaptureRequestData, PaymentMethodTokenizationData, PaymentsApproveData,
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData,
PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData,
PaymentsPostSessionTokensData, PaymentsPreProcessingData, PaymentsRejectData,
PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, RefundsData, ResponseId,
RetrieveFileRequestData, SdkPaymentsSessionUpdateData, SetupMandateRequestData,
SplitRefundsRequest, SubmitEvidenceRequestData, SyncRequestType, UploadFileRequestData,
VerifyWebhookSourceRequestData,
},
router_response_types::{
revenue_recovery::{
BillingConnectorPaymentsSyncResponse, RevenueRecoveryRecordBackResponse,
},
AcceptDisputeResponse, CaptureSyncResponse, DefendDisputeResponse, MandateReference,
MandateRevokeResponseData, PaymentsResponseData, PreprocessingResponseId,
RefundsResponseData, RetrieveFileResponse, SubmitEvidenceResponse,
TaxCalculationResponseData, UploadFileResponse, VerifyWebhookSourceResponseData,
VerifyWebhookStatus,
},
};
#[cfg(feature = "payouts")]
pub use hyperswitch_domain_models::{
router_data_v2::PayoutFlowData, router_request_types::PayoutsData,
router_response_types::PayoutsResponseData,
};
pub use hyperswitch_interfaces::types::{
AcceptDisputeType, ConnectorCustomerType, DefendDisputeType, IncrementalAuthorizationType,
MandateRevokeType, PaymentsAuthorizeType, PaymentsBalanceType, PaymentsCaptureType,
PaymentsCompleteAuthorizeType, PaymentsInitType, PaymentsPostProcessingType,
PaymentsPostSessionTokensType, PaymentsPreAuthorizeType, PaymentsPreProcessingType,
PaymentsSessionType, PaymentsSyncType, PaymentsVoidType, RefreshTokenType, RefundExecuteType,
RefundSyncType, Response, RetrieveFileType, SdkSessionUpdateType, SetupMandateType,
SubmitEvidenceType, TokenizationType, UploadFileType, VerifyWebhookSourceType,
};
#[cfg(feature = "payouts")]
pub use hyperswitch_interfaces::types::{
PayoutCancelType, PayoutCreateType, PayoutEligibilityType, PayoutFulfillType, PayoutQuoteType,
PayoutRecipientAccountType, PayoutRecipientType, PayoutSyncType,
};
pub use crate::core::payments::CustomerDetails;
#[cfg(feature = "payouts")]
use crate::{
connector::utils::missing_field_err,
core::utils::IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_PAYOUTS_FLOW,
};
use crate::{
consts,
core::{
errors::{self},
payments::{OperationSessionGetters, PaymentData},
},
services,
types::transformers::{ForeignFrom, ForeignTryFrom},
};
pub type PaymentsAuthorizeRouterData =
RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>;
pub type PaymentsPreProcessingRouterData =
RouterData<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>;
pub type PaymentsPostProcessingRouterData =
RouterData<PostProcessing, PaymentsPostProcessingData, PaymentsResponseData>;
pub type PaymentsAuthorizeSessionTokenRouterData =
RouterData<AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData>;
pub type PaymentsCompleteAuthorizeRouterData =
RouterData<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>;
pub type PaymentsInitRouterData =
RouterData<InitPayment, PaymentsAuthorizeData, PaymentsResponseData>;
pub type PaymentsBalanceRouterData =
RouterData<Balance, PaymentsAuthorizeData, PaymentsResponseData>;
pub type PaymentsSyncRouterData = RouterData<PSync, PaymentsSyncData, PaymentsResponseData>;
pub type PaymentsCaptureRouterData = RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>;
pub type PaymentsIncrementalAuthorizationRouterData = RouterData<
IncrementalAuthorization,
PaymentsIncrementalAuthorizationData,
PaymentsResponseData,
>;
pub type PaymentsTaxCalculationRouterData =
RouterData<CalculateTax, PaymentsTaxCalculationData, TaxCalculationResponseData>;
pub type SdkSessionUpdateRouterData =
RouterData<SdkSessionUpdate, SdkPaymentsSessionUpdateData, PaymentsResponseData>;
pub type PaymentsPostSessionTokensRouterData =
RouterData<PostSessionTokens, PaymentsPostSessionTokensData, PaymentsResponseData>;
pub type PaymentsCancelRouterData = RouterData<Void, PaymentsCancelData, PaymentsResponseData>;
pub type PaymentsRejectRouterData = RouterData<Reject, PaymentsRejectData, PaymentsResponseData>;
pub type PaymentsApproveRouterData = RouterData<Approve, PaymentsApproveData, PaymentsResponseData>;
pub type PaymentsSessionRouterData = RouterData<Session, PaymentsSessionData, PaymentsResponseData>;
pub type RefundsRouterData<F> = RouterData<F, RefundsData, RefundsResponseData>;
pub type RefundExecuteRouterData = RouterData<Execute, RefundsData, RefundsResponseData>;
pub type RefundSyncRouterData = RouterData<RSync, RefundsData, RefundsResponseData>;
pub type TokenizationRouterData = RouterData<
router_flow_types::PaymentMethodToken,
PaymentMethodTokenizationData,
PaymentsResponseData,
>;
pub type ConnectorCustomerRouterData =
RouterData<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>;
pub type RefreshTokenRouterData = RouterData<AccessTokenAuth, AccessTokenRequestData, AccessToken>;
pub type PaymentsResponseRouterData<R> =
ResponseRouterData<Authorize, R, PaymentsAuthorizeData, PaymentsResponseData>;
pub type PaymentsCancelResponseRouterData<R> =
ResponseRouterData<Void, R, PaymentsCancelData, PaymentsResponseData>;
pub type PaymentsBalanceResponseRouterData<R> =
ResponseRouterData<Balance, R, PaymentsAuthorizeData, PaymentsResponseData>;
pub type PaymentsSyncResponseRouterData<R> =
ResponseRouterData<PSync, R, PaymentsSyncData, PaymentsResponseData>;
pub type PaymentsSessionResponseRouterData<R> =
ResponseRouterData<Session, R, PaymentsSessionData, PaymentsResponseData>;
pub type PaymentsInitResponseRouterData<R> =
ResponseRouterData<InitPayment, R, PaymentsAuthorizeData, PaymentsResponseData>;
pub type SdkSessionUpdateResponseRouterData<R> =
ResponseRouterData<SdkSessionUpdate, R, SdkPaymentsSessionUpdateData, PaymentsResponseData>;
pub type PaymentsCaptureResponseRouterData<R> =
ResponseRouterData<Capture, R, PaymentsCaptureData, PaymentsResponseData>;
pub type PaymentsPreprocessingResponseRouterData<R> =
ResponseRouterData<PreProcessing, R, PaymentsPreProcessingData, PaymentsResponseData>;
pub type TokenizationResponseRouterData<R> =
ResponseRouterData<PaymentMethodToken, R, PaymentMethodTokenizationData, PaymentsResponseData>;
pub type ConnectorCustomerResponseRouterData<R> =
ResponseRouterData<CreateConnectorCustomer, R, ConnectorCustomerData, PaymentsResponseData>;
pub type RefundsResponseRouterData<F, R> =
ResponseRouterData<F, R, RefundsData, RefundsResponseData>;
pub type SetupMandateRouterData =
RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>;
pub type AcceptDisputeRouterData =
RouterData<Accept, AcceptDisputeRequestData, AcceptDisputeResponse>;
pub type VerifyWebhookSourceRouterData = RouterData<
VerifyWebhookSource,
VerifyWebhookSourceRequestData,
VerifyWebhookSourceResponseData,
>;
pub type SubmitEvidenceRouterData =
RouterData<Evidence, SubmitEvidenceRequestData, SubmitEvidenceResponse>;
pub type UploadFileRouterData = RouterData<Upload, UploadFileRequestData, UploadFileResponse>;
pub type RetrieveFileRouterData =
RouterData<Retrieve, RetrieveFileRequestData, RetrieveFileResponse>;
pub type DefendDisputeRouterData =
RouterData<Defend, DefendDisputeRequestData, DefendDisputeResponse>;
pub type MandateRevokeRouterData =
RouterData<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData>;
#[cfg(feature = "payouts")]
pub type PayoutsRouterData<F> = RouterData<F, PayoutsData, PayoutsResponseData>;
#[cfg(feature = "payouts")]
pub type PayoutsResponseRouterData<F, R> =
ResponseRouterData<F, R, PayoutsData, PayoutsResponseData>;
#[cfg(feature = "payouts")]
pub type PayoutActionData = Vec<(
storage::Payouts,
storage::PayoutAttempt,
Option<domain::Customer>,
Option<api_models::payments::Address>,
)>;
#[cfg(feature = "payouts")]
pub trait PayoutIndividualDetailsExt {
type Error;
fn get_external_account_account_holder_type(&self) -> Result<String, Self::Error>;
}
#[cfg(feature = "payouts")]
impl PayoutIndividualDetailsExt for api_models::payouts::PayoutIndividualDetails {
type Error = error_stack::Report<errors::ConnectorError>;
fn get_external_account_account_holder_type(&self) -> Result<String, Self::Error> {
self.external_account_account_holder_type
.clone()
.ok_or_else(missing_field_err("external_account_account_holder_type"))
}
}
pub trait Capturable {
fn get_captured_amount<F>(&self, _payment_data: &PaymentData<F>) -> Option<i64>
where
F: Clone,
{
None
}
fn get_amount_capturable<F>(
&self,
_payment_data: &PaymentData<F>,
_attempt_status: common_enums::AttemptStatus,
) -> Option<i64>
where
F: Clone,
{
None
}
}
#[cfg(feature = "v1")]
impl Capturable for PaymentsAuthorizeData {
fn get_captured_amount<F>(&self, payment_data: &PaymentData<F>) -> Option<i64>
where
F: Clone,
{
Some(
payment_data
.payment_attempt
.get_total_amount()
.get_amount_as_i64(),
)
}
fn get_amount_capturable<F>(
&self,
payment_data: &PaymentData<F>,
attempt_status: common_enums::AttemptStatus,
) -> Option<i64>
where
F: Clone,
{
match payment_data.get_capture_method().unwrap_or_default()
{
common_enums::CaptureMethod::Automatic|common_enums::CaptureMethod::SequentialAutomatic => {
let intent_status = common_enums::IntentStatus::foreign_from(attempt_status);
match intent_status {
common_enums::IntentStatus::Succeeded
| common_enums::IntentStatus::Failed
| common_enums::IntentStatus::Processing => Some(0),
common_enums::IntentStatus::Cancelled
| common_enums::IntentStatus::PartiallyCaptured
| common_enums::IntentStatus::RequiresCustomerAction
| common_enums::IntentStatus::RequiresMerchantAction
| common_enums::IntentStatus::RequiresPaymentMethod
| common_enums::IntentStatus::RequiresConfirmation
| common_enums::IntentStatus::RequiresCapture
| common_enums::IntentStatus::PartiallyCapturedAndCapturable => None,
}
},
common_enums::CaptureMethod::Manual => Some(payment_data.payment_attempt.get_total_amount().get_amount_as_i64()),
// In case of manual multiple, amount capturable must be inferred from all captures.
common_enums::CaptureMethod::ManualMultiple |
// Scheduled capture is not supported as of now
common_enums::CaptureMethod::Scheduled => None,
}
}
}
#[cfg(feature = "v1")]
impl Capturable for PaymentsCaptureData {
fn get_captured_amount<F>(&self, _payment_data: &PaymentData<F>) -> Option<i64>
where
F: Clone,
{
Some(self.amount_to_capture)
}
fn get_amount_capturable<F>(
&self,
_payment_data: &PaymentData<F>,
attempt_status: common_enums::AttemptStatus,
) -> Option<i64>
where
F: Clone,
{
let intent_status = common_enums::IntentStatus::foreign_from(attempt_status);
match intent_status {
common_enums::IntentStatus::Succeeded
| common_enums::IntentStatus::PartiallyCaptured => Some(0),
common_enums::IntentStatus::Processing
| common_enums::IntentStatus::Cancelled
| common_enums::IntentStatus::Failed
| common_enums::IntentStatus::RequiresCustomerAction
| common_enums::IntentStatus::RequiresMerchantAction
| common_enums::IntentStatus::RequiresPaymentMethod
| common_enums::IntentStatus::RequiresConfirmation
| common_enums::IntentStatus::RequiresCapture
| common_enums::IntentStatus::PartiallyCapturedAndCapturable => None,
}
}
}
#[cfg(feature = "v1")]
impl Capturable for CompleteAuthorizeData {
fn get_captured_amount<F>(&self, payment_data: &PaymentData<F>) -> Option<i64>
where
F: Clone,
{
Some(
payment_data
.payment_attempt
.get_total_amount()
.get_amount_as_i64(),
)
}
fn get_amount_capturable<F>(
&self,
payment_data: &PaymentData<F>,
attempt_status: common_enums::AttemptStatus,
) -> Option<i64>
where
F: Clone,
{
match payment_data
.get_capture_method()
.unwrap_or_default()
{
common_enums::CaptureMethod::Automatic | common_enums::CaptureMethod::SequentialAutomatic => {
let intent_status = common_enums::IntentStatus::foreign_from(attempt_status);
match intent_status {
common_enums::IntentStatus::Succeeded|
common_enums::IntentStatus::Failed|
common_enums::IntentStatus::Processing => Some(0),
common_enums::IntentStatus::Cancelled
| common_enums::IntentStatus::PartiallyCaptured
| common_enums::IntentStatus::RequiresCustomerAction
| common_enums::IntentStatus::RequiresMerchantAction
| common_enums::IntentStatus::RequiresPaymentMethod
| common_enums::IntentStatus::RequiresConfirmation
| common_enums::IntentStatus::RequiresCapture
| common_enums::IntentStatus::PartiallyCapturedAndCapturable => None,
}
},
common_enums::CaptureMethod::Manual => Some(payment_data.payment_attempt.get_total_amount().get_amount_as_i64()),
// In case of manual multiple, amount capturable must be inferred from all captures.
common_enums::CaptureMethod::ManualMultiple |
// Scheduled capture is not supported as of now
common_enums::CaptureMethod::Scheduled => None,
}
}
}
impl Capturable for SetupMandateRequestData {}
impl Capturable for PaymentsTaxCalculationData {}
impl Capturable for SdkPaymentsSessionUpdateData {}
impl Capturable for PaymentsPostSessionTokensData {}
impl Capturable for PaymentsCancelData {
fn get_captured_amount<F>(&self, payment_data: &PaymentData<F>) -> Option<i64>
where
F: Clone,
{
// return previously captured amount
payment_data
.payment_intent
.amount_captured
.map(|amt| amt.get_amount_as_i64())
}
fn get_amount_capturable<F>(
&self,
_payment_data: &PaymentData<F>,
attempt_status: common_enums::AttemptStatus,
) -> Option<i64>
where
F: Clone,
{
let intent_status = common_enums::IntentStatus::foreign_from(attempt_status);
match intent_status {
common_enums::IntentStatus::Cancelled
| common_enums::IntentStatus::Processing
| common_enums::IntentStatus::PartiallyCaptured => Some(0),
common_enums::IntentStatus::Succeeded
| common_enums::IntentStatus::Failed
| common_enums::IntentStatus::RequiresCustomerAction
| common_enums::IntentStatus::RequiresMerchantAction
| common_enums::IntentStatus::RequiresPaymentMethod
| common_enums::IntentStatus::RequiresConfirmation
| common_enums::IntentStatus::RequiresCapture
| common_enums::IntentStatus::PartiallyCapturedAndCapturable => None,
}
}
}
impl Capturable for PaymentsApproveData {}
impl Capturable for PaymentsRejectData {}
impl Capturable for PaymentsSessionData {}
impl Capturable for PaymentsIncrementalAuthorizationData {
fn get_amount_capturable<F>(
&self,
_payment_data: &PaymentData<F>,
_attempt_status: common_enums::AttemptStatus,
) -> Option<i64>
where
F: Clone,
{
Some(self.total_amount)
}
}
impl Capturable for PaymentsSyncData {
#[cfg(feature = "v1")]
fn get_captured_amount<F>(&self, payment_data: &PaymentData<F>) -> Option<i64>
where
F: Clone,
{
payment_data
.payment_attempt
.amount_to_capture
.or_else(|| Some(payment_data.payment_attempt.get_total_amount()))
.map(|amt| amt.get_amount_as_i64())
}
#[cfg(feature = "v2")]
fn get_captured_amount<F>(&self, payment_data: &PaymentData<F>) -> Option<i64>
where
F: Clone,
{
// TODO: add a getter for this
payment_data
.payment_attempt
.amount_details
.get_amount_to_capture()
.or_else(|| Some(payment_data.payment_attempt.get_total_amount()))
.map(|amt| amt.get_amount_as_i64())
}
fn get_amount_capturable<F>(
&self,
_payment_data: &PaymentData<F>,
attempt_status: common_enums::AttemptStatus,
) -> Option<i64>
where
F: Clone,
{
if attempt_status.is_terminal_status() {
Some(0)
} else {
None
}
}
}
pub struct AddAccessTokenResult {
pub access_token_result: Result<Option<AccessToken>, ErrorResponse>,
pub connector_supports_access_token: bool,
}
pub struct PaymentMethodTokenResult {
pub payment_method_token_result: Result<Option<String>, ErrorResponse>,
pub is_payment_method_tokenization_performed: bool,
pub connector_response: Option<ConnectorResponseData>,
}
pub struct PspTokenResult {
pub token: Result<String, ErrorResponse>,
}
#[derive(Debug, Clone, Copy)]
pub enum Redirection {
Redirect,
NoRedirect,
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct PollConfig {
pub delay_in_secs: i8,
pub frequency: i8,
}
impl PollConfig {
pub fn get_poll_config_key(connector: String) -> String {
format!("poll_config_external_three_ds_{connector}")
}
}
impl Default for PollConfig {
fn default() -> Self {
Self {
delay_in_secs: consts::DEFAULT_POLL_DELAY_IN_SECS,
frequency: consts::DEFAULT_POLL_FREQUENCY,
}
}
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug)]
pub struct RedirectPaymentFlowResponse {
pub payments_response: api_models::payments::PaymentsResponse,
pub business_profile: domain::Profile,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug)]
pub struct RedirectPaymentFlowResponse<D> {
pub payment_data: D,
pub profile: domain::Profile,
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug)]
pub struct AuthenticatePaymentFlowResponse {
pub payments_response: api_models::payments::PaymentsResponse,
pub poll_config: PollConfig,
pub business_profile: domain::Profile,
}
#[derive(Debug, Clone, Default, serde::Deserialize, serde::Serialize)]
pub struct ConnectorResponse {
pub merchant_id: common_utils::id_type::MerchantId,
pub connector: String,
pub payment_id: common_utils::id_type::PaymentId,
pub amount: i64,
pub connector_transaction_id: String,
pub return_url: Option<String>,
pub three_ds_form: Option<services::RedirectForm>,
}
pub struct ResponseRouterData<Flow, R, Request, Response> {
pub response: R,
pub data: RouterData<Flow, Request, Response>,
pub http_code: u16,
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub enum RecipientIdType {
ConnectorId(Secret<String>),
LockerId(Secret<String>),
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum MerchantAccountData {
Iban {
iban: Secret<String>,
name: String,
connector_recipient_id: Option<RecipientIdType>,
},
Bacs {
account_number: Secret<String>,
sort_code: Secret<String>,
name: String,
connector_recipient_id: Option<RecipientIdType>,
},
}
impl ForeignFrom<MerchantAccountData> for api_models::admin::MerchantAccountData {
fn foreign_from(from: MerchantAccountData) -> Self {
match from {
MerchantAccountData::Iban {
iban,
name,
connector_recipient_id,
} => Self::Iban {
iban,
name,
connector_recipient_id: match connector_recipient_id {
Some(RecipientIdType::ConnectorId(id)) => Some(id.clone()),
_ => None,
},
},
MerchantAccountData::Bacs {
account_number,
sort_code,
name,
connector_recipient_id,
} => Self::Bacs {
account_number,
sort_code,
name,
connector_recipient_id: match connector_recipient_id {
Some(RecipientIdType::ConnectorId(id)) => Some(id.clone()),
_ => None,
},
},
}
}
}
impl From<api_models::admin::MerchantAccountData> for MerchantAccountData {
fn from(from: api_models::admin::MerchantAccountData) -> Self {
match from {
api_models::admin::MerchantAccountData::Iban {
iban,
name,
connector_recipient_id,
} => Self::Iban {
iban,
name,
connector_recipient_id: connector_recipient_id.map(RecipientIdType::ConnectorId),
},
api_models::admin::MerchantAccountData::Bacs {
account_number,
sort_code,
name,
connector_recipient_id,
} => Self::Bacs {
account_number,
sort_code,
name,
connector_recipient_id: connector_recipient_id.map(RecipientIdType::ConnectorId),
},
}
}
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum MerchantRecipientData {
ConnectorRecipientId(Secret<String>),
WalletId(Secret<String>),
AccountData(MerchantAccountData),
}
impl ForeignFrom<MerchantRecipientData> for api_models::admin::MerchantRecipientData {
fn foreign_from(value: MerchantRecipientData) -> Self {
match value {
MerchantRecipientData::ConnectorRecipientId(id) => Self::ConnectorRecipientId(id),
MerchantRecipientData::WalletId(id) => Self::WalletId(id),
MerchantRecipientData::AccountData(data) => {
Self::AccountData(api_models::admin::MerchantAccountData::foreign_from(data))
}
}
}
}
impl From<api_models::admin::MerchantRecipientData> for MerchantRecipientData {
fn from(value: api_models::admin::MerchantRecipientData) -> Self {
match value {
api_models::admin::MerchantRecipientData::ConnectorRecipientId(id) => {
Self::ConnectorRecipientId(id)
}
api_models::admin::MerchantRecipientData::WalletId(id) => Self::WalletId(id),
api_models::admin::MerchantRecipientData::AccountData(data) => {
Self::AccountData(data.into())
}
}
}
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum AdditionalMerchantData {
OpenBankingRecipientData(MerchantRecipientData),
}
impl ForeignFrom<api_models::admin::AdditionalMerchantData> for AdditionalMerchantData {
fn foreign_from(value: api_models::admin::AdditionalMerchantData) -> Self {
match value {
api_models::admin::AdditionalMerchantData::OpenBankingRecipientData(data) => {
Self::OpenBankingRecipientData(MerchantRecipientData::from(data))
}
}
}
}
impl ForeignFrom<AdditionalMerchantData> for api_models::admin::AdditionalMerchantData {
fn foreign_from(value: AdditionalMerchantData) -> Self {
match value {
AdditionalMerchantData::OpenBankingRecipientData(data) => {
Self::OpenBankingRecipientData(
api_models::admin::MerchantRecipientData::foreign_from(data),
)
}
}
}
}
impl ForeignFrom<api_models::admin::ConnectorAuthType> for ConnectorAuthType {
fn foreign_from(value: api_models::admin::ConnectorAuthType) -> Self {
match value {
api_models::admin::ConnectorAuthType::TemporaryAuth => Self::TemporaryAuth,
api_models::admin::ConnectorAuthType::HeaderKey { api_key } => {
Self::HeaderKey { api_key }
}
api_models::admin::ConnectorAuthType::BodyKey { api_key, key1 } => {
Self::BodyKey { api_key, key1 }
}
api_models::admin::ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Self::SignatureKey {
api_key,
key1,
api_secret,
},
api_models::admin::ConnectorAuthType::MultiAuthKey {
api_key,
key1,
api_secret,
key2,
} => Self::MultiAuthKey {
api_key,
key1,
api_secret,
key2,
},
api_models::admin::ConnectorAuthType::CurrencyAuthKey { auth_key_map } => {
Self::CurrencyAuthKey { auth_key_map }
}
api_models::admin::ConnectorAuthType::NoKey => Self::NoKey,
api_models::admin::ConnectorAuthType::CertificateAuth {
certificate,
private_key,
} => Self::CertificateAuth {
certificate,
private_key,
},
}
}
}
impl ForeignFrom<ConnectorAuthType> for api_models::admin::ConnectorAuthType {
fn foreign_from(from: ConnectorAuthType) -> Self {
match from {
ConnectorAuthType::TemporaryAuth => Self::TemporaryAuth,
ConnectorAuthType::HeaderKey { api_key } => Self::HeaderKey { api_key },
ConnectorAuthType::BodyKey { api_key, key1 } => Self::BodyKey { api_key, key1 },
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Self::SignatureKey {
api_key,
key1,
api_secret,
},
ConnectorAuthType::MultiAuthKey {
api_key,
key1,
api_secret,
key2,
} => Self::MultiAuthKey {
api_key,
key1,
api_secret,
key2,
},
ConnectorAuthType::CurrencyAuthKey { auth_key_map } => {
Self::CurrencyAuthKey { auth_key_map }
}
ConnectorAuthType::NoKey => Self::NoKey,
ConnectorAuthType::CertificateAuth {
certificate,
private_key,
} => Self::CertificateAuth {
certificate,
private_key,
},
}
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ConnectorsList {
pub connectors: Vec<String>,
}
impl ForeignTryFrom<ConnectorAuthType> for AccessTokenRequestData {
type Error = errors::ApiErrorResponse;
fn foreign_try_from(connector_auth: ConnectorAuthType) -> Result<Self, Self::Error> {
match connector_auth {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
app_id: api_key,
id: None,
}),
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
app_id: api_key,
id: Some(key1),
}),
ConnectorAuthType::SignatureKey { api_key, key1, .. } => Ok(Self {
app_id: api_key,
id: Some(key1),
}),
ConnectorAuthType::MultiAuthKey { api_key, key1, .. } => Ok(Self {
app_id: api_key,
id: Some(key1),
}),
_ => Err(errors::ApiErrorResponse::InvalidDataValue {
field_name: "connector_account_details",
}),
}
}
}
impl ForeignFrom<&PaymentsAuthorizeRouterData> for AuthorizeSessionTokenData {
fn foreign_from(data: &PaymentsAuthorizeRouterData) -> Self {
Self {
amount_to_capture: data.amount_captured,
currency: data.request.currency,
connector_transaction_id: data.payment_id.clone(),
amount: Some(data.request.amount),
}
}
}
pub trait Tokenizable {
fn set_session_token(&mut self, token: Option<String>);
}
impl Tokenizable for SetupMandateRequestData {
fn set_session_token(&mut self, _token: Option<String>) {}
}
impl Tokenizable for PaymentsAuthorizeData {
fn set_session_token(&mut self, token: Option<String>) {
self.session_token = token;
}
}
impl Tokenizable for CompleteAuthorizeData {
fn set_session_token(&mut self, _token: Option<String>) {}
}
impl ForeignFrom<&SetupMandateRouterData> for PaymentsAuthorizeData {
fn foreign_from(data: &SetupMandateRouterData) -> Self {
Self {
currency: data.request.currency,
payment_method_data: data.request.payment_method_data.clone(),
confirm: data.request.confirm,
statement_descriptor_suffix: data.request.statement_descriptor_suffix.clone(),
mandate_id: data.request.mandate_id.clone(),
setup_future_usage: data.request.setup_future_usage,
off_session: data.request.off_session,
setup_mandate_details: data.request.setup_mandate_details.clone(),
router_return_url: data.request.router_return_url.clone(),
email: data.request.email.clone(),
customer_name: data.request.customer_name.clone(),
amount: 0,
order_tax_amount: Some(MinorUnit::zero()),
minor_amount: MinorUnit::new(0),
statement_descriptor: None,
capture_method: None,
webhook_url: None,
complete_authorize_url: None,
browser_info: data.request.browser_info.clone(),
order_details: None,
order_category: None,
session_token: None,
enrolled_for_3ds: true,
related_transaction_id: None,
payment_experience: None,
payment_method_type: None,
customer_id: None,
surcharge_details: None,
request_incremental_authorization: data.request.request_incremental_authorization,
metadata: None,
request_extended_authorization: None,
authentication_data: None,
customer_acceptance: data.request.customer_acceptance.clone(),
split_payments: None, // TODO: allow charges on mandates?
merchant_order_reference_id: None,
integrity_object: None,
additional_payment_method_data: None,
shipping_cost: data.request.shipping_cost,
merchant_account_id: None,
merchant_config_currency: None,
}
}
}
impl<F1, F2, T1, T2> ForeignFrom<(&RouterData<F1, T1, PaymentsResponseData>, T2)>
for RouterData<F2, T2, PaymentsResponseData>
{
fn foreign_from(item: (&RouterData<F1, T1, PaymentsResponseData>, T2)) -> Self {
let data = item.0;
let request = item.1;
Self {
flow: PhantomData,
request,
merchant_id: data.merchant_id.clone(),
connector: data.connector.clone(),
attempt_id: data.attempt_id.clone(),
tenant_id: data.tenant_id.clone(),
status: data.status,
payment_method: data.payment_method,
connector_auth_type: data.connector_auth_type.clone(),
description: data.description.clone(),
address: data.address.clone(),
auth_type: data.auth_type,
connector_meta_data: data.connector_meta_data.clone(),
connector_wallets_details: data.connector_wallets_details.clone(),
amount_captured: data.amount_captured,
minor_amount_captured: data.minor_amount_captured,
access_token: data.access_token.clone(),
response: data.response.clone(),
payment_id: data.payment_id.clone(),
session_token: data.session_token.clone(),
reference_id: data.reference_id.clone(),
customer_id: data.customer_id.clone(),
payment_method_token: None,
preprocessing_id: None,
connector_customer: data.connector_customer.clone(),
recurring_mandate_payment_data: data.recurring_mandate_payment_data.clone(),
connector_request_reference_id: data.connector_request_reference_id.clone(),
#[cfg(feature = "payouts")]
payout_method_data: data.payout_method_data.clone(),
#[cfg(feature = "payouts")]
quote_id: data.quote_id.clone(),
test_mode: data.test_mode,
payment_method_status: None,
payment_method_balance: data.payment_method_balance.clone(),
connector_api_version: data.connector_api_version.clone(),
connector_http_status_code: data.connector_http_status_code,
external_latency: data.external_latency,
apple_pay_flow: data.apple_pay_flow.clone(),
frm_metadata: data.frm_metadata.clone(),
dispute_id: data.dispute_id.clone(),
refund_id: data.refund_id.clone(),
connector_response: data.connector_response.clone(),
integrity_check: Ok(()),
additional_merchant_data: data.additional_merchant_data.clone(),
header_payload: data.header_payload.clone(),
connector_mandate_request_reference_id: data
.connector_mandate_request_reference_id
.clone(),
authentication_id: data.authentication_id.clone(),
psd2_sca_exemption_type: data.psd2_sca_exemption_type,
}
}
}
#[cfg(feature = "payouts")]
impl<F1, F2>
ForeignFrom<(
&RouterData<F1, PayoutsData, PayoutsResponseData>,
PayoutsData,
)> for RouterData<F2, PayoutsData, PayoutsResponseData>
{
fn foreign_from(
item: (
&RouterData<F1, PayoutsData, PayoutsResponseData>,
PayoutsData,
),
) -> Self {
let data = item.0;
let request = item.1;
Self {
flow: PhantomData,
request,
merchant_id: data.merchant_id.clone(),
connector: data.connector.clone(),
attempt_id: data.attempt_id.clone(),
tenant_id: data.tenant_id.clone(),
status: data.status,
payment_method: data.payment_method,
connector_auth_type: data.connector_auth_type.clone(),
description: data.description.clone(),
address: data.address.clone(),
auth_type: data.auth_type,
connector_meta_data: data.connector_meta_data.clone(),
connector_wallets_details: data.connector_wallets_details.clone(),
amount_captured: data.amount_captured,
minor_amount_captured: data.minor_amount_captured,
access_token: data.access_token.clone(),
response: data.response.clone(),
payment_id: data.payment_id.clone(),
session_token: data.session_token.clone(),
reference_id: data.reference_id.clone(),
customer_id: data.customer_id.clone(),
payment_method_token: None,
recurring_mandate_payment_data: None,
preprocessing_id: None,
connector_customer: data.connector_customer.clone(),
connector_request_reference_id:
IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_PAYOUTS_FLOW.to_string(),
payout_method_data: data.payout_method_data.clone(),
quote_id: data.quote_id.clone(),
test_mode: data.test_mode,
payment_method_balance: None,
payment_method_status: None,
connector_api_version: None,
connector_http_status_code: data.connector_http_status_code,
external_latency: data.external_latency,
apple_pay_flow: None,
frm_metadata: None,
refund_id: None,
dispute_id: None,
connector_response: data.connector_response.clone(),
integrity_check: Ok(()),
header_payload: data.header_payload.clone(),
authentication_id: None,
psd2_sca_exemption_type: None,
additional_merchant_data: data.additional_merchant_data.clone(),
connector_mandate_request_reference_id: None,
}
}
}
#[cfg(feature = "v2")]
impl ForeignFrom<&domain::MerchantConnectorAccountFeatureMetadata>
for api_models::admin::MerchantConnectorAccountFeatureMetadata
{
fn foreign_from(item: &domain::MerchantConnectorAccountFeatureMetadata) -> Self {
let revenue_recovery = item
.revenue_recovery
.as_ref()
.map(
|revenue_recovery_metadata| api_models::admin::RevenueRecoveryMetadata {
max_retry_count: revenue_recovery_metadata.max_retry_count,
billing_connector_retry_threshold: revenue_recovery_metadata
.billing_connector_retry_threshold,
billing_account_reference: revenue_recovery_metadata
.mca_reference
.recovery_to_billing
.clone(),
},
);
Self { revenue_recovery }
}
}
#[cfg(feature = "v2")]
impl ForeignTryFrom<&api_models::admin::MerchantConnectorAccountFeatureMetadata>
for domain::MerchantConnectorAccountFeatureMetadata
{
type Error = errors::ApiErrorResponse;
fn foreign_try_from(
feature_metadata: &api_models::admin::MerchantConnectorAccountFeatureMetadata,
) -> Result<Self, Self::Error> {
let revenue_recovery = feature_metadata
.revenue_recovery
.as_ref()
.map(|revenue_recovery_metadata| {
domain::AccountReferenceMap::new(
revenue_recovery_metadata.billing_account_reference.clone(),
)
.map(|mca_reference| domain::RevenueRecoveryMetadata {
max_retry_count: revenue_recovery_metadata.max_retry_count,
billing_connector_retry_threshold: revenue_recovery_metadata
.billing_connector_retry_threshold,
mca_reference,
})
})
.transpose()?;
Ok(Self { revenue_recovery })
}
}
| 8,926 | 1,213 |
hyperswitch | crates/router/src/analytics_validator.rs | .rs | use analytics::errors::AnalyticsError;
use api_models::analytics::AnalyticsRequest;
use common_utils::errors::CustomResult;
use currency_conversion::types::ExchangeRates;
use router_env::logger;
use crate::core::currency::get_forex_exchange_rates;
pub async fn request_validator(
req_type: AnalyticsRequest,
state: &crate::routes::SessionState,
) -> CustomResult<Option<ExchangeRates>, AnalyticsError> {
let forex_enabled = state.conf.analytics.get_inner().get_forex_enabled();
let require_forex_functionality = req_type.requires_forex_functionality();
let ex_rates = if forex_enabled && require_forex_functionality {
logger::info!("Fetching forex exchange rates");
Some(get_forex_exchange_rates(state.clone()).await?)
} else {
None
};
Ok(ex_rates)
}
| 175 | 1,214 |
hyperswitch | crates/router/src/env.rs | .rs | #[doc(inline)]
pub use router_env::*;
| 10 | 1,215 |
hyperswitch | crates/router/src/lib.rs | .rs | #[cfg(all(feature = "stripe", feature = "v1"))]
pub mod compatibility;
pub mod configs;
pub mod connection;
pub mod connector;
pub mod consts;
pub mod core;
pub mod cors;
pub mod db;
pub mod env;
pub mod locale;
pub(crate) mod macros;
pub mod routes;
pub mod workflows;
#[cfg(feature = "olap")]
pub mod analytics;
pub mod analytics_validator;
pub mod events;
pub mod middleware;
pub mod services;
pub mod types;
pub mod utils;
use actix_web::{
body::MessageBody,
dev::{Server, ServerHandle, ServiceFactory, ServiceRequest},
middleware::ErrorHandlers,
};
use http::StatusCode;
use hyperswitch_interfaces::secrets_interface::secret_state::SecuredSecret;
use router_env::tracing::Instrument;
use routes::{AppState, SessionState};
use storage_impl::errors::ApplicationResult;
use tokio::sync::{mpsc, oneshot};
pub use self::env::logger;
pub(crate) use self::macros::*;
use crate::{configs::settings, core::errors};
#[cfg(feature = "mimalloc")]
#[global_allocator]
static ALLOC: mimalloc::MiMalloc = mimalloc::MiMalloc;
// Import translate fn in root
use crate::locale::{_rust_i18n_t, _rust_i18n_try_translate};
/// Header Constants
pub mod headers {
pub const ACCEPT: &str = "Accept";
pub const ACCEPT_LANGUAGE: &str = "Accept-Language";
pub const KEY: &str = "key";
pub const API_KEY: &str = "API-KEY";
pub const APIKEY: &str = "apikey";
pub const X_CC_API_KEY: &str = "X-CC-Api-Key";
pub const API_TOKEN: &str = "Api-Token";
pub const AUTHORIZATION: &str = "Authorization";
pub const CONTENT_TYPE: &str = "Content-Type";
pub const DATE: &str = "Date";
pub const IDEMPOTENCY_KEY: &str = "Idempotency-Key";
pub const NONCE: &str = "nonce";
pub const TIMESTAMP: &str = "Timestamp";
pub const TOKEN: &str = "token";
pub const USER_AGENT: &str = "User-Agent";
pub const X_API_KEY: &str = "X-API-KEY";
pub const X_API_VERSION: &str = "X-ApiVersion";
pub const X_FORWARDED_FOR: &str = "X-Forwarded-For";
pub const X_MERCHANT_ID: &str = "X-Merchant-Id";
pub const X_ORGANIZATION_ID: &str = "X-Organization-Id";
pub const X_LOGIN: &str = "X-Login";
pub const X_TRANS_KEY: &str = "X-Trans-Key";
pub const X_VERSION: &str = "X-Version";
pub const X_CC_VERSION: &str = "X-CC-Version";
pub const X_ACCEPT_VERSION: &str = "X-Accept-Version";
pub const X_DATE: &str = "X-Date";
pub const X_WEBHOOK_SIGNATURE: &str = "X-Webhook-Signature-512";
pub const X_REQUEST_ID: &str = "X-Request-Id";
pub const X_PROFILE_ID: &str = "X-Profile-Id";
pub const STRIPE_COMPATIBLE_WEBHOOK_SIGNATURE: &str = "Stripe-Signature";
pub const STRIPE_COMPATIBLE_CONNECT_ACCOUNT: &str = "Stripe-Account";
pub const X_CLIENT_VERSION: &str = "X-Client-Version";
pub const X_CLIENT_SOURCE: &str = "X-Client-Source";
pub const X_PAYMENT_CONFIRM_SOURCE: &str = "X-Payment-Confirm-Source";
pub const CONTENT_LENGTH: &str = "Content-Length";
pub const BROWSER_NAME: &str = "x-browser-name";
pub const X_CLIENT_PLATFORM: &str = "x-client-platform";
pub const X_MERCHANT_DOMAIN: &str = "x-merchant-domain";
pub const X_APP_ID: &str = "x-app-id";
pub const X_REDIRECT_URI: &str = "x-redirect-uri";
pub const X_TENANT_ID: &str = "x-tenant-id";
pub const X_CLIENT_SECRET: &str = "X-Client-Secret";
pub const X_CUSTOMER_ID: &str = "X-Customer-Id";
pub const X_CONNECTED_MERCHANT_ID: &str = "x-connected-merchant-id";
}
pub mod pii {
//! Personal Identifiable Information protection.
pub(crate) use common_utils::pii::Email;
#[doc(inline)]
pub use masking::*;
}
pub fn mk_app(
state: AppState,
request_body_limit: usize,
) -> actix_web::App<
impl ServiceFactory<
ServiceRequest,
Config = (),
Response = actix_web::dev::ServiceResponse<impl MessageBody>,
Error = actix_web::Error,
InitError = (),
>,
> {
let mut server_app = get_application_builder(request_body_limit, state.conf.cors.clone());
#[cfg(all(feature = "dummy_connector", feature = "v1"))]
{
use routes::DummyConnector;
server_app = server_app.service(DummyConnector::server(state.clone()));
}
#[cfg(any(feature = "olap", feature = "oltp"))]
{
#[cfg(feature = "olap")]
{
// This is a more specific route as compared to `MerchantConnectorAccount`
// so it is registered before `MerchantConnectorAccount`.
#[cfg(feature = "v1")]
{
server_app = server_app
.service(routes::ProfileNew::server(state.clone()))
.service(routes::Forex::server(state.clone()));
}
server_app = server_app.service(routes::Profile::server(state.clone()));
}
server_app = server_app
.service(routes::Payments::server(state.clone()))
.service(routes::Customers::server(state.clone()))
.service(routes::Configs::server(state.clone()))
.service(routes::MerchantConnectorAccount::server(state.clone()))
.service(routes::RelayWebhooks::server(state.clone()))
.service(routes::Webhooks::server(state.clone()))
.service(routes::Hypersense::server(state.clone()))
.service(routes::Relay::server(state.clone()));
#[cfg(feature = "oltp")]
{
server_app = server_app.service(routes::PaymentMethods::server(state.clone()));
}
#[cfg(all(feature = "v2", feature = "oltp"))]
{
server_app = server_app.service(routes::PaymentMethodSession::server(state.clone()));
}
#[cfg(feature = "v1")]
{
server_app = server_app
.service(routes::Refunds::server(state.clone()))
.service(routes::Mandates::server(state.clone()));
}
}
#[cfg(all(feature = "oltp", any(feature = "v1", feature = "v2"),))]
{
server_app = server_app.service(routes::EphemeralKey::server(state.clone()))
}
#[cfg(all(
feature = "oltp",
any(feature = "v1", feature = "v2"),
not(feature = "customer_v2")
))]
{
server_app = server_app.service(routes::Poll::server(state.clone()))
}
#[cfg(feature = "olap")]
{
server_app = server_app
.service(routes::Organization::server(state.clone()))
.service(routes::MerchantAccount::server(state.clone()))
.service(routes::User::server(state.clone()))
.service(routes::ApiKeys::server(state.clone()))
.service(routes::Routing::server(state.clone()));
#[cfg(feature = "v1")]
{
server_app = server_app
.service(routes::Files::server(state.clone()))
.service(routes::Disputes::server(state.clone()))
.service(routes::Blocklist::server(state.clone()))
.service(routes::Gsm::server(state.clone()))
.service(routes::ApplePayCertificatesMigration::server(state.clone()))
.service(routes::PaymentLink::server(state.clone()))
.service(routes::ConnectorOnboarding::server(state.clone()))
.service(routes::Verify::server(state.clone()))
.service(routes::Analytics::server(state.clone()))
.service(routes::WebhookEvents::server(state.clone()))
.service(routes::FeatureMatrix::server(state.clone()));
}
#[cfg(feature = "v2")]
{
server_app = server_app.service(routes::ProcessTracker::server(state.clone()));
}
}
#[cfg(all(feature = "payouts", feature = "v1"))]
{
server_app = server_app
.service(routes::Payouts::server(state.clone()))
.service(routes::PayoutLink::server(state.clone()));
}
#[cfg(all(
feature = "stripe",
any(feature = "v1", feature = "v2"),
not(feature = "customer_v2")
))]
{
server_app = server_app
.service(routes::StripeApis::server(state.clone()))
.service(routes::Cards::server(state.clone()));
}
#[cfg(all(feature = "recon", feature = "v1"))]
{
server_app = server_app.service(routes::Recon::server(state.clone()));
}
server_app = server_app.service(routes::Cache::server(state.clone()));
server_app = server_app.service(routes::Health::server(state.clone()));
server_app
}
/// Starts the server
///
/// # Panics
///
/// Unwrap used because without the value we can't start the server
#[allow(clippy::expect_used, clippy::unwrap_used)]
pub async fn start_server(conf: settings::Settings<SecuredSecret>) -> ApplicationResult<Server> {
logger::debug!(startup_config=?conf);
let server = conf.server.clone();
let (tx, rx) = oneshot::channel();
let api_client = Box::new(services::ProxyClient::new(&conf.proxy).map_err(|error| {
errors::ApplicationError::ApiClientError(error.current_context().clone())
})?);
let state = Box::pin(AppState::new(conf, tx, api_client)).await;
let request_body_limit = server.request_body_limit;
let server_builder =
actix_web::HttpServer::new(move || mk_app(state.clone(), request_body_limit))
.bind((server.host.as_str(), server.port))?
.workers(server.workers)
.shutdown_timeout(server.shutdown_timeout);
#[cfg(feature = "tls")]
let server = match server.tls {
None => server_builder.run(),
Some(tls_conf) => {
let cert_file =
&mut std::io::BufReader::new(std::fs::File::open(tls_conf.certificate).map_err(
|err| errors::ApplicationError::InvalidConfigurationValueError(err.to_string()),
)?);
let key_file =
&mut std::io::BufReader::new(std::fs::File::open(tls_conf.private_key).map_err(
|err| errors::ApplicationError::InvalidConfigurationValueError(err.to_string()),
)?);
let cert_chain = rustls_pemfile::certs(cert_file)
.collect::<Result<Vec<_>, _>>()
.map_err(|err| {
errors::ApplicationError::InvalidConfigurationValueError(err.to_string())
})?;
let mut keys = rustls_pemfile::pkcs8_private_keys(key_file)
.map(|key| key.map(rustls::pki_types::PrivateKeyDer::Pkcs8))
.collect::<Result<Vec<_>, _>>()
.map_err(|err| {
errors::ApplicationError::InvalidConfigurationValueError(err.to_string())
})?;
// exit if no keys could be parsed
if keys.is_empty() {
return Err(errors::ApplicationError::InvalidConfigurationValueError(
"Could not locate PKCS8 private keys.".into(),
));
}
let config_builder = rustls::ServerConfig::builder().with_no_client_auth();
let config = config_builder
.with_single_cert(cert_chain, keys.remove(0))
.map_err(|err| {
errors::ApplicationError::InvalidConfigurationValueError(err.to_string())
})?;
server_builder
.bind_rustls_0_22(
(tls_conf.host.unwrap_or(server.host).as_str(), tls_conf.port),
config,
)?
.run()
}
};
#[cfg(not(feature = "tls"))]
let server = server_builder.run();
let _task_handle = tokio::spawn(receiver_for_error(rx, server.handle()).in_current_span());
Ok(server)
}
pub async fn receiver_for_error(rx: oneshot::Receiver<()>, mut server: impl Stop) {
match rx.await {
Ok(_) => {
logger::error!("The redis server failed ");
server.stop_server().await;
}
Err(err) => {
logger::error!("Channel receiver error: {err}");
}
}
}
#[async_trait::async_trait]
pub trait Stop {
async fn stop_server(&mut self);
}
#[async_trait::async_trait]
impl Stop for ServerHandle {
async fn stop_server(&mut self) {
let _ = self.stop(true).await;
}
}
#[async_trait::async_trait]
impl Stop for mpsc::Sender<()> {
async fn stop_server(&mut self) {
let _ = self.send(()).await.map_err(|err| logger::error!("{err}"));
}
}
pub fn get_application_builder(
request_body_limit: usize,
cors: settings::CorsSettings,
) -> actix_web::App<
impl ServiceFactory<
ServiceRequest,
Config = (),
Response = actix_web::dev::ServiceResponse<impl MessageBody>,
Error = actix_web::Error,
InitError = (),
>,
> {
let json_cfg = actix_web::web::JsonConfig::default()
.limit(request_body_limit)
.content_type_required(true)
.error_handler(utils::error_parser::custom_json_error_handler);
actix_web::App::new()
.app_data(json_cfg)
.wrap(ErrorHandlers::new().handler(
StatusCode::NOT_FOUND,
errors::error_handlers::custom_error_handlers,
))
.wrap(ErrorHandlers::new().handler(
StatusCode::METHOD_NOT_ALLOWED,
errors::error_handlers::custom_error_handlers,
))
.wrap(middleware::default_response_headers())
.wrap(middleware::RequestId)
.wrap(cors::cors(cors))
// this middleware works only for Http1.1 requests
.wrap(middleware::Http400RequestDetailsLogger)
.wrap(middleware::AddAcceptLanguageHeader)
.wrap(middleware::LogSpanInitializer)
.wrap(router_env::tracing_actix_web::TracingLogger::default())
}
| 3,212 | 1,216 |
hyperswitch | crates/router/src/connector.rs | .rs | pub mod adyenplatform;
#[cfg(feature = "dummy_connector")]
pub mod dummyconnector;
pub mod ebanx;
pub mod gpayments;
pub mod netcetera;
pub mod nmi;
pub mod payone;
pub mod plaid;
pub mod riskified;
pub mod signifyd;
pub mod stripe;
pub mod threedsecureio;
pub mod utils;
pub mod wellsfargopayout;
pub mod wise;
pub use hyperswitch_connectors::connectors::{
aci, aci::Aci, adyen, adyen::Adyen, airwallex, airwallex::Airwallex, amazonpay,
amazonpay::Amazonpay, authorizedotnet, authorizedotnet::Authorizedotnet, bambora,
bambora::Bambora, bamboraapac, bamboraapac::Bamboraapac, bankofamerica,
bankofamerica::Bankofamerica, billwerk, billwerk::Billwerk, bitpay, bitpay::Bitpay, bluesnap,
bluesnap::Bluesnap, boku, boku::Boku, braintree, braintree::Braintree, cashtocode,
cashtocode::Cashtocode, chargebee::Chargebee, checkout, checkout::Checkout, coinbase,
coinbase::Coinbase, coingate, coingate::Coingate, cryptopay, cryptopay::Cryptopay,
ctp_mastercard, ctp_mastercard::CtpMastercard, cybersource, cybersource::Cybersource,
datatrans, datatrans::Datatrans, deutschebank, deutschebank::Deutschebank, digitalvirgo,
digitalvirgo::Digitalvirgo, dlocal, dlocal::Dlocal, elavon, elavon::Elavon, facilitapay,
facilitapay::Facilitapay, fiserv, fiserv::Fiserv, fiservemea, fiservemea::Fiservemea, fiuu,
fiuu::Fiuu, forte, forte::Forte, getnet, getnet::Getnet, globalpay, globalpay::Globalpay,
globepay, globepay::Globepay, gocardless, gocardless::Gocardless, helcim, helcim::Helcim,
hipay, hipay::Hipay, iatapay, iatapay::Iatapay, inespay, inespay::Inespay, itaubank,
itaubank::Itaubank, jpmorgan, jpmorgan::Jpmorgan, juspaythreedsserver,
juspaythreedsserver::Juspaythreedsserver, klarna, klarna::Klarna, mifinity, mifinity::Mifinity,
mollie, mollie::Mollie, moneris, moneris::Moneris, multisafepay, multisafepay::Multisafepay,
nexinets, nexinets::Nexinets, nexixpay, nexixpay::Nexixpay, nomupay, nomupay::Nomupay, noon,
noon::Noon, novalnet, novalnet::Novalnet, nuvei, nuvei::Nuvei, opayo, opayo::Opayo, opennode,
opennode::Opennode, paybox, paybox::Paybox, payeezy, payeezy::Payeezy, payme, payme::Payme,
paypal, paypal::Paypal, paystack, paystack::Paystack, payu, payu::Payu, placetopay,
placetopay::Placetopay, powertranz, powertranz::Powertranz, prophetpay, prophetpay::Prophetpay,
rapyd, rapyd::Rapyd, razorpay, razorpay::Razorpay, recurly::Recurly, redsys, redsys::Redsys,
shift4, shift4::Shift4, square, square::Square, stax, stax::Stax, stripebilling,
stripebilling::Stripebilling, taxjar, taxjar::Taxjar, thunes, thunes::Thunes, trustpay,
trustpay::Trustpay, tsys, tsys::Tsys, unified_authentication_service,
unified_authentication_service::UnifiedAuthenticationService, volt, volt::Volt, wellsfargo,
wellsfargo::Wellsfargo, worldline, worldline::Worldline, worldpay, worldpay::Worldpay, xendit,
xendit::Xendit, zen, zen::Zen, zsl, zsl::Zsl,
};
#[cfg(feature = "dummy_connector")]
pub use self::dummyconnector::DummyConnector;
pub use self::{
adyenplatform::Adyenplatform, ebanx::Ebanx, gpayments::Gpayments, netcetera::Netcetera,
nmi::Nmi, payone::Payone, plaid::Plaid, riskified::Riskified, signifyd::Signifyd,
stripe::Stripe, threedsecureio::Threedsecureio, wellsfargopayout::Wellsfargopayout, wise::Wise,
};
| 1,142 | 1,217 |
hyperswitch | crates/router/src/events.rs | .rs | use std::collections::HashMap;
use error_stack::ResultExt;
use events::{EventsError, Message, MessagingInterface};
use masking::ErasedMaskSerialize;
use router_env::logger;
use serde::{Deserialize, Serialize};
use storage_impl::{
config::TenantConfig,
errors::{ApplicationError, StorageError, StorageResult},
};
use time::PrimitiveDateTime;
use crate::{
db::KafkaProducer,
services::kafka::{KafkaMessage, KafkaSettings},
};
pub mod api_logs;
pub mod audit_events;
pub mod connector_api_logs;
pub mod event_logger;
pub mod outgoing_webhook_logs;
#[derive(Debug, Serialize, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum EventType {
PaymentIntent,
FraudCheck,
PaymentAttempt,
Refund,
ApiLogs,
ConnectorApiLogs,
OutgoingWebhookLogs,
Dispute,
AuditEvent,
#[cfg(feature = "payouts")]
Payout,
Consolidated,
Authentication,
}
#[derive(Debug, Default, Deserialize, Clone)]
#[serde(tag = "source")]
#[serde(rename_all = "lowercase")]
pub enum EventsConfig {
Kafka {
kafka: Box<KafkaSettings>,
},
#[default]
Logs,
}
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone)]
pub enum EventsHandler {
Kafka(KafkaProducer),
Logs(event_logger::EventLogger),
}
impl Default for EventsHandler {
fn default() -> Self {
Self::Logs(event_logger::EventLogger {})
}
}
impl EventsConfig {
pub async fn get_event_handler(&self) -> StorageResult<EventsHandler> {
Ok(match self {
Self::Kafka { kafka } => EventsHandler::Kafka(
KafkaProducer::create(kafka)
.await
.change_context(StorageError::InitializationError)?,
),
Self::Logs => EventsHandler::Logs(event_logger::EventLogger::default()),
})
}
pub fn validate(&self) -> Result<(), ApplicationError> {
match self {
Self::Kafka { kafka } => kafka.validate(),
Self::Logs => Ok(()),
}
}
}
impl EventsHandler {
pub fn log_event<T: KafkaMessage>(&self, event: &T) {
match self {
Self::Kafka(kafka) => kafka.log_event(event).unwrap_or_else(|e| {
logger::error!("Failed to log event: {:?}", e);
}),
Self::Logs(logger) => logger.log_event(event),
};
}
pub fn add_tenant(&mut self, tenant_config: &dyn TenantConfig) {
if let Self::Kafka(kafka_producer) = self {
kafka_producer.set_tenancy(tenant_config);
}
}
}
impl MessagingInterface for EventsHandler {
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> + ErasedMaskSerialize,
{
match self {
Self::Kafka(a) => a.send_message(data, metadata, timestamp),
Self::Logs(a) => a.send_message(data, metadata, timestamp),
}
}
}
| 703 | 1,218 |
hyperswitch | crates/router/src/services.rs | .rs | pub mod api;
pub mod authentication;
pub mod authorization;
pub mod connector_integration_interface;
#[cfg(feature = "email")]
pub mod email;
pub mod encryption;
#[cfg(feature = "olap")]
pub mod jwt;
pub mod kafka;
pub mod logger;
pub mod pm_auth;
pub mod card_testing_guard;
#[cfg(feature = "olap")]
pub mod openidconnect;
use std::sync::Arc;
use error_stack::ResultExt;
pub use hyperswitch_interfaces::connector_integration_v2::{
BoxedConnectorIntegrationV2, ConnectorIntegrationAnyV2, ConnectorIntegrationV2,
};
use masking::{ExposeInterface, StrongSecret};
#[cfg(feature = "kv_store")]
use storage_impl::kv_router_store::KVRouterStore;
use storage_impl::{config::TenantConfig, errors::StorageResult, redis::RedisStore, RouterStore};
use tokio::sync::oneshot;
pub use self::{api::*, encryption::*};
use crate::{configs::Settings, core::errors};
#[cfg(not(feature = "olap"))]
pub type StoreType = storage_impl::database::store::Store;
#[cfg(feature = "olap")]
pub type StoreType = storage_impl::database::store::ReplicaStore;
#[cfg(not(feature = "kv_store"))]
pub type Store = RouterStore<StoreType>;
#[cfg(feature = "kv_store")]
pub type Store = KVRouterStore<StoreType>;
/// # Panics
///
/// Will panic if hex decode of master key fails
#[allow(clippy::expect_used)]
pub async fn get_store(
config: &Settings,
tenant: &dyn TenantConfig,
cache_store: Arc<RedisStore>,
test_transaction: bool,
) -> StorageResult<Store> {
let master_config = config.master_database.clone().into_inner();
#[cfg(feature = "olap")]
let replica_config = config.replica_database.clone().into_inner();
#[allow(clippy::expect_used)]
let master_enc_key = hex::decode(config.secrets.get_inner().master_enc_key.clone().expose())
.map(StrongSecret::new)
.expect("Failed to decode master key from hex");
#[cfg(not(feature = "olap"))]
let conf = master_config.into();
#[cfg(feature = "olap")]
// this would get abstracted, for all cases
#[allow(clippy::useless_conversion)]
let conf = (master_config.into(), replica_config.into());
let store: RouterStore<StoreType> = if test_transaction {
RouterStore::test_store(conf, tenant, &config.redis, master_enc_key).await?
} else {
RouterStore::from_config(
conf,
tenant,
master_enc_key,
cache_store,
storage_impl::redis::cache::IMC_INVALIDATION_CHANNEL,
)
.await?
};
#[cfg(feature = "kv_store")]
let store = KVRouterStore::from_store(
store,
config.drainer.stream_name.clone(),
config.drainer.num_partitions,
config.kv_config.ttl,
config.kv_config.soft_kill,
);
Ok(store)
}
#[allow(clippy::expect_used)]
pub async fn get_cache_store(
config: &Settings,
shut_down_signal: oneshot::Sender<()>,
_test_transaction: bool,
) -> StorageResult<Arc<RedisStore>> {
RouterStore::<StoreType>::cache_store(&config.redis, shut_down_signal).await
}
#[inline]
pub fn generate_aes256_key() -> errors::CustomResult<[u8; 32], common_utils::errors::CryptoError> {
use ring::rand::SecureRandom;
let rng = ring::rand::SystemRandom::new();
let mut key: [u8; 256 / 8] = [0_u8; 256 / 8];
rng.fill(&mut key)
.change_context(common_utils::errors::CryptoError::EncodingFailed)?;
Ok(key)
}
| 840 | 1,219 |
hyperswitch | crates/router/src/macros.rs | .rs | pub use common_utils::{collect_missing_value_keys, newtype};
#[macro_export]
macro_rules! get_formatted_date_time {
($date_format:tt) => {{
let format = time::macros::format_description!($date_format);
time::OffsetDateTime::now_utc()
.format(&format)
.change_context($crate::core::errors::ConnectorError::InvalidDateFormat)
}};
}
#[macro_export]
macro_rules! get_payment_link_config_value_based_on_priority {
($config:expr, $business_config:expr, $field:ident, $default:expr) => {
$config
.as_ref()
.and_then(|pc_config| pc_config.theme_config.$field.clone())
.or_else(|| {
$business_config
.as_ref()
.and_then(|business_config| business_config.$field.clone())
})
.unwrap_or($default)
};
}
#[macro_export]
macro_rules! get_payment_link_config_value {
($config:expr, $business_config:expr, $(($field:ident, $default:expr)),*) => {
(
$(get_payment_link_config_value_based_on_priority!($config, $business_config, $field, $default)),*
)
};
($config:expr, $business_config:expr, $(($field:ident)),*) => {
(
$(
$config
.as_ref()
.and_then(|pc_config| pc_config.theme_config.$field.clone())
.or_else(|| {
$business_config
.as_ref()
.and_then(|business_config| business_config.$field.clone())
})
),*
)
};
($config:expr, $business_config:expr, $(($field:ident $(, $transform:expr)?)),* $(,)?) => {
(
$(
$config
.as_ref()
.and_then(|pc_config| pc_config.theme_config.$field.clone())
.or_else(|| {
$business_config
.as_ref()
.and_then(|business_config| {
let value = business_config.$field.clone();
$(let value = value.map($transform);)?
value
})
})
),*
)
};
}
| 462 | 1,220 |
hyperswitch | crates/router/src/routes.rs | .rs | pub mod admin;
pub mod api_keys;
pub mod app;
#[cfg(feature = "v1")]
pub mod apple_pay_certificates_migration;
#[cfg(all(feature = "olap", feature = "v1"))]
pub mod blocklist;
pub mod cache;
pub mod cards_info;
pub mod configs;
#[cfg(feature = "olap")]
pub mod connector_onboarding;
#[cfg(any(feature = "olap", feature = "oltp"))]
pub mod currency;
pub mod customers;
pub mod disputes;
#[cfg(feature = "dummy_connector")]
pub mod dummy_connector;
pub mod ephemeral_key;
pub mod feature_matrix;
pub mod files;
#[cfg(feature = "frm")]
pub mod fraud_check;
pub mod gsm;
pub mod health;
pub mod hypersense;
pub mod lock_utils;
#[cfg(feature = "v1")]
pub mod locker_migration;
pub mod mandates;
pub mod metrics;
#[cfg(feature = "v1")]
pub mod payment_link;
pub mod payment_methods;
pub mod payments;
#[cfg(feature = "payouts")]
pub mod payout_link;
#[cfg(feature = "payouts")]
pub mod payouts;
#[cfg(any(feature = "olap", feature = "oltp"))]
pub mod pm_auth;
pub mod poll;
#[cfg(feature = "olap")]
pub mod profiles;
#[cfg(feature = "recon")]
pub mod recon;
#[cfg(feature = "v1")]
pub mod refunds;
#[cfg(feature = "olap")]
pub mod routing;
#[cfg(feature = "olap")]
pub mod user;
#[cfg(feature = "olap")]
pub mod user_role;
#[cfg(feature = "olap")]
pub mod verification;
#[cfg(feature = "olap")]
pub mod verify_connector;
#[cfg(all(feature = "olap", feature = "v1"))]
pub mod webhook_events;
pub mod webhooks;
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
pub mod recovery_webhooks;
pub mod relay;
#[cfg(feature = "olap")]
pub mod process_tracker;
#[cfg(feature = "dummy_connector")]
pub use self::app::DummyConnector;
#[cfg(feature = "v2")]
pub use self::app::PaymentMethodSession;
#[cfg(all(feature = "olap", feature = "recon", feature = "v1"))]
pub use self::app::Recon;
pub use self::app::{
ApiKeys, AppState, ApplePayCertificatesMigration, Cache, Cards, Configs, ConnectorOnboarding,
Customers, Disputes, EphemeralKey, FeatureMatrix, Files, Forex, Gsm, Health, Hypersense,
Mandates, MerchantAccount, MerchantConnectorAccount, PaymentLink, PaymentMethods, Payments,
Poll, ProcessTracker, Profile, ProfileNew, Refunds, Relay, RelayWebhooks, SessionState, User,
Webhooks,
};
#[cfg(feature = "olap")]
pub use self::app::{Blocklist, Organization, Routing, Verify, WebhookEvents};
#[cfg(feature = "payouts")]
pub use self::app::{PayoutLink, Payouts};
#[cfg(all(
feature = "stripe",
any(feature = "v1", feature = "v2"),
not(feature = "customer_v2")
))]
pub use super::compatibility::stripe::StripeApis;
#[cfg(feature = "olap")]
pub use crate::analytics::routes::{self as analytics, Analytics};
| 712 | 1,221 |
hyperswitch | crates/router/src/configs.rs | .rs | use hyperswitch_interfaces::secrets_interface::secret_state::RawSecret;
pub(crate) mod defaults;
pub mod secrets_transformers;
pub mod settings;
mod validations;
pub type Settings = settings::Settings<RawSecret>;
| 45 | 1,222 |
hyperswitch | crates/router/src/events/event_logger.rs | .rs | use std::collections::HashMap;
use events::{EventsError, Message, MessagingInterface};
use masking::ErasedMaskSerialize;
use time::PrimitiveDateTime;
use super::EventType;
use crate::services::{kafka::KafkaMessage, logger};
#[derive(Clone, Debug, Default)]
pub struct EventLogger {}
impl EventLogger {
#[track_caller]
pub(super) fn log_event<T: KafkaMessage>(&self, event: &T) {
logger::info!(event = ?event.masked_serialize().unwrap_or_else(|e| serde_json::json!({"error": e.to_string()})), event_type =? event.event_type(), event_id =? event.key(), log_type =? "event");
}
}
impl MessagingInterface for EventLogger {
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> + ErasedMaskSerialize,
{
logger::info!(event =? data.masked_serialize().unwrap_or_else(|e| serde_json::json!({"error": e.to_string()})), event_type =? data.get_message_class(), event_id =? data.identifier(), log_type =? "event", metadata = ?metadata);
Ok(())
}
}
| 294 | 1,223 |
hyperswitch | crates/router/src/events/outgoing_webhook_logs.rs | .rs | use api_models::{enums::EventType as OutgoingWebhookEventType, webhooks::OutgoingWebhookContent};
use common_enums::WebhookDeliveryAttempt;
use serde::Serialize;
use serde_json::Value;
use time::OffsetDateTime;
use super::EventType;
use crate::services::kafka::KafkaMessage;
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct OutgoingWebhookEvent {
tenant_id: common_utils::id_type::TenantId,
merchant_id: common_utils::id_type::MerchantId,
event_id: String,
event_type: OutgoingWebhookEventType,
#[serde(flatten)]
content: Option<OutgoingWebhookEventContent>,
is_error: bool,
error: Option<Value>,
created_at_timestamp: i128,
initial_attempt_id: Option<String>,
status_code: Option<u16>,
delivery_attempt: Option<WebhookDeliveryAttempt>,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(tag = "outgoing_webhook_event_type", rename_all = "snake_case")]
pub enum OutgoingWebhookEventContent {
#[cfg(feature = "v1")]
Payment {
payment_id: common_utils::id_type::PaymentId,
content: Value,
},
#[cfg(feature = "v2")]
Payment {
payment_id: common_utils::id_type::GlobalPaymentId,
content: Value,
},
Payout {
payout_id: String,
content: Value,
},
#[cfg(feature = "v1")]
Refund {
payment_id: common_utils::id_type::PaymentId,
refund_id: String,
content: Value,
},
#[cfg(feature = "v2")]
Refund {
payment_id: common_utils::id_type::GlobalPaymentId,
refund_id: String,
content: Value,
},
Dispute {
payment_id: common_utils::id_type::PaymentId,
attempt_id: String,
dispute_id: String,
content: Value,
},
Mandate {
payment_method_id: String,
mandate_id: String,
content: Value,
},
}
pub trait OutgoingWebhookEventMetric {
fn get_outgoing_webhook_event_content(&self) -> Option<OutgoingWebhookEventContent>;
}
#[cfg(feature = "v1")]
impl OutgoingWebhookEventMetric for OutgoingWebhookContent {
fn get_outgoing_webhook_event_content(&self) -> Option<OutgoingWebhookEventContent> {
match self {
Self::PaymentDetails(payment_payload) => Some(OutgoingWebhookEventContent::Payment {
payment_id: payment_payload.payment_id.clone(),
content: masking::masked_serialize(&payment_payload)
.unwrap_or(serde_json::json!({"error":"failed to serialize"})),
}),
Self::RefundDetails(refund_payload) => Some(OutgoingWebhookEventContent::Refund {
payment_id: refund_payload.payment_id.clone(),
refund_id: refund_payload.get_refund_id_as_string(),
content: masking::masked_serialize(&refund_payload)
.unwrap_or(serde_json::json!({"error":"failed to serialize"})),
}),
Self::DisputeDetails(dispute_payload) => Some(OutgoingWebhookEventContent::Dispute {
payment_id: dispute_payload.payment_id.clone(),
attempt_id: dispute_payload.attempt_id.clone(),
dispute_id: dispute_payload.dispute_id.clone(),
content: masking::masked_serialize(&dispute_payload)
.unwrap_or(serde_json::json!({"error":"failed to serialize"})),
}),
Self::MandateDetails(mandate_payload) => Some(OutgoingWebhookEventContent::Mandate {
payment_method_id: mandate_payload.payment_method_id.clone(),
mandate_id: mandate_payload.mandate_id.clone(),
content: masking::masked_serialize(&mandate_payload)
.unwrap_or(serde_json::json!({"error":"failed to serialize"})),
}),
#[cfg(feature = "payouts")]
Self::PayoutDetails(payout_payload) => Some(OutgoingWebhookEventContent::Payout {
payout_id: payout_payload.payout_id.clone(),
content: masking::masked_serialize(&payout_payload)
.unwrap_or(serde_json::json!({"error":"failed to serialize"})),
}),
}
}
}
#[cfg(feature = "v2")]
impl OutgoingWebhookEventMetric for OutgoingWebhookContent {
fn get_outgoing_webhook_event_content(&self) -> Option<OutgoingWebhookEventContent> {
match self {
Self::PaymentDetails(payment_payload) => Some(OutgoingWebhookEventContent::Payment {
payment_id: payment_payload.id.clone(),
content: masking::masked_serialize(&payment_payload)
.unwrap_or(serde_json::json!({"error":"failed to serialize"})),
}),
Self::RefundDetails(refund_payload) => Some(OutgoingWebhookEventContent::Refund {
payment_id: refund_payload.payment_id.clone(),
refund_id: refund_payload.get_refund_id_as_string(),
content: masking::masked_serialize(&refund_payload)
.unwrap_or(serde_json::json!({"error":"failed to serialize"})),
}),
Self::DisputeDetails(dispute_payload) => Some(OutgoingWebhookEventContent::Dispute {
payment_id: dispute_payload.payment_id.clone(),
attempt_id: dispute_payload.attempt_id.clone(),
dispute_id: dispute_payload.dispute_id.clone(),
content: masking::masked_serialize(&dispute_payload)
.unwrap_or(serde_json::json!({"error":"failed to serialize"})),
}),
Self::MandateDetails(mandate_payload) => Some(OutgoingWebhookEventContent::Mandate {
payment_method_id: mandate_payload.payment_method_id.clone(),
mandate_id: mandate_payload.mandate_id.clone(),
content: masking::masked_serialize(&mandate_payload)
.unwrap_or(serde_json::json!({"error":"failed to serialize"})),
}),
#[cfg(feature = "payouts")]
Self::PayoutDetails(payout_payload) => Some(OutgoingWebhookEventContent::Payout {
payout_id: payout_payload.payout_id.clone(),
content: masking::masked_serialize(&payout_payload)
.unwrap_or(serde_json::json!({"error":"failed to serialize"})),
}),
}
}
}
impl OutgoingWebhookEvent {
#[allow(clippy::too_many_arguments)]
pub fn new(
tenant_id: common_utils::id_type::TenantId,
merchant_id: common_utils::id_type::MerchantId,
event_id: String,
event_type: OutgoingWebhookEventType,
content: Option<OutgoingWebhookEventContent>,
error: Option<Value>,
initial_attempt_id: Option<String>,
status_code: Option<u16>,
delivery_attempt: Option<WebhookDeliveryAttempt>,
) -> Self {
Self {
tenant_id,
merchant_id,
event_id,
event_type,
content,
is_error: error.is_some(),
error,
created_at_timestamp: OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000,
initial_attempt_id,
status_code,
delivery_attempt,
}
}
}
impl KafkaMessage for OutgoingWebhookEvent {
fn event_type(&self) -> EventType {
EventType::OutgoingWebhookLogs
}
fn key(&self) -> String {
self.event_id.clone()
}
}
| 1,613 | 1,224 |
hyperswitch | crates/router/src/events/audit_events.rs | .rs | use api_models::payments::Amount;
use common_utils::types::MinorUnit;
use diesel_models::fraud_check::FraudCheck;
use events::{Event, EventInfo};
use serde::Serialize;
use time::PrimitiveDateTime;
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "event_type")]
pub enum AuditEventType {
Error {
error_message: String,
},
PaymentCreated,
ConnectorDecided,
ConnectorCalled,
RefundCreated,
RefundSuccess,
RefundFail,
PaymentConfirm {
client_src: Option<String>,
client_ver: Option<String>,
frm_message: Box<Option<FraudCheck>>,
},
PaymentCancelled {
cancellation_reason: Option<String>,
},
PaymentCapture {
capture_amount: Option<MinorUnit>,
multiple_capture_count: Option<i16>,
},
PaymentUpdate {
amount: Amount,
},
PaymentApprove,
PaymentCreate,
PaymentStatus,
PaymentCompleteAuthorize,
PaymentReject {
error_code: Option<String>,
error_message: Option<String>,
},
}
#[derive(Debug, Clone, Serialize)]
pub struct AuditEvent {
#[serde(flatten)]
event_type: AuditEventType,
#[serde(with = "common_utils::custom_serde::iso8601")]
created_at: PrimitiveDateTime,
}
impl AuditEvent {
pub fn new(event_type: AuditEventType) -> Self {
Self {
event_type,
created_at: common_utils::date_time::now(),
}
}
}
impl Event for AuditEvent {
type EventType = super::EventType;
fn timestamp(&self) -> PrimitiveDateTime {
self.created_at
}
fn identifier(&self) -> String {
let event_type = match &self.event_type {
AuditEventType::Error { .. } => "error",
AuditEventType::PaymentCreated => "payment_created",
AuditEventType::PaymentConfirm { .. } => "payment_confirm",
AuditEventType::ConnectorDecided => "connector_decided",
AuditEventType::ConnectorCalled => "connector_called",
AuditEventType::PaymentCapture { .. } => "payment_capture",
AuditEventType::RefundCreated => "refund_created",
AuditEventType::RefundSuccess => "refund_success",
AuditEventType::RefundFail => "refund_fail",
AuditEventType::PaymentCancelled { .. } => "payment_cancelled",
AuditEventType::PaymentUpdate { .. } => "payment_update",
AuditEventType::PaymentApprove => "payment_approve",
AuditEventType::PaymentCreate => "payment_create",
AuditEventType::PaymentStatus => "payment_status",
AuditEventType::PaymentCompleteAuthorize => "payment_complete_authorize",
AuditEventType::PaymentReject { .. } => "payment_rejected",
};
format!(
"{event_type}-{}",
self.timestamp().assume_utc().unix_timestamp_nanos()
)
}
fn class(&self) -> Self::EventType {
super::EventType::AuditEvent
}
}
impl EventInfo for AuditEvent {
type Data = Self;
fn data(&self) -> error_stack::Result<Self::Data, events::EventsError> {
Ok(self.clone())
}
fn key(&self) -> String {
"event".to_string()
}
}
| 685 | 1,225 |
hyperswitch | crates/router/src/events/api_logs.rs | .rs | use actix_web::HttpRequest;
pub use common_utils::events::{ApiEventMetric, ApiEventsType};
use common_utils::impl_api_event_type;
use router_env::{tracing_actix_web::RequestId, types::FlowMetric};
use serde::Serialize;
use time::OffsetDateTime;
use super::EventType;
#[cfg(feature = "dummy_connector")]
use crate::routes::dummy_connector::types::{
DummyConnectorPaymentCompleteRequest, DummyConnectorPaymentConfirmRequest,
DummyConnectorPaymentRequest, DummyConnectorPaymentResponse,
DummyConnectorPaymentRetrieveRequest, DummyConnectorRefundRequest,
DummyConnectorRefundResponse, DummyConnectorRefundRetrieveRequest,
};
use crate::{
core::payments::PaymentsRedirectResponseData,
services::{authentication::AuthenticationType, kafka::KafkaMessage},
types::api::{
AttachEvidenceRequest, Config, ConfigUpdate, CreateFileRequest, DisputeId, FileId, PollId,
},
};
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct ApiEvent {
tenant_id: common_utils::id_type::TenantId,
merchant_id: Option<common_utils::id_type::MerchantId>,
api_flow: String,
created_at_timestamp: i128,
request_id: String,
latency: u128,
status_code: i64,
#[serde(flatten)]
auth_type: AuthenticationType,
request: String,
user_agent: Option<String>,
ip_addr: Option<String>,
url_path: String,
response: Option<String>,
error: Option<serde_json::Value>,
#[serde(flatten)]
event_type: ApiEventsType,
hs_latency: Option<u128>,
http_method: String,
}
impl ApiEvent {
#[allow(clippy::too_many_arguments)]
pub fn new(
tenant_id: common_utils::id_type::TenantId,
merchant_id: Option<common_utils::id_type::MerchantId>,
api_flow: &impl FlowMetric,
request_id: &RequestId,
latency: u128,
status_code: i64,
request: serde_json::Value,
response: Option<serde_json::Value>,
hs_latency: Option<u128>,
auth_type: AuthenticationType,
error: Option<serde_json::Value>,
event_type: ApiEventsType,
http_req: &HttpRequest,
http_method: &http::Method,
) -> Self {
Self {
tenant_id,
merchant_id,
api_flow: api_flow.to_string(),
created_at_timestamp: OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000,
request_id: request_id.as_hyphenated().to_string(),
latency,
status_code,
request: request.to_string(),
response: response.map(|resp| resp.to_string()),
auth_type,
error,
ip_addr: http_req
.connection_info()
.realip_remote_addr()
.map(ToOwned::to_owned),
user_agent: http_req
.headers()
.get("user-agent")
.and_then(|user_agent_value| user_agent_value.to_str().ok().map(ToOwned::to_owned)),
url_path: http_req.path().to_string(),
event_type,
hs_latency,
http_method: http_method.to_string(),
}
}
}
impl KafkaMessage for ApiEvent {
fn event_type(&self) -> EventType {
EventType::ApiLogs
}
fn key(&self) -> String {
self.request_id.clone()
}
}
impl_api_event_type!(
Miscellaneous,
(
Config,
CreateFileRequest,
FileId,
AttachEvidenceRequest,
ConfigUpdate
)
);
#[cfg(feature = "dummy_connector")]
impl_api_event_type!(
Miscellaneous,
(
DummyConnectorPaymentCompleteRequest,
DummyConnectorPaymentRequest,
DummyConnectorPaymentResponse,
DummyConnectorPaymentRetrieveRequest,
DummyConnectorPaymentConfirmRequest,
DummyConnectorRefundRetrieveRequest,
DummyConnectorRefundResponse,
DummyConnectorRefundRequest
)
);
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentsRedirectResponseData {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::PaymentRedirectionResponse {
connector: self.connector.clone(),
payment_id: match &self.resource_id {
api_models::payments::PaymentIdType::PaymentIntentId(id) => Some(id.clone()),
_ => None,
},
})
}
}
#[cfg(feature = "v2")]
impl ApiEventMetric for PaymentsRedirectResponseData {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::PaymentRedirectionResponse {
payment_id: self.payment_id.clone(),
})
}
}
impl ApiEventMetric for DisputeId {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Dispute {
dispute_id: self.dispute_id.clone(),
})
}
}
impl ApiEventMetric for PollId {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Poll {
poll_id: self.poll_id.clone(),
})
}
}
| 1,129 | 1,226 |
hyperswitch | crates/router/src/events/connector_api_logs.rs | .rs | pub use hyperswitch_interfaces::events::connector_api_logs::ConnectorEvent;
use super::EventType;
use crate::services::kafka::KafkaMessage;
impl KafkaMessage for ConnectorEvent {
fn event_type(&self) -> EventType {
EventType::ConnectorApiLogs
}
fn key(&self) -> String {
self.request_id.clone()
}
}
| 76 | 1,227 |
hyperswitch | crates/router/src/routes/apple_pay_certificates_migration.rs | .rs | 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
}
| 193 | 1,228 |
hyperswitch | crates/router/src/routes/payment_link.rs | .rs | use actix_web::{web, Responder};
use router_env::{instrument, tracing, Flow};
use crate::{
core::{api_locking, payment_link::*},
services::{api, authentication as auth},
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
#[utoipa::path(
get,
path = "/payment_link/{payment_link_id}",
params(
("payment_link_id" = String, Path, description = "The identifier for payment link")
),
request_body=RetrievePaymentLinkRequest,
responses(
(status = 200, description = "Gets details regarding payment link", body = RetrievePaymentLinkResponse),
(status = 404, description = "No payment link found")
),
tag = "Payments",
operation_id = "Retrieve a Payment Link",
security(("api_key" = []), ("publishable_key" = []))
)]
#[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 (auth_type, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload) {
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, _, _| {
initiate_payment_link_flow(
state,
auth.merchant_account,
auth.key_store,
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, _, _| {
initiate_secure_payment_link_flow(
state,
auth.merchant_account,
auth.key_store,
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
#[utoipa::path(
get,
path = "/payment_link/list",
params(
("limit" = Option<i64>, Query, description = "The maximum number of payment_link Objects to include in the response"),
("connector" = Option<String>, Query, description = "The connector linked to payment_link"),
("created_time" = Option<PrimitiveDateTime>, Query, description = "The time at which payment_link is created"),
("created_time.lt" = Option<PrimitiveDateTime>, Query, description = "Time less than the payment_link created time"),
("created_time.gt" = Option<PrimitiveDateTime>, Query, description = "Time greater than the payment_link created time"),
("created_time.lte" = Option<PrimitiveDateTime>, Query, description = "Time less than or equals to the payment_link created time"),
("created_time.gte" = Option<PrimitiveDateTime>, Query, description = "Time greater than or equals to the payment_link created time"),
),
responses(
(status = 200, description = "The payment link list was retrieved successfully"),
(status = 401, description = "Unauthorized request")
),
tag = "Payment Link",
operation_id = "List all Payment links",
security(("api_key" = []))
)]
#[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),
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, _, _| {
get_payment_link_status(
state,
auth.merchant_account,
auth.key_store,
payload.merchant_id.clone(),
payload.payment_id.clone(),
)
},
&crate::services::authentication::MerchantIdAuth(merchant_id),
api_locking::LockAction::NotApplicable,
))
.await
}
| 1,564 | 1,229 |
hyperswitch | crates/router/src/routes/metrics.rs | .rs | pub mod bg_metrics_collector;
pub mod request;
pub mod utils;
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);
counter_metric!(REQUEST_STATUS, GLOBAL_METER);
histogram_metric_f64!(REQUEST_TIME, GLOBAL_METER);
histogram_metric_f64!(EXTERNAL_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!(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_CONNECTION_CLOSED, GLOBAL_METER);
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);
| 1,458 | 1,230 |
hyperswitch | crates/router/src/routes/disputes.rs | .rs | use actix_multipart::Multipart;
use actix_web::{web, HttpRequest, HttpResponse};
use api_models::disputes as dispute_models;
use router_env::{instrument, tracing, Flow};
use crate::{core::api_locking, services::authorization::permissions::Permission};
pub mod utils;
use super::app::AppState;
use crate::{
core::disputes,
services::{api, authentication as auth},
types::api::disputes as dispute_types,
};
#[cfg(feature = "v1")]
/// Disputes - Retrieve Dispute
#[utoipa::path(
get,
path = "/disputes/{dispute_id}",
params(
("dispute_id" = String, Path, description = "The identifier for dispute")
),
responses(
(status = 200, description = "The dispute was retrieved successfully", body = DisputeResponse),
(status = 404, description = "Dispute does not exist in our records")
),
tag = "Disputes",
operation_id = "Retrieve a Dispute",
security(("api_key" = []))
)]
#[instrument(skip_all, fields(flow = ?Flow::DisputesRetrieve))]
pub async fn retrieve_dispute(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::DisputesRetrieve;
let dispute_id = dispute_types::DisputeId {
dispute_id: path.into_inner(),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
dispute_id,
|state, auth: auth::AuthenticationData, req, _| {
disputes::retrieve_dispute(state, auth.merchant_account, auth.profile_id, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::ProfileDisputeRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Disputes - List Disputes
#[utoipa::path(
get,
path = "/disputes/list",
params(
("limit" = Option<i64>, Query, description = "The maximum number of Dispute Objects to include in the response"),
("dispute_status" = Option<DisputeStatus>, Query, description = "The status of dispute"),
("dispute_stage" = Option<DisputeStage>, Query, description = "The stage of dispute"),
("reason" = Option<String>, Query, description = "The reason for dispute"),
("connector" = Option<String>, Query, description = "The connector linked to dispute"),
("received_time" = Option<PrimitiveDateTime>, Query, description = "The time at which dispute is received"),
("received_time.lt" = Option<PrimitiveDateTime>, Query, description = "Time less than the dispute received time"),
("received_time.gt" = Option<PrimitiveDateTime>, Query, description = "Time greater than the dispute received time"),
("received_time.lte" = Option<PrimitiveDateTime>, Query, description = "Time less than or equals to the dispute received time"),
("received_time.gte" = Option<PrimitiveDateTime>, Query, description = "Time greater than or equals to the dispute received time"),
),
responses(
(status = 200, description = "The dispute list was retrieved successfully", body = Vec<DisputeResponse>),
(status = 401, description = "Unauthorized request")
),
tag = "Disputes",
operation_id = "List Disputes",
security(("api_key" = []))
)]
#[instrument(skip_all, fields(flow = ?Flow::DisputesList))]
pub async fn retrieve_disputes_list(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<dispute_models::DisputeListGetConstraints>,
) -> HttpResponse {
let flow = Flow::DisputesList;
let payload = query.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
disputes::retrieve_disputes_list(state, auth.merchant_account, None, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::MerchantDisputeRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// Disputes - List Disputes for The Given Business Profiles
#[utoipa::path(
get,
path = "/disputes/profile/list",
params(
("limit" = Option<i64>, Query, description = "The maximum number of Dispute Objects to include in the response"),
("dispute_status" = Option<DisputeStatus>, Query, description = "The status of dispute"),
("dispute_stage" = Option<DisputeStage>, Query, description = "The stage of dispute"),
("reason" = Option<String>, Query, description = "The reason for dispute"),
("connector" = Option<String>, Query, description = "The connector linked to dispute"),
("received_time" = Option<PrimitiveDateTime>, Query, description = "The time at which dispute is received"),
("received_time.lt" = Option<PrimitiveDateTime>, Query, description = "Time less than the dispute received time"),
("received_time.gt" = Option<PrimitiveDateTime>, Query, description = "Time greater than the dispute received time"),
("received_time.lte" = Option<PrimitiveDateTime>, Query, description = "Time less than or equals to the dispute received time"),
("received_time.gte" = Option<PrimitiveDateTime>, Query, description = "Time greater than or equals to the dispute received time"),
),
responses(
(status = 200, description = "The dispute list was retrieved successfully", body = Vec<DisputeResponse>),
(status = 401, description = "Unauthorized request")
),
tag = "Disputes",
operation_id = "List Disputes for The given Business Profiles",
security(("api_key" = []))
)]
#[instrument(skip_all, fields(flow = ?Flow::DisputesList))]
pub async fn retrieve_disputes_list_profile(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Query<dispute_models::DisputeListGetConstraints>,
) -> HttpResponse {
let flow = Flow::DisputesList;
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
disputes::retrieve_disputes_list(
state,
auth.merchant_account,
auth.profile_id.map(|profile_id| vec![profile_id]),
req,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::ProfileDisputeRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// Disputes - Disputes Filters
#[utoipa::path(
get,
path = "/disputes/filter",
responses(
(status = 200, description = "List of filters", body = DisputeListFilters),
),
tag = "Disputes",
operation_id = "List all filters for disputes",
security(("api_key" = []))
)]
#[instrument(skip_all, fields(flow = ?Flow::DisputesFilters))]
pub async fn get_disputes_filters(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
let flow = Flow::DisputesFilters;
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
|state, auth: auth::AuthenticationData, _, _| {
disputes::get_filters_for_disputes(state, auth.merchant_account, None)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::MerchantDisputeRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// Disputes - Disputes Filters Profile
#[utoipa::path(
get,
path = "/disputes/profile/filter",
responses(
(status = 200, description = "List of filters", body = DisputeListFilters),
),
tag = "Disputes",
operation_id = "List all filters for disputes",
security(("api_key" = []))
)]
#[instrument(skip_all, fields(flow = ?Flow::DisputesFilters))]
pub async fn get_disputes_filters_profile(
state: web::Data<AppState>,
req: HttpRequest,
) -> HttpResponse {
let flow = Flow::DisputesFilters;
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
|state, auth: auth::AuthenticationData, _, _| {
disputes::get_filters_for_disputes(
state,
auth.merchant_account,
auth.profile_id.map(|profile_id| vec![profile_id]),
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::ProfileDisputeRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// Disputes - Accept Dispute
#[utoipa::path(
get,
path = "/disputes/accept/{dispute_id}",
params(
("dispute_id" = String, Path, description = "The identifier for dispute")
),
responses(
(status = 200, description = "The dispute was accepted successfully", body = DisputeResponse),
(status = 404, description = "Dispute does not exist in our records")
),
tag = "Disputes",
operation_id = "Accept a Dispute",
security(("api_key" = []))
)]
#[instrument(skip_all, fields(flow = ?Flow::DisputesRetrieve))]
pub async fn accept_dispute(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::DisputesRetrieve;
let dispute_id = dispute_types::DisputeId {
dispute_id: path.into_inner(),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
dispute_id,
|state, auth: auth::AuthenticationData, req, _| {
disputes::accept_dispute(
state,
auth.merchant_account,
auth.profile_id,
auth.key_store,
req,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::ProfileDisputeWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// Disputes - Submit Dispute Evidence
#[utoipa::path(
post,
path = "/disputes/evidence",
request_body=AcceptDisputeRequestData,
responses(
(status = 200, description = "The dispute evidence submitted successfully", body = AcceptDisputeResponse),
(status = 404, description = "Dispute does not exist in our records")
),
tag = "Disputes",
operation_id = "Submit Dispute Evidence",
security(("api_key" = []))
)]
#[instrument(skip_all, fields(flow = ?Flow::DisputesEvidenceSubmit))]
pub async fn submit_dispute_evidence(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<dispute_models::SubmitEvidenceRequest>,
) -> HttpResponse {
let flow = Flow::DisputesEvidenceSubmit;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| {
disputes::submit_evidence(
state,
auth.merchant_account,
auth.profile_id,
auth.key_store,
req,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::ProfileDisputeWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// Disputes - Attach Evidence to Dispute
///
/// To attach an evidence file to dispute
#[utoipa::path(
put,
path = "/disputes/evidence",
request_body=MultipartRequestWithFile,
responses(
(status = 200, description = "Evidence attached to dispute", body = CreateFileResponse),
(status = 400, description = "Bad Request")
),
tag = "Disputes",
operation_id = "Attach Evidence to Dispute",
security(("api_key" = []))
)]
#[instrument(skip_all, fields(flow = ?Flow::AttachDisputeEvidence))]
pub async fn attach_dispute_evidence(
state: web::Data<AppState>,
req: HttpRequest,
payload: Multipart,
) -> HttpResponse {
let flow = Flow::AttachDisputeEvidence;
//Get attach_evidence_request from the multipart request
let attach_evidence_request_result = utils::get_attach_evidence_request(payload).await;
let attach_evidence_request = match attach_evidence_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,
attach_evidence_request,
|state, auth: auth::AuthenticationData, req, _| {
disputes::attach_evidence(
state,
auth.merchant_account,
auth.profile_id,
auth.key_store,
req,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::ProfileDisputeWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// Disputes - Retrieve Dispute
#[utoipa::path(
get,
path = "/disputes/evidence/{dispute_id}",
params(
("dispute_id" = String, Path, description = "The identifier for dispute")
),
responses(
(status = 200, description = "The dispute evidence was retrieved successfully", body = DisputeResponse),
(status = 404, description = "Dispute does not exist in our records")
),
tag = "Disputes",
operation_id = "Retrieve a Dispute Evidence",
security(("api_key" = []))
)]
#[instrument(skip_all, fields(flow = ?Flow::RetrieveDisputeEvidence))]
pub async fn retrieve_dispute_evidence(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::RetrieveDisputeEvidence;
let dispute_id = dispute_types::DisputeId {
dispute_id: path.into_inner(),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
dispute_id,
|state, auth: auth::AuthenticationData, req, _| {
disputes::retrieve_dispute_evidence(state, auth.merchant_account, auth.profile_id, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::ProfileDisputeRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Disputes - Delete Evidence attached to a Dispute
///
/// To delete an evidence file attached to a dispute
#[utoipa::path(
put,
path = "/disputes/evidence",
request_body=DeleteEvidenceRequest,
responses(
(status = 200, description = "Evidence deleted from a dispute"),
(status = 400, description = "Bad Request")
),
tag = "Disputes",
operation_id = "Delete Evidence attached to a Dispute",
security(("api_key" = []))
)]
#[instrument(skip_all, fields(flow = ?Flow::DeleteDisputeEvidence))]
pub async fn delete_dispute_evidence(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<dispute_models::DeleteEvidenceRequest>,
) -> HttpResponse {
let flow = Flow::DeleteDisputeEvidence;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| {
disputes::delete_evidence(state, auth.merchant_account, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::ProfileDisputeWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::DisputesAggregate))]
pub async fn get_disputes_aggregate(
state: web::Data<AppState>,
req: HttpRequest,
query_param: web::Query<common_utils::types::TimeRange>,
) -> HttpResponse {
let flow = Flow::DisputesAggregate;
let query_param = query_param.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
query_param,
|state, auth: auth::AuthenticationData, req, _| {
disputes::get_aggregates_for_disputes(state, auth.merchant_account, None, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::MerchantDisputeRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::DisputesAggregate))]
pub async fn get_disputes_aggregate_profile(
state: web::Data<AppState>,
req: HttpRequest,
query_param: web::Query<common_utils::types::TimeRange>,
) -> HttpResponse {
let flow = Flow::DisputesAggregate;
let query_param = query_param.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
query_param,
|state, auth: auth::AuthenticationData, req, _| {
disputes::get_aggregates_for_disputes(
state,
auth.merchant_account,
auth.profile_id.map(|profile_id| vec![profile_id]),
req,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::ProfileDisputeRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
| 4,299 | 1,231 |
hyperswitch | crates/router/src/routes/connector_onboarding.rs | .rs | 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
}
| 463 | 1,232 |
hyperswitch | crates/router/src/routes/cache.rs | .rs | use actix_web::{web, HttpRequest, Responder};
use router_env::{instrument, tracing, Flow};
use super::AppState;
use crate::{
core::{api_locking, cache},
services::{api, authentication as auth},
};
#[instrument(skip_all)]
pub async fn invalidate(
state: web::Data<AppState>,
req: HttpRequest,
key: web::Path<String>,
) -> impl Responder {
let flow = Flow::CacheInvalidate;
let key = key.into_inner().to_owned();
api::server_wrap(
flow,
state,
&req,
&key,
|state, _, key, _| cache::invalidate(state, key),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
)
.await
}
| 170 | 1,233 |
hyperswitch | crates/router/src/routes/api_keys.rs | .rs | 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::AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(merchant_id.clone()),
&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::AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(merchant_id.clone()),
&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::AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(merchant_id.clone()),
&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, key_id),
auth::auth_type(
&auth::AdminApiAuth,
&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::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, key_id),
auth::auth_type(
&auth::V2AdminApiAuth,
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
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::AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(merchant_id.clone()),
&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
}
| 2,458 | 1,234 |
hyperswitch | crates/router/src/routes/relay.rs | .rs | 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, _| {
relay::relay_flow_decider(
state,
auth.merchant_account,
#[cfg(feature = "v1")]
auth.profile_id,
#[cfg(feature = "v2")]
Some(auth.profile.get_id().clone()),
auth.key_store,
req,
)
},
&auth::HeaderAuth(auth::ApiKeyAuth),
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, _| {
relay::relay_retrieve(
state,
auth.merchant_account,
#[cfg(feature = "v1")]
auth.profile_id,
#[cfg(feature = "v2")]
Some(auth.profile.get_id().clone()),
auth.key_store,
req,
)
},
&auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
))
.await
}
| 527 | 1,235 |
hyperswitch | crates/router/src/routes/currency.rs | .rs | 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),
&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 = ¶ms.to_currency;
let from_currency = ¶ms.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),
&auth::DashboardNoPermissionAuth,
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
| 385 | 1,236 |
hyperswitch | crates/router/src/routes/user.rs | .rs | 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 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
}
| 6,782 | 1,237 |
hyperswitch | crates/router/src/routes/verify_connector.rs | .rs | 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
}
| 231 | 1,238 |
hyperswitch | crates/router/src/routes/payments.rs | .rs | use crate::{
core::api_locking::{self, GetLockingInput},
services::authorization::permissions::Permission,
};
pub mod helpers;
use actix_web::{web, Responder};
use error_stack::report;
use hyperswitch_domain_models::payments::HeaderPayload;
use masking::PeekInterface;
use router_env::{env, instrument, logger, tracing, types, Flow};
use super::app::ReqState;
use crate::{
self as app,
core::{
errors::{self, http_not_implemented},
payments::{self, PaymentRedirectFlow},
},
routes::lock_utils,
services::{api, authentication as auth},
types::{
api::{
self as api_types, enums as api_enums,
payments::{self as payment_types, PaymentIdTypeExt},
},
domain,
transformers::ForeignTryFrom,
},
};
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsCreate, payment_id))]
pub async fn payments_create(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsRequest>,
) -> impl Responder {
let flow = Flow::PaymentsCreate;
let mut payload = json_payload.into_inner();
if let Some(api_enums::CaptureMethod::Scheduled) = payload.capture_method {
return http_not_implemented();
};
if let Err(err) = get_or_generate_payment_id(&mut payload) {
return api::log_and_return_error_response(err);
}
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
tracing::Span::current().record(
"payment_id",
payload
.payment_id
.as_ref()
.map(|payment_id_type| payment_id_type.get_payment_intent_id())
.transpose()
.unwrap_or_default()
.as_ref()
.map(|id| id.get_string_repr())
.unwrap_or_default(),
);
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
authorize_verify_select::<_>(
payments::PaymentCreate,
state,
req_state,
auth.merchant_account,
auth.profile_id,
auth.key_store,
header_payload.clone(),
req,
api::AuthFlow::Merchant,
auth.platform_merchant_account,
)
},
match env::which() {
env::Env::Production => &auth::HeaderAuth(auth::ApiKeyAuth),
_ => auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::ProfilePaymentWrite,
},
req.headers(),
),
},
locking_action,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsCreateIntent, payment_id))]
pub async fn payments_create_intent(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsCreateIntentRequest>,
) -> impl Responder {
use hyperswitch_domain_models::payments::PaymentIntentData;
let flow = Flow::PaymentsCreateIntent;
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
let global_payment_id =
common_utils::id_type::GlobalPaymentId::generate(&state.conf.cell_information.id);
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, req, req_state| {
payments::payments_intent_core::<
api_types::PaymentCreateIntent,
payment_types::PaymentsIntentResponse,
_,
_,
PaymentIntentData<api_types::PaymentCreateIntent>,
>(
state,
req_state,
auth.merchant_account,
auth.profile,
auth.key_store,
payments::operations::PaymentIntentCreate,
req,
global_payment_id.clone(),
header_payload.clone(),
auth.platform_merchant_account,
)
},
match env::which() {
env::Env::Production => &auth::V2ApiKeyAuth,
_ => auth::auth_type(
&auth::V2ApiKeyAuth,
&auth::JWTAuth {
permission: Permission::ProfilePaymentWrite,
},
req.headers(),
),
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsGetIntent, payment_id))]
pub async fn payments_get_intent(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
path: web::Path<common_utils::id_type::GlobalPaymentId>,
) -> impl Responder {
use api_models::payments::PaymentsGetIntentRequest;
use hyperswitch_domain_models::payments::PaymentIntentData;
let flow = Flow::PaymentsGetIntent;
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
let payload = PaymentsGetIntentRequest {
id: path.into_inner(),
};
let global_payment_id = payload.id.clone();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
payments::payments_intent_core::<
api_types::PaymentGetIntent,
payment_types::PaymentsIntentResponse,
_,
_,
PaymentIntentData<api_types::PaymentGetIntent>,
>(
state,
req_state,
auth.merchant_account,
auth.profile,
auth.key_store,
payments::operations::PaymentGetIntent,
req,
global_payment_id.clone(),
header_payload.clone(),
auth.platform_merchant_account,
)
},
&auth::V2ApiKeyAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsCreateAndConfirmIntent, payment_id))]
pub async fn payments_create_and_confirm_intent(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsRequest>,
) -> impl Responder {
let flow = Flow::PaymentsCreateAndConfirmIntent;
let header_payload = match 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,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, request, req_state| {
payments::payments_create_and_confirm_intent(
state,
req_state,
auth.merchant_account,
auth.profile,
auth.key_store,
request,
header_payload.clone(),
auth.platform_merchant_account,
)
},
match env::which() {
env::Env::Production => &auth::V2ApiKeyAuth,
_ => auth::auth_type(
&auth::V2ApiKeyAuth,
&auth::JWTAuth {
permission: Permission::ProfilePaymentWrite,
},
req.headers(),
),
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsUpdateIntent, payment_id))]
pub async fn payments_update_intent(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsUpdateIntentRequest>,
path: web::Path<common_utils::id_type::GlobalPaymentId>,
) -> impl Responder {
use hyperswitch_domain_models::payments::PaymentIntentData;
let flow = Flow::PaymentsUpdateIntent;
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId {
global_payment_id: path.into_inner(),
payload: json_payload.into_inner(),
};
let global_payment_id = internal_payload.global_payment_id.clone();
Box::pin(api::server_wrap(
flow,
state,
&req,
internal_payload,
|state, auth: auth::AuthenticationData, req, req_state| {
payments::payments_intent_core::<
api_types::PaymentUpdateIntent,
payment_types::PaymentsIntentResponse,
_,
_,
PaymentIntentData<api_types::PaymentUpdateIntent>,
>(
state,
req_state,
auth.merchant_account,
auth.profile,
auth.key_store,
payments::operations::PaymentUpdateIntent,
req.payload,
global_payment_id.clone(),
header_payload.clone(),
auth.platform_merchant_account,
)
},
&auth::V2ApiKeyAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip(state, req), fields(flow = ?Flow::PaymentsStart, payment_id))]
pub async fn payments_start(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
path: web::Path<(
common_utils::id_type::PaymentId,
common_utils::id_type::MerchantId,
String,
)>,
) -> impl Responder {
let flow = Flow::PaymentsStart;
let (payment_id, merchant_id, attempt_id) = path.into_inner();
let payload = payment_types::PaymentsStartRequest {
payment_id: payment_id.clone(),
merchant_id: merchant_id.clone(),
attempt_id: attempt_id.clone(),
};
let locking_action = payload.get_locking_input(flow.clone());
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
payments::payments_core::<
api_types::Authorize,
payment_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::Authorize>,
>(
state,
req_state,
auth.merchant_account,
auth.profile_id,
auth.key_store,
payments::operations::PaymentStart,
req,
api::AuthFlow::Client,
payments::CallConnectorAction::Trigger,
None,
HeaderPayload::default(),
None,
)
},
&auth::MerchantIdAuth(merchant_id),
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip(state, req), fields(flow, payment_id))]
pub async fn payments_retrieve(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
path: web::Path<common_utils::id_type::PaymentId>,
json_payload: web::Query<payment_types::PaymentRetrieveBody>,
) -> impl Responder {
let flow = match json_payload.force_sync {
Some(true) => Flow::PaymentsRetrieveForceSync,
_ => Flow::PaymentsRetrieve,
};
let payment_id = path.into_inner();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
let payload = payment_types::PaymentsRetrieveRequest {
resource_id: payment_types::PaymentIdType::PaymentIntentId(payment_id),
merchant_id: json_payload.merchant_id.clone(),
force_sync: json_payload.force_sync.unwrap_or(false),
client_secret: json_payload.client_secret.clone(),
expand_attempts: json_payload.expand_attempts,
expand_captures: json_payload.expand_captures,
..Default::default()
};
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
tracing::Span::current().record("flow", flow.to_string());
let (auth_type, auth_flow) =
match auth::check_client_secret_and_get_auth(req.headers(), &payload) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(report!(err)),
};
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
payments::payments_core::<
api_types::PSync,
payment_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::PSync>,
>(
state,
req_state,
auth.merchant_account,
auth.profile_id,
auth.key_store,
payments::PaymentStatus,
req,
auth_flow,
payments::CallConnectorAction::Trigger,
None,
header_payload.clone(),
auth.platform_merchant_account,
)
},
auth::auth_type(
&*auth_type,
&auth::JWTAuth {
permission: Permission::ProfilePaymentRead,
},
req.headers(),
),
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip(state, req), fields(flow, payment_id))]
pub async fn payments_retrieve_with_gateway_creds(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentRetrieveBodyWithCredentials>,
) -> impl Responder {
let (auth_type, _auth_flow) = match auth::get_auth_type_and_flow(req.headers()) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(report!(err)),
};
tracing::Span::current().record("payment_id", json_payload.payment_id.get_string_repr());
let payload = payment_types::PaymentsRetrieveRequest {
resource_id: payment_types::PaymentIdType::PaymentIntentId(json_payload.payment_id.clone()),
merchant_id: json_payload.merchant_id.clone(),
force_sync: json_payload.force_sync.unwrap_or(false),
merchant_connector_details: json_payload.merchant_connector_details.clone(),
..Default::default()
};
let flow = match json_payload.force_sync {
Some(true) => Flow::PaymentsRetrieveForceSync,
_ => Flow::PaymentsRetrieve,
};
tracing::Span::current().record("flow", flow.to_string());
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
payments::payments_core::<
api_types::PSync,
payment_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::PSync>,
>(
state,
req_state,
auth.merchant_account,
auth.profile_id,
auth.key_store,
payments::PaymentStatus,
req,
api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
HeaderPayload::default(),
auth.platform_merchant_account,
)
},
&*auth_type,
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsUpdate, payment_id))]
pub async fn payments_update(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder {
let flow = Flow::PaymentsUpdate;
let mut payload = json_payload.into_inner();
if let Some(api_enums::CaptureMethod::Scheduled) = payload.capture_method {
return http_not_implemented();
};
let payment_id = path.into_inner();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
payload.payment_id = Some(payment_types::PaymentIdType::PaymentIntentId(payment_id));
let (auth_type, auth_flow) = match auth::get_auth_type_and_flow(req.headers()) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(report!(err)),
};
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
authorize_verify_select::<_>(
payments::PaymentUpdate,
state,
req_state,
auth.merchant_account,
auth.profile_id,
auth.key_store,
HeaderPayload::default(),
req,
auth_flow,
auth.platform_merchant_account,
)
},
&*auth_type,
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsPostSessionTokens, payment_id))]
pub async fn payments_post_session_tokens(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsPostSessionTokensRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder {
let flow = Flow::PaymentsPostSessionTokens;
let payment_id = path.into_inner();
let payload = payment_types::PaymentsPostSessionTokensRequest {
payment_id,
..json_payload.into_inner()
};
tracing::Span::current().record("payment_id", payload.payment_id.get_string_repr());
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth, req, req_state| {
payments::payments_core::<
api_types::PostSessionTokens,
payment_types::PaymentsPostSessionTokensResponse,
_,
_,
_,
payments::PaymentData<api_types::PostSessionTokens>,
>(
state,
req_state,
auth.merchant_account,
auth.profile_id,
auth.key_store,
payments::PaymentPostSessionTokens,
req,
api::AuthFlow::Client,
payments::CallConnectorAction::Trigger,
None,
header_payload.clone(),
None,
)
},
&auth::PublishableKeyAuth,
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsConfirm, payment_id))]
pub async fn payments_confirm(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder {
let flow = Flow::PaymentsConfirm;
let mut payload = json_payload.into_inner();
if let Some(api_enums::CaptureMethod::Scheduled) = payload.capture_method {
return http_not_implemented();
};
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
if let Err(err) = helpers::populate_browser_info(&req, &mut payload, &header_payload) {
return api::log_and_return_error_response(err);
}
let payment_id = path.into_inner();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
payload.payment_id = Some(payment_types::PaymentIdType::PaymentIntentId(payment_id));
payload.confirm = Some(true);
let (auth_type, auth_flow) =
match auth::check_client_secret_and_get_auth(req.headers(), &payload) {
Ok(auth) => auth,
Err(e) => return api::log_and_return_error_response(e),
};
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
authorize_verify_select::<_>(
payments::PaymentConfirm,
state,
req_state,
auth.merchant_account,
auth.profile_id,
auth.key_store,
header_payload.clone(),
req,
auth_flow,
auth.platform_merchant_account,
)
},
&*auth_type,
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsCapture, payment_id))]
pub async fn payments_capture(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsCaptureRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder {
let payment_id = path.into_inner();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
let flow = Flow::PaymentsCapture;
let payload = payment_types::PaymentsCaptureRequest {
payment_id,
..json_payload.into_inner()
};
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, payload, req_state| {
payments::payments_core::<
api_types::Capture,
payment_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::Capture>,
>(
state,
req_state,
auth.merchant_account,
auth.profile_id,
auth.key_store,
payments::PaymentCapture,
payload,
api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
HeaderPayload::default(),
auth.platform_merchant_account,
)
},
&auth::HeaderAuth(auth::ApiKeyAuth),
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::SessionUpdateTaxCalculation, payment_id))]
pub async fn payments_dynamic_tax_calculation(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsDynamicTaxCalculationRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder {
let flow = Flow::SessionUpdateTaxCalculation;
let payment_id = path.into_inner();
let payload = payment_types::PaymentsDynamicTaxCalculationRequest {
payment_id,
..json_payload.into_inner()
};
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(error) => {
logger::error!(
?error,
"Failed to get headers in payments_connector_session"
);
HeaderPayload::default()
}
};
tracing::Span::current().record("payment_id", payload.payment_id.get_string_repr());
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, payload, req_state| {
payments::payments_core::<
api_types::SdkSessionUpdate,
payment_types::PaymentsDynamicTaxCalculationResponse,
_,
_,
_,
_,
>(
state,
req_state,
auth.merchant_account,
auth.profile_id,
auth.key_store,
payments::PaymentSessionUpdate,
payload,
api::AuthFlow::Client,
payments::CallConnectorAction::Trigger,
None,
header_payload.clone(),
None,
)
},
&auth::PublishableKeyAuth,
locking_action,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsSessionToken, payment_id))]
pub async fn payments_connector_session(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsSessionRequest>,
path: web::Path<common_utils::id_type::GlobalPaymentId>,
) -> impl Responder {
use hyperswitch_domain_models::payments::PaymentIntentData;
let flow = Flow::PaymentsSessionToken;
let global_payment_id = path.into_inner();
tracing::Span::current().record("payment_id", global_payment_id.get_string_repr());
let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId {
global_payment_id: global_payment_id.clone(),
payload: json_payload.into_inner(),
};
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
let locking_action = internal_payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
internal_payload,
|state, auth: auth::AuthenticationData, req, req_state| {
let payment_id = req.global_payment_id;
let request = req.payload;
let operation = payments::operations::PaymentSessionIntent;
payments::payments_session_core::<
api_types::Session,
payment_types::PaymentsSessionResponse,
_,
_,
_,
PaymentIntentData<api_types::Session>,
>(
state,
req_state,
auth.merchant_account,
auth.profile,
auth.key_store,
operation,
request,
payment_id,
payments::CallConnectorAction::Trigger,
header_payload.clone(),
auth.platform_merchant_account,
)
},
&auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Payment(
global_payment_id,
)),
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsSessionToken, payment_id))]
pub async fn payments_connector_session(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsSessionRequest>,
) -> impl Responder {
let flow = Flow::PaymentsSessionToken;
let payload = json_payload.into_inner();
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(error) => {
logger::error!(
?error,
"Failed to get headers in payments_connector_session"
);
HeaderPayload::default()
}
};
tracing::Span::current().record("payment_id", payload.payment_id.get_string_repr());
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, payload, req_state| {
payments::payments_core::<
api_types::Session,
payment_types::PaymentsSessionResponse,
_,
_,
_,
payments::PaymentData<api_types::Session>,
>(
state,
req_state,
auth.merchant_account,
auth.profile_id,
auth.key_store,
payments::PaymentSession,
payload,
api::AuthFlow::Client,
payments::CallConnectorAction::Trigger,
None,
header_payload.clone(),
None,
)
},
&auth::HeaderAuth(auth::PublishableKeyAuth),
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsRedirect, payment_id))]
pub async fn payments_redirect_response(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: Option<web::Form<serde_json::Value>>,
path: web::Path<(
common_utils::id_type::PaymentId,
common_utils::id_type::MerchantId,
String,
)>,
) -> impl Responder {
let flow = Flow::PaymentsRedirect;
let (payment_id, merchant_id, connector) = path.into_inner();
let param_string = req.query_string();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
let payload = payments::PaymentsRedirectResponseData {
resource_id: payment_types::PaymentIdType::PaymentIntentId(payment_id),
merchant_id: Some(merchant_id.clone()),
force_sync: true,
json_payload: json_payload.map(|payload| payload.0),
param: Some(param_string.to_string()),
connector: Some(connector),
creds_identifier: None,
};
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
<payments::PaymentRedirectSync as PaymentRedirectFlow>::handle_payments_redirect_response(
&payments::PaymentRedirectSync {},
state,
req_state,
auth.merchant_account,
auth.key_store,
req,
auth.platform_merchant_account,
)
},
&auth::MerchantIdAuth(merchant_id),
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsRedirect, payment_id))]
pub async fn payments_redirect_response_with_creds_identifier(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
path: web::Path<(
common_utils::id_type::PaymentId,
common_utils::id_type::MerchantId,
String,
String,
)>,
) -> impl Responder {
let (payment_id, merchant_id, connector, creds_identifier) = path.into_inner();
let param_string = req.query_string();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
let payload = payments::PaymentsRedirectResponseData {
resource_id: payment_types::PaymentIdType::PaymentIntentId(payment_id),
merchant_id: Some(merchant_id.clone()),
force_sync: true,
json_payload: None,
param: Some(param_string.to_string()),
connector: Some(connector),
creds_identifier: Some(creds_identifier),
};
let flow = Flow::PaymentsRedirect;
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
<payments::PaymentRedirectSync as PaymentRedirectFlow>::handle_payments_redirect_response(
&payments::PaymentRedirectSync {},
state,
req_state,
auth.merchant_account,
auth.key_store,
req,
auth.platform_merchant_account,
)
},
&auth::MerchantIdAuth(merchant_id),
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow =? Flow::PaymentsRedirect, payment_id))]
pub async fn payments_complete_authorize_redirect(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: Option<web::Form<serde_json::Value>>,
path: web::Path<(
common_utils::id_type::PaymentId,
common_utils::id_type::MerchantId,
String,
)>,
) -> impl Responder {
let flow = Flow::PaymentsRedirect;
let (payment_id, merchant_id, connector) = path.into_inner();
let param_string = req.query_string();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
let payload = payments::PaymentsRedirectResponseData {
resource_id: payment_types::PaymentIdType::PaymentIntentId(payment_id),
merchant_id: Some(merchant_id.clone()),
param: Some(param_string.to_string()),
json_payload: json_payload.map(|s| s.0),
force_sync: false,
connector: Some(connector),
creds_identifier: None,
};
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
<payments::PaymentRedirectCompleteAuthorize as PaymentRedirectFlow>::handle_payments_redirect_response(
&payments::PaymentRedirectCompleteAuthorize {},
state,
req_state,
auth.merchant_account,
auth.key_store,
req,
auth.platform_merchant_account,
)
},
&auth::MerchantIdAuth(merchant_id),
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow =? Flow::PaymentsRedirect, payment_id))]
pub async fn payments_complete_authorize_redirect_with_creds_identifier(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: Option<web::Form<serde_json::Value>>,
path: web::Path<(
common_utils::id_type::PaymentId,
common_utils::id_type::MerchantId,
String,
String,
)>,
) -> impl Responder {
let flow = Flow::PaymentsRedirect;
let (payment_id, merchant_id, connector, creds_identifier) = path.into_inner();
let param_string = req.query_string();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
let payload = payments::PaymentsRedirectResponseData {
resource_id: payment_types::PaymentIdType::PaymentIntentId(payment_id),
merchant_id: Some(merchant_id.clone()),
param: Some(param_string.to_string()),
json_payload: json_payload.map(|s| s.0),
force_sync: false,
connector: Some(connector),
creds_identifier: Some(creds_identifier),
};
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
<payments::PaymentRedirectCompleteAuthorize as PaymentRedirectFlow>::handle_payments_redirect_response(
&payments::PaymentRedirectCompleteAuthorize {},
state,
req_state,
auth.merchant_account,
auth.key_store,
req,
auth.platform_merchant_account,
)
},
&auth::MerchantIdAuth(merchant_id),
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow =? Flow::PaymentsCompleteAuthorize, payment_id))]
pub async fn payments_complete_authorize(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsCompleteAuthorizeRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder {
let flow = Flow::PaymentsCompleteAuthorize;
let mut payload = json_payload.into_inner();
let payment_id = path.into_inner();
payload.payment_id.clone_from(&payment_id);
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
let payment_confirm_req = payment_types::PaymentsRequest {
payment_id: Some(payment_types::PaymentIdType::PaymentIntentId(
payment_id.clone(),
)),
shipping: payload.shipping.clone(),
client_secret: Some(payload.client_secret.peek().clone()),
threeds_method_comp_ind: payload.threeds_method_comp_ind.clone(),
..Default::default()
};
let (auth_type, auth_flow) =
match auth::check_client_secret_and_get_auth(req.headers(), &payment_confirm_req) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(report!(err)),
};
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, _req, req_state| {
payments::payments_core::<
api_types::CompleteAuthorize,
payment_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::CompleteAuthorize>,
>(
state.clone(),
req_state,
auth.merchant_account,
auth.profile_id,
auth.key_store,
payments::operations::payment_complete_authorize::CompleteAuthorize,
payment_confirm_req.clone(),
auth_flow,
payments::CallConnectorAction::Trigger,
None,
HeaderPayload::default(),
None,
)
},
&*auth_type,
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsCancel, payment_id))]
pub async fn payments_cancel(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsCancelRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder {
let flow = Flow::PaymentsCancel;
let mut payload = json_payload.into_inner();
let payment_id = path.into_inner();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
payload.payment_id = payment_id;
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
payments::payments_core::<
api_types::Void,
payment_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::Void>,
>(
state,
req_state,
auth.merchant_account,
auth.profile_id,
auth.key_store,
payments::PaymentCancel,
req,
api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
HeaderPayload::default(),
auth.platform_merchant_account,
)
},
&auth::HeaderAuth(auth::ApiKeyAuth),
locking_action,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::PaymentsList))]
#[cfg(all(feature = "olap", feature = "v1"))]
pub async fn payments_list(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
payload: web::Query<payment_types::PaymentListConstraints>,
) -> impl Responder {
let flow = Flow::PaymentsList;
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
payments::list_payments(state, auth.merchant_account, None, auth.key_store, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::MerchantPaymentRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::PaymentsList))]
#[cfg(all(feature = "olap", feature = "v2"))]
pub async fn payments_list(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
payload: web::Query<payment_types::PaymentListConstraints>,
) -> impl Responder {
let flow = Flow::PaymentsList;
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
payments::list_payments(state, auth.merchant_account, auth.key_store, req)
},
auth::auth_type(
&auth::V2ApiKeyAuth,
&auth::JWTAuth {
permission: Permission::MerchantPaymentRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::PaymentsList))]
#[cfg(all(feature = "olap", feature = "v1"))]
pub async fn profile_payments_list(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
payload: web::Query<payment_types::PaymentListConstraints>,
) -> impl Responder {
let flow = Flow::PaymentsList;
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
payments::list_payments(
state,
auth.merchant_account,
auth.profile_id.map(|profile_id| vec![profile_id]),
auth.key_store,
req,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::ProfilePaymentRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::PaymentsList))]
#[cfg(all(feature = "olap", feature = "v1"))]
pub async fn payments_list_by_filter(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
payload: web::Json<payment_types::PaymentListFilterConstraints>,
) -> impl Responder {
let flow = Flow::PaymentsList;
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
payments::apply_filters_on_payments(
state,
auth.merchant_account,
None,
auth.key_store,
req,
)
},
&auth::JWTAuth {
permission: Permission::MerchantPaymentRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::PaymentsList))]
#[cfg(all(feature = "olap", feature = "v1"))]
pub async fn profile_payments_list_by_filter(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
payload: web::Json<payment_types::PaymentListFilterConstraints>,
) -> impl Responder {
let flow = Flow::PaymentsList;
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
payments::apply_filters_on_payments(
state,
auth.merchant_account.clone(),
auth.profile_id.map(|profile_id| vec![profile_id]),
auth.key_store,
req,
)
},
&auth::JWTAuth {
permission: Permission::ProfilePaymentRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::PaymentsList))]
#[cfg(all(feature = "olap", feature = "v1"))]
pub async fn get_filters_for_payments(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
payload: web::Json<common_utils::types::TimeRange>,
) -> impl Responder {
let flow = Flow::PaymentsList;
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
payments::get_filters_for_payments(state, auth.merchant_account, auth.key_store, req)
},
&auth::JWTAuth {
permission: Permission::MerchantPaymentRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::PaymentsFilters))]
#[cfg(feature = "olap")]
pub async fn get_payment_filters(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
) -> impl Responder {
let flow = Flow::PaymentsFilters;
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
|state, auth: auth::AuthenticationData, _, _| {
payments::get_payment_filters(state, auth.merchant_account, None)
},
&auth::JWTAuth {
permission: Permission::MerchantPaymentRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::PaymentsFilters))]
#[cfg(all(feature = "olap", feature = "v2"))]
pub async fn get_payment_filters_profile(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
) -> impl Responder {
let flow = Flow::PaymentsFilters;
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
|state, auth: auth::AuthenticationData, _, _| {
payments::get_payment_filters(
state,
auth.merchant_account,
Some(vec![auth.profile.get_id().clone()]),
)
},
&auth::JWTAuth {
permission: Permission::ProfilePaymentRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::PaymentsFilters))]
#[cfg(all(feature = "olap", feature = "v1"))]
pub async fn get_payment_filters_profile(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
) -> impl Responder {
let flow = Flow::PaymentsFilters;
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
|state, auth: auth::AuthenticationData, _, _| {
payments::get_payment_filters(
state,
auth.merchant_account,
auth.profile_id.map(|profile_id| vec![profile_id]),
)
},
&auth::JWTAuth {
permission: Permission::ProfilePaymentRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::PaymentsAggregate))]
#[cfg(feature = "olap")]
pub async fn get_payments_aggregates(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
payload: web::Query<common_utils::types::TimeRange>,
) -> impl Responder {
let flow = Flow::PaymentsAggregate;
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
payments::get_aggregates_for_payments(state, auth.merchant_account, None, req)
},
&auth::JWTAuth {
permission: Permission::MerchantPaymentRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "oltp", feature = "v1"))]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsApprove, payment_id))]
pub async fn payments_approve(
state: web::Data<app::AppState>,
http_req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsApproveRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder {
let mut payload = json_payload.into_inner();
let payment_id = path.into_inner();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
payload.payment_id = payment_id;
let flow = Flow::PaymentsApprove;
let fpayload = FPaymentsApproveRequest(&payload);
let locking_action = fpayload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow.clone(),
state,
&http_req,
payload.clone(),
|state, auth: auth::AuthenticationData, req, req_state| {
payments::payments_core::<
api_types::Capture,
payment_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::Capture>,
>(
state,
req_state,
auth.merchant_account,
auth.profile_id,
auth.key_store,
payments::PaymentApprove,
payment_types::PaymentsCaptureRequest {
payment_id: req.payment_id,
..Default::default()
},
api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
HeaderPayload::default(),
auth.platform_merchant_account,
)
},
match env::which() {
env::Env::Production => &auth::HeaderAuth(auth::ApiKeyAuth),
_ => auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::ProfilePaymentWrite,
},
http_req.headers(),
),
},
locking_action,
))
.await
}
#[cfg(all(feature = "oltp", feature = "v1"))]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsReject, payment_id))]
pub async fn payments_reject(
state: web::Data<app::AppState>,
http_req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsRejectRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder {
let mut payload = json_payload.into_inner();
let payment_id = path.into_inner();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
payload.payment_id = payment_id;
let flow = Flow::PaymentsReject;
let fpayload = FPaymentsRejectRequest(&payload);
let locking_action = fpayload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow.clone(),
state,
&http_req,
payload.clone(),
|state, auth: auth::AuthenticationData, req, req_state| {
payments::payments_core::<
api_types::Void,
payment_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::Void>,
>(
state,
req_state,
auth.merchant_account,
auth.profile_id,
auth.key_store,
payments::PaymentReject,
payment_types::PaymentsCancelRequest {
payment_id: req.payment_id,
cancellation_reason: Some("Rejected by merchant".to_string()),
..Default::default()
},
api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
HeaderPayload::default(),
auth.platform_merchant_account,
)
},
match env::which() {
env::Env::Production => &auth::HeaderAuth(auth::ApiKeyAuth),
_ => auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::ProfilePaymentWrite,
},
http_req.headers(),
),
},
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
async fn authorize_verify_select<Op>(
operation: Op,
state: app::SessionState,
req_state: ReqState,
merchant_account: domain::MerchantAccount,
profile_id: Option<common_utils::id_type::ProfileId>,
key_store: domain::MerchantKeyStore,
header_payload: HeaderPayload,
req: api_models::payments::PaymentsRequest,
auth_flow: api::AuthFlow,
platform_merchant_account: Option<domain::MerchantAccount>,
) -> errors::RouterResponse<api_models::payments::PaymentsResponse>
where
Op: Sync
+ Clone
+ std::fmt::Debug
+ payments::operations::Operation<
api_types::Authorize,
api_models::payments::PaymentsRequest,
Data = payments::PaymentData<api_types::Authorize>,
> + payments::operations::Operation<
api_types::SetupMandate,
api_models::payments::PaymentsRequest,
Data = payments::PaymentData<api_types::SetupMandate>,
>,
{
// TODO: Change for making it possible for the flow to be inferred internally or through validation layer
// This is a temporary fix.
// After analyzing the code structure,
// the operation are flow agnostic, and the flow is only required in the post_update_tracker
// Thus the flow can be generated just before calling the connector instead of explicitly passing it here.
let is_recurring_details_type_nti_and_card_details = req
.recurring_details
.clone()
.map(|recurring_details| {
recurring_details.is_network_transaction_id_and_card_details_flow()
})
.unwrap_or(false);
if is_recurring_details_type_nti_and_card_details {
// no list of eligible connectors will be passed in the confirm call
logger::debug!("Authorize call for NTI and Card Details flow");
payments::proxy_for_payments_core::<
api_types::Authorize,
payment_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::Authorize>,
>(
state,
req_state,
merchant_account,
profile_id,
key_store,
operation,
req,
auth_flow,
payments::CallConnectorAction::Trigger,
header_payload,
platform_merchant_account,
)
.await
} else {
let eligible_connectors = req.connector.clone();
match req.payment_type.unwrap_or_default() {
api_models::enums::PaymentType::Normal
| api_models::enums::PaymentType::RecurringMandate
| api_models::enums::PaymentType::NewMandate => {
payments::payments_core::<
api_types::Authorize,
payment_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::Authorize>,
>(
state,
req_state,
merchant_account,
profile_id,
key_store,
operation,
req,
auth_flow,
payments::CallConnectorAction::Trigger,
eligible_connectors,
header_payload,
platform_merchant_account,
)
.await
}
api_models::enums::PaymentType::SetupMandate => {
payments::payments_core::<
api_types::SetupMandate,
payment_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::SetupMandate>,
>(
state,
req_state,
merchant_account,
profile_id,
key_store,
operation,
req,
auth_flow,
payments::CallConnectorAction::Trigger,
eligible_connectors,
header_payload,
platform_merchant_account,
)
.await
}
}
}
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsIncrementalAuthorization, payment_id))]
pub async fn payments_incremental_authorization(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsIncrementalAuthorizationRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder {
let flow = Flow::PaymentsIncrementalAuthorization;
let mut payload = json_payload.into_inner();
let payment_id = path.into_inner();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
payload.payment_id = payment_id;
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
payments::payments_core::<
api_types::IncrementalAuthorization,
payment_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::IncrementalAuthorization>,
>(
state,
req_state,
auth.merchant_account,
auth.profile_id,
auth.key_store,
payments::PaymentIncrementalAuthorization,
req,
api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
HeaderPayload::default(),
auth.platform_merchant_account,
)
},
&auth::HeaderAuth(auth::ApiKeyAuth),
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsExternalAuthentication, payment_id))]
pub async fn payments_external_authentication(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsExternalAuthenticationRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder {
let flow = Flow::PaymentsExternalAuthentication;
let mut payload = json_payload.into_inner();
let payment_id = path.into_inner();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
payload.payment_id = payment_id;
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
payments::payment_external_authentication::<
hyperswitch_domain_models::router_flow_types::Authenticate,
>(state, auth.merchant_account, auth.key_store, req)
},
&auth::HeaderAuth(auth::PublishableKeyAuth),
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsAuthorize, payment_id))]
pub async fn post_3ds_payments_authorize(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: Option<web::Form<serde_json::Value>>,
path: web::Path<(
common_utils::id_type::PaymentId,
common_utils::id_type::MerchantId,
String,
)>,
) -> impl Responder {
let flow = Flow::PaymentsAuthorize;
let (payment_id, merchant_id, connector) = path.into_inner();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
let param_string = req.query_string();
let payload = payments::PaymentsRedirectResponseData {
resource_id: payment_types::PaymentIdType::PaymentIntentId(payment_id),
merchant_id: Some(merchant_id.clone()),
force_sync: true,
json_payload: json_payload.map(|payload| payload.0),
param: Some(param_string.to_string()),
connector: Some(connector),
creds_identifier: None,
};
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
<payments::PaymentAuthenticateCompleteAuthorize as PaymentRedirectFlow>::handle_payments_redirect_response(
&payments::PaymentAuthenticateCompleteAuthorize {},
state,
req_state,
auth.merchant_account,
auth.key_store,
req,
auth.platform_merchant_account,
)
},
&auth::MerchantIdAuth(merchant_id),
locking_action,
))
.await
}
#[cfg(all(feature = "olap", feature = "v1"))]
pub async fn payments_manual_update(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsManualUpdateRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder {
let flow = Flow::PaymentsManualUpdate;
let mut payload = json_payload.into_inner();
let payment_id = path.into_inner();
let locking_action = payload.get_locking_input(flow.clone());
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
payload.payment_id = payment_id;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, _auth, req, _req_state| payments::payments_manual_update(state, req),
&auth::AdminApiAuthWithMerchantIdFromHeader,
locking_action,
))
.await
}
#[cfg(feature = "v1")]
/// Retrieve endpoint for merchant to fetch the encrypted customer payment method data
#[instrument(skip_all, fields(flow = ?Flow::GetExtendedCardInfo, payment_id))]
pub async fn retrieve_extended_card_info(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder {
let flow = Flow::GetExtendedCardInfo;
let payment_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payment_id,
|state, auth: auth::AuthenticationData, payment_id, _| {
payments::get_extended_card_info(
state,
auth.merchant_account.get_id().to_owned(),
payment_id,
)
},
&auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
pub fn get_or_generate_payment_id(
payload: &mut payment_types::PaymentsRequest,
) -> errors::RouterResult<()> {
let given_payment_id = payload
.payment_id
.clone()
.map(|payment_id| {
payment_id
.get_payment_intent_id()
.map_err(|err| err.change_context(errors::ApiErrorResponse::PaymentNotFound))
})
.transpose()?;
let payment_id = given_payment_id.unwrap_or(common_utils::id_type::PaymentId::default());
payload.payment_id = Some(api_models::payments::PaymentIdType::PaymentIntentId(
payment_id,
));
Ok(())
}
#[cfg(feature = "v1")]
impl GetLockingInput for payment_types::PaymentsRequest {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
lock_utils::ApiIdentifier: From<F>,
{
match self.payment_id {
Some(payment_types::PaymentIdType::PaymentIntentId(ref id)) => {
api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::from(flow),
override_lock_retries: None,
},
}
}
_ => api_locking::LockAction::NotApplicable,
}
}
}
#[cfg(feature = "v1")]
impl GetLockingInput for payment_types::PaymentsStartRequest {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
lock_utils::ApiIdentifier: From<F>,
{
api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: self.payment_id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::from(flow),
override_lock_retries: None,
},
}
}
}
#[cfg(feature = "v1")]
impl GetLockingInput for payment_types::PaymentsRetrieveRequest {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
lock_utils::ApiIdentifier: From<F>,
{
match self.resource_id {
payment_types::PaymentIdType::PaymentIntentId(ref id) if self.force_sync => {
api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::from(flow),
override_lock_retries: None,
},
}
}
_ => api_locking::LockAction::NotApplicable,
}
}
}
#[cfg(feature = "v1")]
impl GetLockingInput for payment_types::PaymentsSessionRequest {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
lock_utils::ApiIdentifier: From<F>,
{
api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: self.payment_id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::from(flow),
override_lock_retries: None,
},
}
}
}
#[cfg(feature = "v2")]
impl GetLockingInput for payment_types::PaymentsSessionRequest {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
{
api_locking::LockAction::NotApplicable
}
}
#[cfg(feature = "v1")]
impl GetLockingInput for payment_types::PaymentsDynamicTaxCalculationRequest {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
lock_utils::ApiIdentifier: From<F>,
{
api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: self.payment_id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::from(flow),
override_lock_retries: None,
},
}
}
}
#[cfg(feature = "v1")]
impl GetLockingInput for payment_types::PaymentsPostSessionTokensRequest {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
lock_utils::ApiIdentifier: From<F>,
{
api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: self.payment_id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::from(flow),
override_lock_retries: None,
},
}
}
}
#[cfg(feature = "v1")]
impl GetLockingInput for payments::PaymentsRedirectResponseData {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
lock_utils::ApiIdentifier: From<F>,
{
match self.resource_id {
payment_types::PaymentIdType::PaymentIntentId(ref id) => {
api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::from(flow),
override_lock_retries: None,
},
}
}
_ => api_locking::LockAction::NotApplicable,
}
}
}
#[cfg(feature = "v2")]
impl GetLockingInput for payments::PaymentsRedirectResponseData {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
lock_utils::ApiIdentifier: From<F>,
{
api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: self.payment_id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::from(flow),
override_lock_retries: None,
},
}
}
}
#[cfg(feature = "v1")]
impl GetLockingInput for payment_types::PaymentsCompleteAuthorizeRequest {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
lock_utils::ApiIdentifier: From<F>,
{
api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: self.payment_id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::from(flow),
override_lock_retries: None,
},
}
}
}
#[cfg(feature = "v1")]
impl GetLockingInput for payment_types::PaymentsCancelRequest {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
lock_utils::ApiIdentifier: From<F>,
{
api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: self.payment_id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::from(flow),
override_lock_retries: None,
},
}
}
}
#[cfg(feature = "v1")]
impl GetLockingInput for payment_types::PaymentsCaptureRequest {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
lock_utils::ApiIdentifier: From<F>,
{
api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: self.payment_id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::from(flow),
override_lock_retries: None,
},
}
}
}
#[cfg(feature = "oltp")]
struct FPaymentsApproveRequest<'a>(&'a payment_types::PaymentsApproveRequest);
#[cfg(feature = "oltp")]
impl GetLockingInput for FPaymentsApproveRequest<'_> {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
lock_utils::ApiIdentifier: From<F>,
{
api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: self.0.payment_id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::from(flow),
override_lock_retries: None,
},
}
}
}
#[cfg(feature = "oltp")]
struct FPaymentsRejectRequest<'a>(&'a payment_types::PaymentsRejectRequest);
#[cfg(feature = "oltp")]
impl GetLockingInput for FPaymentsRejectRequest<'_> {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
lock_utils::ApiIdentifier: From<F>,
{
api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: self.0.payment_id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::from(flow),
override_lock_retries: None,
},
}
}
}
#[cfg(feature = "v1")]
impl GetLockingInput for payment_types::PaymentsIncrementalAuthorizationRequest {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
lock_utils::ApiIdentifier: From<F>,
{
api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: self.payment_id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::from(flow),
override_lock_retries: None,
},
}
}
}
#[cfg(feature = "v1")]
impl GetLockingInput for payment_types::PaymentsExternalAuthenticationRequest {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
lock_utils::ApiIdentifier: From<F>,
{
api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: self.payment_id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::from(flow),
override_lock_retries: None,
},
}
}
}
#[cfg(feature = "v1")]
impl GetLockingInput for payment_types::PaymentsManualUpdateRequest {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
lock_utils::ApiIdentifier: From<F>,
{
api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: self.payment_id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::from(flow),
override_lock_retries: None,
},
}
}
}
#[instrument(skip_all, fields(flow = ?Flow::PaymentsAggregate))]
#[cfg(all(feature = "olap", feature = "v1"))]
pub async fn get_payments_aggregates_profile(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
payload: web::Query<common_utils::types::TimeRange>,
) -> impl Responder {
let flow = Flow::PaymentsAggregate;
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
payments::get_aggregates_for_payments(
state,
auth.merchant_account,
auth.profile_id.map(|profile_id| vec![profile_id]),
req,
)
},
&auth::JWTAuth {
permission: Permission::ProfilePaymentRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::PaymentsAggregate))]
#[cfg(all(feature = "olap", feature = "v2"))]
pub async fn get_payments_aggregates_profile(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
payload: web::Query<common_utils::types::TimeRange>,
) -> impl Responder {
let flow = Flow::PaymentsAggregate;
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
payments::get_aggregates_for_payments(
state,
auth.merchant_account,
Some(vec![auth.profile.get_id().clone()]),
req,
)
},
&auth::JWTAuth {
permission: Permission::ProfilePaymentRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
/// A private module to hold internal types to be used in route handlers.
/// This is because we will need to implement certain traits on these types which will have the resource id
/// But the api payload will not contain the resource id
/// So these types can hold the resource id along with actual api payload, on which api event and locking action traits can be implemented
mod internal_payload_types {
use super::*;
// Serialize is implemented because of api events
#[derive(Debug, serde::Serialize)]
pub struct PaymentsGenericRequestWithResourceId<T: serde::Serialize> {
pub global_payment_id: common_utils::id_type::GlobalPaymentId,
#[serde(flatten)]
pub payload: T,
}
impl<T: serde::Serialize> GetLockingInput for PaymentsGenericRequestWithResourceId<T> {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
F: types::FlowMetric,
lock_utils::ApiIdentifier: From<F>,
{
api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: self.global_payment_id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::from(flow),
override_lock_retries: None,
},
}
}
}
impl<T: serde::Serialize> common_utils::events::ApiEventMetric
for PaymentsGenericRequestWithResourceId<T>
{
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::Payment {
payment_id: self.global_payment_id.clone(),
})
}
}
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentStartRedirection, payment_id))]
pub async fn payments_start_redirection(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
payload: web::Query<api_models::payments::PaymentStartRedirectionParams>,
path: web::Path<common_utils::id_type::GlobalPaymentId>,
) -> impl Responder {
let flow = Flow::PaymentStartRedirection;
let global_payment_id = path.into_inner();
tracing::Span::current().record("payment_id", global_payment_id.get_string_repr());
let publishable_key = &payload.publishable_key;
let profile_id = &payload.profile_id;
let payment_start_redirection_request = api_models::payments::PaymentStartRedirectionRequest {
id: global_payment_id.clone(),
};
let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId {
global_payment_id: global_payment_id.clone(),
payload: payment_start_redirection_request.clone(),
};
let locking_action = internal_payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payment_start_redirection_request.clone(),
|state, auth: auth::AuthenticationData, _req, req_state| async {
payments::payment_start_redirection(
state,
auth.merchant_account,
auth.key_store,
payment_start_redirection_request.clone(),
)
.await
},
&auth::PublishableKeyAndProfileIdAuth {
publishable_key: publishable_key.clone(),
profile_id: profile_id.clone(),
},
locking_action,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsConfirmIntent, payment_id))]
pub async fn payment_confirm_intent(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<api_models::payments::PaymentsConfirmIntentRequest>,
path: web::Path<common_utils::id_type::GlobalPaymentId>,
) -> impl Responder {
use hyperswitch_domain_models::payments::PaymentConfirmData;
let flow = Flow::PaymentsConfirmIntent;
// TODO: Populate browser information into the payload
// if let Err(err) = helpers::populate_ip_into_browser_info(&req, &mut payload) {
// return api::log_and_return_error_response(err);
// }
let global_payment_id = path.into_inner();
tracing::Span::current().record("payment_id", global_payment_id.get_string_repr());
let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId {
global_payment_id: global_payment_id.clone(),
payload: json_payload.into_inner(),
};
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
let locking_action = internal_payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
internal_payload,
|state, auth: auth::AuthenticationData, req, req_state| async {
let payment_id = req.global_payment_id;
let request = req.payload;
let operation = payments::operations::PaymentIntentConfirm;
Box::pin(payments::payments_core::<
api_types::Authorize,
api_models::payments::PaymentsResponse,
_,
_,
_,
PaymentConfirmData<api_types::Authorize>,
>(
state,
req_state,
auth.merchant_account,
auth.profile,
auth.key_store,
operation,
request,
payment_id,
payments::CallConnectorAction::Trigger,
header_payload.clone(),
))
.await
},
&auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Payment(
global_payment_id,
)),
locking_action,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::ProxyConfirmIntent, payment_id))]
pub async fn proxy_confirm_intent(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<api_models::payments::ProxyPaymentsRequest>,
path: web::Path<common_utils::id_type::GlobalPaymentId>,
) -> impl Responder {
use hyperswitch_domain_models::payments::PaymentConfirmData;
let flow = Flow::ProxyConfirmIntent;
// Extract the payment ID from the path
let global_payment_id = path.into_inner();
tracing::Span::current().record("payment_id", global_payment_id.get_string_repr());
// Parse and validate headers
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
// Prepare the internal payload
let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId {
global_payment_id,
payload: json_payload.into_inner(),
};
// Determine the locking action, if required
let locking_action = internal_payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
internal_payload,
|state, auth: auth::AuthenticationData, req, req_state| {
let payment_id = req.global_payment_id;
let request = req.payload;
// Define the operation for proxy payments intent
let operation = payments::operations::proxy_payments_intent::PaymentProxyIntent;
// Call the core proxy logic
Box::pin(payments::proxy_for_payments_core::<
api_types::Authorize,
api_models::payments::PaymentsResponse,
_,
_,
_,
PaymentConfirmData<api_types::Authorize>,
>(
state,
req_state,
auth.merchant_account,
auth.profile,
auth.key_store,
operation,
request,
payment_id,
payments::CallConnectorAction::Trigger,
header_payload.clone(),
))
},
&auth::V2ApiKeyAuth,
locking_action,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip(state, req), fields(flow, payment_id))]
pub async fn payment_status(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
payload: web::Query<api_models::payments::PaymentsRetrieveRequest>,
path: web::Path<common_utils::id_type::GlobalPaymentId>,
) -> impl Responder {
use hyperswitch_domain_models::payments::PaymentStatusData;
let flow = match payload.force_sync {
true => Flow::PaymentsRetrieveForceSync,
false => Flow::PaymentsRetrieve,
};
let global_payment_id = path.into_inner();
tracing::Span::current().record("payment_id", global_payment_id.get_string_repr());
let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId {
global_payment_id,
payload: payload.into_inner(),
};
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
let locking_action = internal_payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
internal_payload,
|state, auth: auth::AuthenticationData, req, req_state| async {
let payment_id = req.global_payment_id;
let request = req.payload;
let operation = payments::operations::PaymentGet;
Box::pin(payments::payments_core::<
api_types::PSync,
api_models::payments::PaymentsResponse,
_,
_,
_,
PaymentStatusData<api_types::PSync>,
>(
state,
req_state,
auth.merchant_account,
auth.profile,
auth.key_store,
operation,
request,
payment_id,
payments::CallConnectorAction::Trigger,
header_payload.clone(),
))
.await
},
auth::auth_type(
&auth::V2ApiKeyAuth,
&auth::JWTAuth {
permission: Permission::ProfilePaymentRead,
},
req.headers(),
),
locking_action,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip(state, req), fields(flow, payment_id))]
pub async fn payment_get_intent_using_merchant_reference_id(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
path: web::Path<common_utils::id_type::PaymentReferenceId>,
) -> impl Responder {
let flow = Flow::PaymentsRetrieveUsingMerchantReferenceId;
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
let merchant_reference_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
|state, auth: auth::AuthenticationData, _, req_state| async {
Box::pin(payments::payments_get_intent_using_merchant_reference(
state,
auth.merchant_account,
auth.profile,
auth.key_store,
req_state,
&merchant_reference_id,
header_payload.clone(),
auth.platform_merchant_account,
))
.await
},
&auth::V2ApiKeyAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsRedirect, payment_id))]
pub async fn payments_finish_redirection(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: Option<web::Form<serde_json::Value>>,
path: web::Path<(
common_utils::id_type::GlobalPaymentId,
String,
common_utils::id_type::ProfileId,
)>,
) -> impl Responder {
let flow = Flow::PaymentsRedirect;
let (payment_id, publishable_key, profile_id) = path.into_inner();
let param_string = req.query_string();
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
let payload = payments::PaymentsRedirectResponseData {
payment_id,
json_payload: json_payload.map(|payload| payload.0),
query_params: param_string.to_string(),
};
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth, req, req_state| {
<payments::PaymentRedirectSync as PaymentRedirectFlow>::handle_payments_redirect_response(
&payments::PaymentRedirectSync {},
state,
req_state,
auth.merchant_account,
auth.key_store,
auth.profile,
req,
auth.platform_merchant_account
)
},
&auth::PublishableKeyAndProfileIdAuth {
publishable_key: publishable_key.clone(),
profile_id: profile_id.clone(),
},
locking_action,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip(state, req), fields(flow, payment_id))]
pub async fn payments_capture(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
payload: web::Json<api_models::payments::PaymentsCaptureRequest>,
path: web::Path<common_utils::id_type::GlobalPaymentId>,
) -> impl Responder {
use hyperswitch_domain_models::payments::PaymentCaptureData;
let flow = Flow::PaymentsCapture;
let global_payment_id = path.into_inner();
tracing::Span::current().record("payment_id", global_payment_id.get_string_repr());
let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId {
global_payment_id,
payload: payload.into_inner(),
};
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
let locking_action = internal_payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
internal_payload,
|state, auth: auth::AuthenticationData, req, req_state| async {
let payment_id = req.global_payment_id;
let request = req.payload;
let operation = payments::operations::payment_capture_v2::PaymentsCapture;
Box::pin(payments::payments_core::<
api_types::Capture,
api_models::payments::PaymentsCaptureResponse,
_,
_,
_,
PaymentCaptureData<api_types::Capture>,
>(
state,
req_state,
auth.merchant_account,
auth.profile,
auth.key_store,
operation,
request,
payment_id,
payments::CallConnectorAction::Trigger,
header_payload.clone(),
))
.await
},
auth::auth_type(
&auth::V2ApiKeyAuth,
&auth::JWTAuth {
permission: Permission::ProfileAccountWrite,
},
req.headers(),
),
locking_action,
))
.await
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsList))]
pub async fn list_payment_methods(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
path: web::Path<common_utils::id_type::GlobalPaymentId>,
query_payload: web::Query<api_models::payments::PaymentMethodsListRequest>,
) -> impl Responder {
let flow = Flow::PaymentMethodsList;
let payload = query_payload.into_inner();
let global_payment_id = path.into_inner();
tracing::Span::current().record("payment_id", global_payment_id.get_string_repr());
let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId {
global_payment_id: global_payment_id.clone(),
payload,
};
let header_payload = match 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,
internal_payload,
|state, auth, req, _| {
payments::payment_methods::list_payment_methods(
state,
auth.merchant_account,
auth.profile,
auth.key_store,
req.global_payment_id,
req.payload,
&header_payload,
)
},
&auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Payment(
global_payment_id,
)),
api_locking::LockAction::NotApplicable,
))
.await
}
| 20,044 | 1,239 |
hyperswitch | crates/router/src/routes/dummy_connector.rs | .rs | use actix_web::web;
use router_env::{instrument, tracing};
use super::app;
use crate::{
core::api_locking,
services::{api, authentication as auth},
};
mod consts;
mod core;
mod errors;
pub mod types;
mod utils;
#[cfg(all(feature = "dummy_connector", feature = "v1"))]
#[instrument(skip_all, fields(flow = ?types::Flow::DummyPaymentCreate))]
pub async fn dummy_connector_authorize_payment(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
path: web::Path<String>,
) -> impl actix_web::Responder {
let flow = types::Flow::DummyPaymentAuthorize;
let attempt_id = path.into_inner();
let payload = types::DummyConnectorPaymentConfirmRequest { attempt_id };
api::server_wrap(
flow,
state,
&req,
payload,
|state, _: (), req, _| core::payment_authorize(state, req),
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
)
.await
}
#[cfg(all(feature = "dummy_connector", feature = "v1"))]
#[instrument(skip_all, fields(flow = ?types::Flow::DummyPaymentCreate))]
pub async fn dummy_connector_complete_payment(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
path: web::Path<String>,
json_payload: web::Query<types::DummyConnectorPaymentCompleteBody>,
) -> impl actix_web::Responder {
let flow = types::Flow::DummyPaymentComplete;
let attempt_id = path.into_inner();
let payload = types::DummyConnectorPaymentCompleteRequest {
attempt_id,
confirm: json_payload.confirm,
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, _: (), req, _| core::payment_complete(state, req),
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "dummy_connector", feature = "v1"))]
#[instrument(skip_all, fields(flow = ?types::Flow::DummyPaymentCreate))]
pub async fn dummy_connector_payment(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<types::DummyConnectorPaymentRequest>,
) -> impl actix_web::Responder {
let payload = json_payload.into_inner();
let flow = types::Flow::DummyPaymentCreate;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, _: (), req, _| core::payment(state, req),
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "dummy_connector", feature = "v1"))]
#[instrument(skip_all, fields(flow = ?types::Flow::DummyPaymentRetrieve))]
pub async fn dummy_connector_payment_data(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
path: web::Path<String>,
) -> impl actix_web::Responder {
let flow = types::Flow::DummyPaymentRetrieve;
let payment_id = path.into_inner();
let payload = types::DummyConnectorPaymentRetrieveRequest { payment_id };
api::server_wrap(
flow,
state,
&req,
payload,
|state, _: (), req, _| core::payment_data(state, req),
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
)
.await
}
#[cfg(all(feature = "dummy_connector", feature = "v1"))]
#[instrument(skip_all, fields(flow = ?types::Flow::DummyRefundCreate))]
pub async fn dummy_connector_refund(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<types::DummyConnectorRefundRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl actix_web::Responder {
let flow = types::Flow::DummyRefundCreate;
let mut payload = json_payload.into_inner();
payload.payment_id = Some(path.into_inner());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, _: (), req, _| core::refund_payment(state, req),
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "dummy_connector", feature = "v1"))]
#[instrument(skip_all, fields(flow = ?types::Flow::DummyRefundRetrieve))]
pub async fn dummy_connector_refund_data(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
path: web::Path<String>,
) -> impl actix_web::Responder {
let flow = types::Flow::DummyRefundRetrieve;
let refund_id = path.into_inner();
let payload = types::DummyConnectorRefundRetrieveRequest { refund_id };
api::server_wrap(
flow,
state,
&req,
payload,
|state, _: (), req, _| core::refund_data(state, req),
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
)
.await
}
| 1,165 | 1,240 |
hyperswitch | crates/router/src/routes/hypersense.rs | .rs | use actix_web::{web, HttpRequest, HttpResponse};
use api_models::external_service_auth as external_service_auth_api;
use router_env::Flow;
use super::AppState;
use crate::{
core::{api_locking, external_service_auth},
services::{
api,
authentication::{self, ExternalServiceType},
},
};
pub async fn get_hypersense_token(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
let flow = Flow::HypersenseTokenRequest;
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
|state, user, _, _| {
external_service_auth::generate_external_token(
state,
user,
ExternalServiceType::Hypersense,
)
},
&authentication::DashboardNoPermissionAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn signout_hypersense_token(
state: web::Data<AppState>,
http_req: HttpRequest,
json_payload: web::Json<external_service_auth_api::ExternalSignoutTokenRequest>,
) -> HttpResponse {
let flow = Flow::HypersenseSignoutToken;
Box::pin(api::server_wrap(
flow,
state.clone(),
&http_req,
json_payload.into_inner(),
|state, _: (), json_payload, _| {
external_service_auth::signout_external_token(state, json_payload)
},
&authentication::NoAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn verify_hypersense_token(
state: web::Data<AppState>,
http_req: HttpRequest,
json_payload: web::Json<external_service_auth_api::ExternalVerifyTokenRequest>,
) -> HttpResponse {
let flow = Flow::HypersenseVerifyToken;
Box::pin(api::server_wrap(
flow,
state.clone(),
&http_req,
json_payload.into_inner(),
|state, _: (), json_payload, _| {
external_service_auth::verify_external_token(
state,
json_payload,
ExternalServiceType::Hypersense,
)
},
&authentication::NoAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
| 488 | 1,241 |
hyperswitch | crates/router/src/routes/locker_migration.rs | .rs | use actix_web::{web, HttpRequest, HttpResponse};
use router_env::Flow;
use super::AppState;
use crate::{
core::{api_locking, locker_migration},
services::{api, authentication as auth},
};
pub async fn rust_locker_migration(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::MerchantId>,
) -> HttpResponse {
let flow = Flow::RustLockerMigration;
let merchant_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
&merchant_id,
|state, _, _, _| locker_migration::rust_locker_migration(state, &merchant_id),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
| 178 | 1,242 |
hyperswitch | crates/router/src/routes/webhooks.rs | .rs | 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},
};
#[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| {
webhooks::incoming_webhooks_wrapper::<W>(
&flow,
state.to_owned(),
req_state,
&req,
auth.merchant_account,
auth.key_store,
&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| {
webhooks::incoming_webhooks_wrapper::<W>(
&flow,
state.to_owned(),
req_state,
&req,
auth.merchant_account,
auth.key_store,
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| {
webhooks::incoming_webhooks_wrapper::<W>(
&flow,
state.to_owned(),
req_state,
&req,
auth.merchant_account,
auth.profile,
auth.key_store,
&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| {
webhooks::incoming_webhooks_wrapper::<W>(
&flow,
state.to_owned(),
req_state,
&req,
auth.merchant_account,
auth.profile,
auth.key_store,
&connector_id,
body.clone(),
false,
)
},
&auth::MerchantIdAndProfileIdAuth {
merchant_id,
profile_id,
},
api_locking::LockAction::NotApplicable,
))
.await
}
| 1,119 | 1,243 |
hyperswitch | crates/router/src/routes/mandates.rs | .rs | 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,
};
/// Mandates - Retrieve Mandate
///
/// Retrieves a mandate created using the Payments/Create API
#[utoipa::path(
get,
path = "/mandates/{mandate_id}",
params(
("mandate_id" = String, Path, description = "The identifier for mandate")
),
responses(
(status = 200, description = "The mandate was retrieved successfully", body = MandateResponse),
(status = 404, description = "Mandate does not exist in our records")
),
tag = "Mandates",
operation_id = "Retrieve a Mandate",
security(("api_key" = []))
)]
#[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, _| {
mandate::get_mandate(state, auth.merchant_account, auth.key_store, req)
},
&auth::HeaderAuth(auth::ApiKeyAuth),
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, _| {
mandate::revoke_mandate(state, auth.merchant_account, auth.key_store, req)
},
&auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Mandates - List Mandates
#[utoipa::path(
get,
path = "/mandates/list",
params(
("limit" = Option<i64>, Query, description = "The maximum number of Mandate Objects to include in the response"),
("mandate_status" = Option<MandateStatus>, Query, description = "The status of mandate"),
("connector" = Option<String>, Query, description = "The connector linked to mandate"),
("created_time" = Option<PrimitiveDateTime>, Query, description = "The time at which mandate is created"),
("created_time.lt" = Option<PrimitiveDateTime>, Query, description = "Time less than the mandate created time"),
("created_time.gt" = Option<PrimitiveDateTime>, Query, description = "Time greater than the mandate created time"),
("created_time.lte" = Option<PrimitiveDateTime>, Query, description = "Time less than or equals to the mandate created time"),
("created_time.gte" = Option<PrimitiveDateTime>, Query, description = "Time greater than or equals to the mandate created time"),
("offset" = Option<i64>, Query, description = "The number of Mandate Objects to skip when retrieving the list Mandates."),
),
responses(
(status = 200, description = "The mandate list was retrieved successfully", body = Vec<MandateResponse>),
(status = 401, description = "Unauthorized request")
),
tag = "Mandates",
operation_id = "List Mandates",
security(("api_key" = []))
)]
#[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, _| {
mandate::retrieve_mandates_list(state, auth.merchant_account, auth.key_store, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::MerchantMandateRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
| 1,110 | 1,244 |
hyperswitch | crates/router/src/routes/recon.rs | .rs | 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
}
| 566 | 1,245 |
hyperswitch | crates/router/src/routes/routing.rs | .rs | //! 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 as routing_types, routing::RoutingRetrieveQuery};
use router_env::{
tracing::{self, instrument},
Flow,
};
use crate::{
core::{api_locking, conditional_config, routing, surcharge_decision_config},
routes::AppState,
services::{api as oss_api, authentication as auth, authorization::permissions::Permission},
};
#[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: 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, _| {
routing::create_routing_algorithm_under_profile(
state,
auth.merchant_account,
auth.key_store,
auth.profile_id,
payload,
transaction_type,
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&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 = "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, _| {
routing::create_routing_algorithm_under_profile(
state,
auth.merchant_account,
auth.key_store,
Some(auth.profile.get_id().clone()),
payload,
transaction_type,
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::V2ApiKeyAuth,
&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>,
transaction_type: &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, _| {
routing::link_routing_config(
state,
auth.merchant_account,
auth.key_store,
auth.profile_id,
algorithm,
transaction_type,
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&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 = "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, _| {
routing::link_routing_config_under_profile(
state,
auth.merchant_account,
auth.key_store,
wrapper.profile_id,
wrapper.algorithm_id.routing_algorithm_id,
transaction_type,
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::V2ApiKeyAuth,
&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, _| {
routing::retrieve_routing_algorithm_from_algorithm_id(
state,
auth.merchant_account,
auth.key_store,
auth.profile_id,
algorithm_id,
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::ProfileRoutingRead,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
permission: Permission::ProfileRoutingRead,
},
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, _| {
routing::retrieve_routing_algorithm_from_algorithm_id(
state,
auth.merchant_account,
auth.key_store,
Some(auth.profile.get_id().clone()),
algorithm_id,
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::V2ApiKeyAuth,
&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: &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, _| {
routing::retrieve_merchant_routing_dictionary(
state,
auth.merchant_account,
None,
query_params,
transaction_type,
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::MerchantRoutingRead,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
permission: Permission::MerchantRoutingRead,
},
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: &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, _| {
routing::retrieve_merchant_routing_dictionary(
state,
auth.merchant_account,
auth.profile_id.map(|profile_id| vec![profile_id]),
query_params,
transaction_type,
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::ProfileRoutingRead,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
permission: Permission::ProfileRoutingRead,
},
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, _| {
routing::unlink_routing_config_under_profile(
state,
auth.merchant_account,
auth.key_store,
path,
transaction_type,
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::V2ApiKeyAuth,
&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: &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, _| {
routing::unlink_routing_config(
state,
auth.merchant_account,
auth.key_store,
payload_req,
auth.profile_id,
transaction_type,
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&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 = "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, _| {
routing::update_default_fallback_routing(
state,
auth.merchant_account,
auth.key_store,
wrapper.profile_id,
wrapper.connectors,
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::V2ApiKeyAuth,
&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, _| {
routing::update_default_routing_config(
state,
auth.merchant_account,
updated_config,
transaction_type,
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&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 = "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, _| {
routing::retrieve_default_fallback_algorithm_for_profile(
state,
auth.merchant_account,
auth.key_store,
profile_id,
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::V2ApiKeyAuth,
&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, _, _| {
routing::retrieve_default_routing_config(
state,
auth.profile_id,
auth.merchant_account,
transaction_type,
)
},
&auth::JWTAuth {
permission: Permission::ProfileRoutingRead,
},
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, _| {
surcharge_decision_config::upsert_surcharge_decision_config(
state,
auth.key_store,
auth.merchant_account,
update_decision,
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&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, (), _| {
surcharge_decision_config::delete_surcharge_decision_config(
state,
auth.key_store,
auth.merchant_account,
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&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, _, _| {
surcharge_decision_config::retrieve_surcharge_decision_config(
state,
auth.merchant_account,
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&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, _| {
conditional_config::upsert_conditional_config(
state,
auth.key_store,
auth.merchant_account,
update_decision,
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&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,
&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, (), _| {
conditional_config::delete_conditional_config(
state,
auth.key_store,
auth.merchant_account,
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&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,
&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, _, _| {
conditional_config::retrieve_conditional_config(state, auth.merchant_account)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&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: &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, _| {
routing::retrieve_linked_routing_config(
state,
auth.merchant_account,
auth.key_store,
auth.profile_id,
query_params,
transaction_type,
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuthProfileFromRoute {
profile_id,
required_permission: Permission::ProfileRoutingRead,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuthProfileFromRoute {
profile_id,
required_permission: Permission::ProfileRoutingRead,
},
api_locking::LockAction::NotApplicable,
))
.await
} else {
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
query.clone(),
|state, auth: AuthenticationData, query_params, _| {
routing::retrieve_linked_routing_config(
state,
auth.merchant_account,
auth.key_store,
auth.profile_id,
query_params,
transaction_type,
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::ProfileRoutingRead,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
permission: Permission::ProfileRoutingRead,
},
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, _| {
routing::retrieve_routing_config_under_profile(
state,
auth.merchant_account,
auth.key_store,
wrapper.routing_query,
wrapper.profile_id,
transaction_type,
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::V2ApiKeyAuth,
&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, _, _| {
routing::retrieve_default_routing_config_for_profiles(
state,
auth.merchant_account,
auth.key_store,
transaction_type,
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::MerchantRoutingRead,
},
req.headers(),
),
#[cfg(feature = "release")]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&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, _| {
routing::update_default_routing_config_for_profile(
state,
auth.merchant_account,
auth.key_store,
wrapper.updated_config,
wrapper.profile_id,
transaction_type,
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuthProfileFromRoute {
profile_id: routing_payload_wrapper.profile_id,
required_permission: Permission::ProfileRoutingWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuthProfileFromRoute {
profile_id: routing_payload_wrapper.profile_id,
required_permission: Permission::ProfileRoutingWrite,
},
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,
_| {
routing::toggle_specific_dynamic_routing(
state,
auth.merchant_account,
auth.key_store,
wrapper.feature_to_enable,
wrapper.profile_id,
api_models::routing::DynamicRoutingType::SuccessRateBasedRouting,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&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),
&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 {
Box::pin(routing::contract_based_dynamic_routing_setup(
state,
auth.key_store,
auth.merchant_account,
wrapper.profile_id,
wrapper.features_to_enable,
wrapper.config,
))
.await
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&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 {
Box::pin(routing::contract_based_routing_update_configs(
state,
wrapper.updated_config,
auth.merchant_account,
auth.key_store,
wrapper.algorithm_id,
wrapper.profile_id,
))
.await
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&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,
_| {
routing::toggle_specific_dynamic_routing(
state,
auth.merchant_account,
auth.key_store,
wrapper.feature_to_enable,
wrapper.profile_id,
api_models::routing::DynamicRoutingType::EliminationRouting,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&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,
_| {
routing::configure_dynamic_routing_volume_split(
state,
auth.merchant_account,
auth.key_store,
payload.profile_id,
payload.routing_info,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuthProfileFromRoute {
profile_id: payload.profile_id,
required_permission: Permission::ProfileRoutingWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
| 8,965 | 1,246 |
hyperswitch | crates/router/src/routes/pm_auth.rs | .rs | 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, 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 (auth, _) = match crate::services::authentication::check_client_secret_and_get_auth(
req.headers(),
&payload,
) {
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, _| {
crate::core::pm_auth::create_link_token(
state,
auth.merchant_account,
auth.key_store,
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 (auth, _) = match crate::services::authentication::check_client_secret_and_get_auth(
req.headers(),
&payload,
) {
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, _| {
crate::core::pm_auth::exchange_token_core(
state,
auth.merchant_account,
auth.key_store,
payload,
)
},
&*auth,
api_locking::LockAction::NotApplicable,
))
.await
}
| 596 | 1,247 |
hyperswitch | crates/router/src/routes/process_tracker.rs | .rs | #[cfg(feature = "v2")]
pub mod revenue_recovery;
| 13 | 1,248 |
hyperswitch | crates/router/src/routes/payout_link.rs | .rs | use actix_web::{web, Responder};
use api_models::payouts::PayoutLinkInitiateRequest;
use router_env::Flow;
use crate::{
core::{api_locking, payout_link::*},
services::{
api,
authentication::{self as auth},
},
AppState,
};
#[cfg(feature = "v1")]
pub async fn render_payout_link(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
path: web::Path<(common_utils::id_type::MerchantId, String)>,
) -> impl Responder {
let flow = Flow::PayoutLinkInitiate;
let (merchant_id, payout_id) = path.into_inner();
let payload = PayoutLinkInitiateRequest {
merchant_id: merchant_id.clone(),
payout_id,
};
let headers = req.headers();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload.clone(),
|state, auth, req, _| {
initiate_payout_link(state, auth.merchant_account, auth.key_store, req, headers)
},
&auth::MerchantIdAuth(merchant_id),
api_locking::LockAction::NotApplicable,
))
.await
}
| 266 | 1,249 |
hyperswitch | crates/router/src/routes/ephemeral_key.rs | .rs | use actix_web::{web, HttpRequest, HttpResponse};
use router_env::{instrument, tracing, Flow};
use super::AppState;
use crate::{
core::{api_locking, payments::helpers},
services::{api, authentication as auth},
};
#[cfg(all(feature = "v1", not(feature = "customer_v2")))]
#[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),
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),
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, _| {
helpers::make_client_secret(
state,
payload.resource_id.to_owned(),
auth.merchant_account,
auth.key_store,
req.headers(),
)
},
&auth::V2ApiKeyAuth,
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,
api_locking::LockAction::NotApplicable,
))
.await
}
| 746 | 1,250 |
hyperswitch | crates/router/src/routes/customers.rs | .rs | 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,
};
#[cfg(all(feature = "v2", feature = "customer_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, _| {
create_customer(state, auth.merchant_account, auth.key_store, req)
},
auth::auth_type(
&auth::V2ApiKeyAuth,
&auth::JWTAuth {
permission: Permission::MerchantCustomerWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_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, _| {
create_customer(state, auth.merchant_account, auth.key_store, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::MerchantCustomerWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
#[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 {
match auth::is_ephemeral_auth(req.headers()) {
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, _| {
retrieve_customer(
state,
auth.merchant_account,
auth.profile_id,
auth.key_store,
customer_id,
)
},
&*auth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v2", feature = "customer_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, &v2_client_auth, req.headers())
};
Box::pin(api::server_wrap(
flow,
state,
&req,
id,
|state, auth: auth::AuthenticationData, id, _| {
retrieve_customer(state, auth.merchant_account, auth.key_store, id)
},
auth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v2", feature = "customer_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();
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,
&auth::JWTAuth {
permission: Permission::MerchantCustomerRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
)
.await
}
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_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::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::MerchantCustomerRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
#[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, _| {
update_customer(
state,
auth.merchant_account,
request_internal,
auth.key_store,
)
},
auth::auth_type(
&auth::ApiKeyAuth,
&auth::JWTAuth {
permission: Permission::MerchantCustomerWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v2", feature = "customer_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, _| {
update_customer(
state,
auth.merchant_account,
request_internal,
auth.key_store,
)
},
auth::auth_type(
&auth::V2ApiKeyAuth,
&auth::JWTAuth {
permission: Permission::MerchantCustomerWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v2", feature = "customer_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, _| {
delete_customer(state, auth.merchant_account, id, auth.key_store)
},
auth::auth_type(
&auth::V2ApiKeyAuth,
&auth::JWTAuth {
permission: Permission::MerchantCustomerWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
#[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, _| {
delete_customer(state, auth.merchant_account, customer_id, auth.key_store)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::MerchantCustomerWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
#[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, _| {
crate::core::mandate::get_customer_mandates(
state,
auth.merchant_account,
auth.key_store,
customer_id,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::MerchantMandateRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
| 2,595 | 1,251 |
hyperswitch | crates/router/src/routes/recovery_webhooks.rs | .rs | 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},
};
#[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| {
webhooks::incoming_webhooks_wrapper::<W>(
&flow,
state.to_owned(),
req_state,
&req,
auth.merchant_account,
auth.profile,
auth.key_store,
&connector_id,
body.clone(),
false,
)
},
&auth::MerchantIdAndProfileIdAuth {
merchant_id,
profile_id,
},
api_locking::LockAction::NotApplicable,
))
.await
}
| 326 | 1,252 |
hyperswitch | crates/router/src/routes/refunds.rs | .rs | use actix_web::{web, HttpRequest, HttpResponse};
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
use crate::{
core::{api_locking, refunds::*},
services::{api, authentication as auth, authorization::permissions::Permission},
types::api::refunds,
};
/// Refunds - Create
///
/// To create a refund against an already processed payment
#[utoipa::path(
post,
path = "/refunds",
request_body=RefundRequest,
responses(
(status = 200, description = "Refund created", body = RefundResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Refunds",
operation_id = "Create a Refund",
security(("api_key" = []))
)]
#[instrument(skip_all, fields(flow = ?Flow::RefundsCreate))]
// #[post("")]
pub async fn refunds_create(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<refunds::RefundRequest>,
) -> HttpResponse {
let flow = Flow::RefundsCreate;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| {
refund_create_core(
state,
auth.merchant_account,
auth.profile_id,
auth.key_store,
req,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::ProfileRefundWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Refunds - Retrieve (GET)
///
/// To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment
#[utoipa::path(
get,
path = "/refunds/{refund_id}",
params(
("refund_id" = String, Path, description = "The identifier for refund")
),
responses(
(status = 200, description = "Refund retrieved", body = RefundResponse),
(status = 404, description = "Refund does not exist in our records")
),
tag = "Refunds",
operation_id = "Retrieve a Refund",
security(("api_key" = []))
)]
#[instrument(skip_all, fields(flow))]
// #[get("/{id}")]
pub async fn refunds_retrieve(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
query_params: web::Query<api_models::refunds::RefundsRetrieveBody>,
) -> HttpResponse {
let refund_request = refunds::RefundsRetrieveRequest {
refund_id: path.into_inner(),
force_sync: query_params.force_sync,
merchant_connector_details: None,
};
let flow = match query_params.force_sync {
Some(true) => Flow::RefundsRetrieveForceSync,
_ => Flow::RefundsRetrieve,
};
tracing::Span::current().record("flow", flow.to_string());
Box::pin(api::server_wrap(
flow,
state,
&req,
refund_request,
|state, auth: auth::AuthenticationData, refund_request, _| {
refund_response_wrapper(
state,
auth.merchant_account,
auth.profile_id,
auth.key_store,
refund_request,
refund_retrieve_core_with_refund_id,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::ProfileRefundRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Refunds - Retrieve (POST)
///
/// To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment
#[utoipa::path(
get,
path = "/refunds/sync",
responses(
(status = 200, description = "Refund retrieved", body = RefundResponse),
(status = 404, description = "Refund does not exist in our records")
),
tag = "Refunds",
operation_id = "Retrieve a Refund",
security(("api_key" = []))
)]
#[instrument(skip_all, fields(flow))]
// #[post("/sync")]
pub async fn refunds_retrieve_with_body(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<refunds::RefundsRetrieveRequest>,
) -> HttpResponse {
let flow = match json_payload.force_sync {
Some(true) => Flow::RefundsRetrieveForceSync,
_ => Flow::RefundsRetrieve,
};
tracing::Span::current().record("flow", flow.to_string());
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| {
refund_response_wrapper(
state,
auth.merchant_account,
auth.profile_id,
auth.key_store,
req,
refund_retrieve_core_with_refund_id,
)
},
&auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Refunds - Update
///
/// To update the properties of a Refund object. This may include attaching a reason for the refund or metadata fields
#[utoipa::path(
post,
path = "/refunds/{refund_id}",
params(
("refund_id" = String, Path, description = "The identifier for refund")
),
request_body=RefundUpdateRequest,
responses(
(status = 200, description = "Refund updated", body = RefundResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Refunds",
operation_id = "Update a Refund",
security(("api_key" = []))
)]
#[instrument(skip_all, fields(flow = ?Flow::RefundsUpdate))]
// #[post("/{id}")]
pub async fn refunds_update(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<refunds::RefundUpdateRequest>,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::RefundsUpdate;
let mut refund_update_req = json_payload.into_inner();
refund_update_req.refund_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
refund_update_req,
|state, auth: auth::AuthenticationData, req, _| {
refund_update_core(state, auth.merchant_account, req)
},
&auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Refunds - List
///
/// To list the refunds associated with a payment_id or with the merchant, if payment_id is not provided
#[utoipa::path(
post,
path = "/refunds/list",
request_body=RefundListRequest,
responses(
(status = 200, description = "List of refunds", body = RefundListResponse),
),
tag = "Refunds",
operation_id = "List all Refunds",
security(("api_key" = []))
)]
#[instrument(skip_all, fields(flow = ?Flow::RefundsList))]
#[cfg(feature = "olap")]
pub async fn refunds_list(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<api_models::refunds::RefundListRequest>,
) -> HttpResponse {
let flow = Flow::RefundsList;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| {
refund_list(state, auth.merchant_account, None, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::MerchantRefundRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Refunds - List at profile level
///
/// To list the refunds associated with a payment_id or with the merchant, if payment_id is not provided
#[utoipa::path(
post,
path = "/refunds/profile/list",
request_body=RefundListRequest,
responses(
(status = 200, description = "List of refunds", body = RefundListResponse),
),
tag = "Refunds",
operation_id = "List all Refunds",
security(("api_key" = []))
)]
#[instrument(skip_all, fields(flow = ?Flow::RefundsList))]
#[cfg(feature = "olap")]
pub async fn refunds_list_profile(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<api_models::refunds::RefundListRequest>,
) -> HttpResponse {
let flow = Flow::RefundsList;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| {
refund_list(
state,
auth.merchant_account,
auth.profile_id.map(|profile_id| vec![profile_id]),
req,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::ProfileRefundRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Refunds - Filter
///
/// To list the refunds filters associated with list of connectors, currencies and payment statuses
#[utoipa::path(
post,
path = "/refunds/filter",
request_body=TimeRange,
responses(
(status = 200, description = "List of filters", body = RefundListMetaData),
),
tag = "Refunds",
operation_id = "List all filters for Refunds",
security(("api_key" = []))
)]
#[instrument(skip_all, fields(flow = ?Flow::RefundsList))]
#[cfg(feature = "olap")]
pub async fn refunds_filter_list(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<common_utils::types::TimeRange>,
) -> HttpResponse {
let flow = Flow::RefundsList;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| {
refund_filter_list(state, auth.merchant_account, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::MerchantRefundRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Refunds - Filter V2
///
/// To list the refunds filters associated with list of connectors, currencies and payment statuses
#[utoipa::path(
get,
path = "/refunds/v2/filter",
responses(
(status = 200, description = "List of static filters", body = RefundListFilters),
),
tag = "Refunds",
operation_id = "List all filters for Refunds",
security(("api_key" = []))
)]
#[instrument(skip_all, fields(flow = ?Flow::RefundsFilters))]
#[cfg(feature = "olap")]
pub async fn get_refunds_filters(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
let flow = Flow::RefundsFilters;
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
|state, auth: auth::AuthenticationData, _, _| {
get_filters_for_refunds(state, auth.merchant_account, None)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::MerchantRefundRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Refunds - Filter V2 at profile level
///
/// To list the refunds filters associated with list of connectors, currencies and payment statuses
#[utoipa::path(
get,
path = "/refunds/v2/profile/filter",
responses(
(status = 200, description = "List of static filters", body = RefundListFilters),
),
tag = "Refunds",
operation_id = "List all filters for Refunds",
security(("api_key" = []))
)]
#[instrument(skip_all, fields(flow = ?Flow::RefundsFilters))]
#[cfg(feature = "olap")]
pub async fn get_refunds_filters_profile(
state: web::Data<AppState>,
req: HttpRequest,
) -> HttpResponse {
let flow = Flow::RefundsFilters;
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
|state, auth: auth::AuthenticationData, _, _| {
get_filters_for_refunds(
state,
auth.merchant_account,
auth.profile_id.map(|profile_id| vec![profile_id]),
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::ProfileRefundRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::RefundsAggregate))]
#[cfg(feature = "olap")]
pub async fn get_refunds_aggregates(
state: web::Data<AppState>,
req: HttpRequest,
query_params: web::Query<common_utils::types::TimeRange>,
) -> HttpResponse {
let flow = Flow::RefundsAggregate;
let query_params = query_params.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
query_params,
|state, auth: auth::AuthenticationData, req, _| {
get_aggregates_for_refunds(state, auth.merchant_account, None, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::MerchantRefundRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::RefundsManualUpdate))]
#[cfg(feature = "olap")]
pub async fn refunds_manual_update(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<api_models::refunds::RefundManualUpdateRequest>,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::RefundsManualUpdate;
let mut refund_manual_update_req = payload.into_inner();
refund_manual_update_req.refund_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
refund_manual_update_req,
|state, _auth, req, _| refund_manual_update(state, req),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::RefundsAggregate))]
#[cfg(feature = "olap")]
pub async fn get_refunds_aggregate_profile(
state: web::Data<AppState>,
req: HttpRequest,
query_params: web::Query<common_utils::types::TimeRange>,
) -> HttpResponse {
let flow = Flow::RefundsAggregate;
let query_params = query_params.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
query_params,
|state, auth: auth::AuthenticationData, req, _| {
get_aggregates_for_refunds(
state,
auth.merchant_account,
auth.profile_id.map(|profile_id| vec![profile_id]),
req,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::ProfileRefundRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
| 3,617 | 1,253 |
hyperswitch | crates/router/src/routes/fraud_check.rs | .rs | use actix_web::{web, HttpRequest, HttpResponse};
use router_env::Flow;
use crate::{
core::{api_locking, fraud_check as frm_core},
services::{self, api},
AppState,
};
#[cfg(feature = "v1")]
pub async fn frm_fulfillment(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<frm_core::types::FrmFulfillmentRequest>,
) -> HttpResponse {
let flow = Flow::FrmFulfillment;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
json_payload.into_inner(),
|state, auth: services::authentication::AuthenticationData, req, _| {
frm_core::frm_fulfillment_core(state, auth.merchant_account, auth.key_store, req)
},
&services::authentication::ApiKeyAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
| 205 | 1,254 |
hyperswitch | crates/router/src/routes/gsm.rs | .rs | 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},
};
/// 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),
&auth::AdminApiAuth,
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),
&auth::AdminApiAuth,
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),
&auth::AdminApiAuth,
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),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
| 1,147 | 1,255 |
hyperswitch | crates/router/src/routes/admin.rs | .rs | use actix_web::{web, HttpRequest, HttpResponse};
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
use crate::{
core::{admin::*, api_locking},
services::{api, authentication as auth, authorization::permissions::Permission},
types::api::admin,
};
#[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::AdminApiAuth,
&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::AdminApiAuth,
&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;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, _, req, _| create_merchant_account(state, req),
&auth::AdminApiAuthWithApiKeyFallback,
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),
&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::AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(merchant_id.clone()),
&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, _, request, _| list_merchant_account(state, request),
auth::auth_type(
&auth::AdminApiAuthWithApiKeyFallback,
&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::AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(merchant_id.clone()),
&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, _| {
create_connector(
state,
req,
auth_data.merchant_account,
auth_data.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: 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, _| {
create_connector(
state,
req,
auth_data.merchant_account,
None,
auth_data.key_store,
)
},
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")]
#[utoipa::path(
get,
path = "/accounts/{account_id}/connectors/{connector_id}",
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account"),
("connector_id" = i32, Path, description = "The unique identifier for the Merchant Connector")
),
responses(
(status = 200, description = "Merchant Connector retrieved successfully", body = MerchantConnectorResponse),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Merchant Connector Account",
operation_id = "Retrieve a Merchant Connector",
security(("admin_api_key" = []))
)]
#[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,
_| { retrieve_connector(state, merchant_account, key_store, 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
#[utoipa::path(
get,
path = "/accounts/{account_id}/connectors",
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account"),
),
responses(
(status = 200, description = "Merchant Connector list retrieved successfully", body = Vec<MerchantConnectorResponse>),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Merchant Connector Account",
operation_id = "List all Merchant Connectors",
security(("admin_api_key" = []))
)]
#[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
#[utoipa::path(
get,
path = "/accounts/{account_id}/profile/connectors",
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account"),
),
responses(
(status = 200, description = "Merchant Connector list retrieved successfully", body = Vec<MerchantConnectorResponse>),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Merchant Connector Account",
operation_id = "List all Merchant Connectors for The given Profile",
security(("admin_api_key" = []))
)]
#[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")]
#[utoipa::path(
post,
path = "/accounts/{account_id}/connectors/{connector_id}",
request_body = MerchantConnectorUpdate,
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account"),
("connector_id" = i32, Path, description = "The unique identifier for the Merchant Connector")
),
responses(
(status = 200, description = "Merchant Connector Updated", body = MerchantConnectorResponse),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Merchant Connector Account",
operation_id = "Update a Merchant Connector",
security(("admin_api_key" = []))
)]
#[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")]
#[utoipa::path(
post,
path = "/connector_accounts/{id}",
request_body = MerchantConnectorUpdate,
params(
("id" = i32, Path, description = "The unique identifier for the Merchant Connector")
),
responses(
(status = 200, description = "Merchant Connector Updated", body = MerchantConnectorResponse),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Merchant Connector Account",
operation_id = "Update a Merchant Connector",
security(("admin_api_key" = []))
)]
#[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")]
#[utoipa::path(
delete,
path = "/accounts/{account_id}/connectors/{connector_id}",
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account"),
("connector_id" = i32, Path, description = "The unique identifier for the Merchant Connector")
),
responses(
(status = 200, description = "Merchant Connector Deleted", body = MerchantConnectorDeleteResponse),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Merchant Connector Account",
operation_id = "Delete a Merchant Connector",
security(("admin_api_key" = []))
)]
#[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,
_| { delete_connector(state, merchant_account, key_store, 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
#[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
}
/// 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
#[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
}
/// 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
}
| 8,141 | 1,256 |
hyperswitch | crates/router/src/routes/profiles.rs | .rs | use actix_web::{web, HttpRequest, HttpResponse};
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
use crate::{
core::{admin::*, api_locking},
services::{api, authentication as auth, authorization::permissions},
types::api::admin,
};
#[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();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth_data, req, _| {
create_profile(state, req, auth_data.merchant_account, auth_data.key_store)
},
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();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state,
auth::AuthenticationDataWithoutProfile {
merchant_account,
key_store,
},
req,
_| { create_profile(state, req, merchant_account, key_store) },
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();
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|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();
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|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),
&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
}
| 2,924 | 1,257 |
hyperswitch | crates/router/src/routes/payouts.rs | .rs | use actix_web::{
body::{BoxBody, MessageBody},
web, HttpRequest, HttpResponse, Responder,
};
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
use crate::{
core::{api_locking, payouts::*},
services::{
api,
authentication::{self as auth},
authorization::permissions::Permission,
},
types::api::payouts as payout_types,
};
/// Payouts - Create
#[instrument(skip_all, fields(flow = ?Flow::PayoutsCreate))]
pub async fn payouts_create(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payout_types::PayoutCreateRequest>,
) -> HttpResponse {
let flow = Flow::PayoutsCreate;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| {
payouts_create_core(state, auth.merchant_account, auth.key_store, req)
},
&auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v1", feature = "payouts"))]
/// Payouts - Retrieve
#[instrument(skip_all, fields(flow = ?Flow::PayoutsRetrieve))]
pub async fn payouts_retrieve(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
query_params: web::Query<payout_types::PayoutRetrieveBody>,
) -> HttpResponse {
let payout_retrieve_request = payout_types::PayoutRetrieveRequest {
payout_id: path.into_inner(),
force_sync: query_params.force_sync.to_owned(),
merchant_id: query_params.merchant_id.to_owned(),
};
let flow = Flow::PayoutsRetrieve;
Box::pin(api::server_wrap(
flow,
state,
&req,
payout_retrieve_request,
|state, auth: auth::AuthenticationData, req, _| {
payouts_retrieve_core(
state,
auth.merchant_account,
auth.profile_id,
auth.key_store,
req,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::ProfilePayoutRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Payouts - Update
#[instrument(skip_all, fields(flow = ?Flow::PayoutsUpdate))]
pub async fn payouts_update(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
json_payload: web::Json<payout_types::PayoutCreateRequest>,
) -> HttpResponse {
let flow = Flow::PayoutsUpdate;
let payout_id = path.into_inner();
let mut payout_update_payload = json_payload.into_inner();
payout_update_payload.payout_id = Some(payout_id);
Box::pin(api::server_wrap(
flow,
state,
&req,
payout_update_payload,
|state, auth: auth::AuthenticationData, req, _| {
payouts_update_core(state, auth.merchant_account, auth.key_store, req)
},
&auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::PayoutsConfirm))]
pub async fn payouts_confirm(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payout_types::PayoutCreateRequest>,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::PayoutsConfirm;
let mut payload = json_payload.into_inner();
let payout_id = path.into_inner();
tracing::Span::current().record("payout_id", &payout_id);
payload.payout_id = Some(payout_id);
payload.confirm = Some(true);
let (auth_type, _auth_flow) =
match auth::check_client_secret_and_get_auth(req.headers(), &payload) {
Ok(auth) => auth,
Err(e) => return api::log_and_return_error_response(e),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth, req, _| {
payouts_confirm_core(state, auth.merchant_account, auth.key_store, req)
},
&*auth_type,
api_locking::LockAction::NotApplicable,
))
.await
}
/// Payouts - Cancel
#[instrument(skip_all, fields(flow = ?Flow::PayoutsCancel))]
pub async fn payouts_cancel(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payout_types::PayoutActionRequest>,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::PayoutsCancel;
let mut payload = json_payload.into_inner();
payload.payout_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
payouts_cancel_core(state, auth.merchant_account, auth.key_store, req)
},
&auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Payouts - Fulfill
#[instrument(skip_all, fields(flow = ?Flow::PayoutsFulfill))]
pub async fn payouts_fulfill(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payout_types::PayoutActionRequest>,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::PayoutsFulfill;
let mut payload = json_payload.into_inner();
payload.payout_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
payouts_fulfill_core(state, auth.merchant_account, auth.key_store, req)
},
&auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Payouts - List
#[cfg(feature = "olap")]
#[instrument(skip_all, fields(flow = ?Flow::PayoutsList))]
pub async fn payouts_list(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Query<payout_types::PayoutListConstraints>,
) -> HttpResponse {
let flow = Flow::PayoutsList;
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
payouts_list_core(state, auth.merchant_account, None, auth.key_store, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::MerchantPayoutRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Payouts - List Profile
#[cfg(all(feature = "olap", feature = "payouts", feature = "v1"))]
#[instrument(skip_all, fields(flow = ?Flow::PayoutsList))]
pub async fn payouts_list_profile(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Query<payout_types::PayoutListConstraints>,
) -> HttpResponse {
let flow = Flow::PayoutsList;
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
payouts_list_core(
state,
auth.merchant_account,
auth.profile_id.map(|profile_id| vec![profile_id]),
auth.key_store,
req,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::ProfilePayoutRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Payouts - Filtered list
#[cfg(feature = "olap")]
#[instrument(skip_all, fields(flow = ?Flow::PayoutsList))]
pub async fn payouts_list_by_filter(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payout_types::PayoutListFilterConstraints>,
) -> HttpResponse {
let flow = Flow::PayoutsList;
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
payouts_filtered_list_core(state, auth.merchant_account, None, auth.key_store, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::MerchantPayoutRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Payouts - Filtered list
#[cfg(all(feature = "olap", feature = "payouts", feature = "v1"))]
#[instrument(skip_all, fields(flow = ?Flow::PayoutsList))]
pub async fn payouts_list_by_filter_profile(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payout_types::PayoutListFilterConstraints>,
) -> HttpResponse {
let flow = Flow::PayoutsList;
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
payouts_filtered_list_core(
state,
auth.merchant_account,
auth.profile_id.map(|profile_id| vec![profile_id]),
auth.key_store,
req,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::ProfilePayoutRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Payouts - Available filters for Merchant
#[cfg(feature = "olap")]
#[instrument(skip_all, fields(flow = ?Flow::PayoutsFilter))]
pub async fn payouts_list_available_filters_for_merchant(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<common_utils::types::TimeRange>,
) -> HttpResponse {
let flow = Flow::PayoutsFilter;
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
payouts_list_available_filters_core(state, auth.merchant_account, None, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::MerchantPayoutRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
/// Payouts - Available filters for Profile
#[cfg(all(feature = "olap", feature = "payouts", feature = "v1"))]
#[instrument(skip_all, fields(flow = ?Flow::PayoutsFilter))]
pub async fn payouts_list_available_filters_for_profile(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<common_utils::types::TimeRange>,
) -> HttpResponse {
let flow = Flow::PayoutsFilter;
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
payouts_list_available_filters_core(
state,
auth.merchant_account,
auth.profile_id.map(|profile_id| vec![profile_id]),
req,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::ProfilePayoutRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::PayoutsAccounts))]
// #[get("/accounts")]
pub async fn payouts_accounts() -> impl Responder {
let _flow = Flow::PayoutsAccounts;
http_response("accounts")
}
fn http_response<T: MessageBody + 'static>(response: T) -> HttpResponse<BoxBody> {
HttpResponse::Ok().body(response)
}
| 2,846 | 1,258 |
hyperswitch | crates/router/src/routes/lock_utils.rs | .rs | use router_env::Flow;
#[derive(Clone, Debug, strum::Display)]
#[strum(serialize_all = "snake_case")]
pub enum ApiIdentifier {
Payments,
Refunds,
Webhooks,
Organization,
MerchantAccount,
MerchantConnector,
Configs,
Customers,
Ephemeral,
Health,
Mandates,
PaymentMethods,
PaymentMethodAuth,
Payouts,
Disputes,
CardsInfo,
Files,
Cache,
Profile,
Verification,
ApiKeys,
PaymentLink,
Routing,
Blocklist,
Forex,
RustLockerMigration,
Gsm,
Role,
User,
UserRole,
ConnectorOnboarding,
Recon,
Poll,
ApplePayCertificatesMigration,
Relay,
Documentation,
CardNetworkTokenization,
Hypersense,
PaymentMethodSession,
ProcessTracker,
}
impl From<Flow> for ApiIdentifier {
fn from(flow: Flow) -> Self {
match flow {
Flow::MerchantsAccountCreate
| Flow::MerchantsAccountRetrieve
| Flow::MerchantsAccountUpdate
| Flow::MerchantsAccountDelete
| Flow::MerchantTransferKey
| Flow::MerchantAccountList
| Flow::EnablePlatformAccount => Self::MerchantAccount,
Flow::OrganizationCreate | Flow::OrganizationRetrieve | Flow::OrganizationUpdate => {
Self::Organization
}
Flow::RoutingCreateConfig
| Flow::RoutingLinkConfig
| Flow::RoutingUnlinkConfig
| Flow::RoutingRetrieveConfig
| Flow::RoutingRetrieveActiveConfig
| Flow::RoutingRetrieveDefaultConfig
| Flow::RoutingRetrieveDictionary
| Flow::RoutingUpdateConfig
| Flow::RoutingUpdateDefaultConfig
| Flow::RoutingDeleteConfig
| Flow::DecisionManagerDeleteConfig
| Flow::DecisionManagerRetrieveConfig
| Flow::ToggleDynamicRouting
| Flow::UpdateDynamicRoutingConfigs
| Flow::DecisionManagerUpsertConfig
| Flow::VolumeSplitOnRoutingType => Self::Routing,
Flow::RetrieveForexFlow => Self::Forex,
Flow::AddToBlocklist => Self::Blocklist,
Flow::DeleteFromBlocklist => Self::Blocklist,
Flow::ListBlocklist => Self::Blocklist,
Flow::ToggleBlocklistGuard => Self::Blocklist,
Flow::MerchantConnectorsCreate
| Flow::MerchantConnectorsRetrieve
| Flow::MerchantConnectorsUpdate
| Flow::MerchantConnectorsDelete
| Flow::MerchantConnectorsList => Self::MerchantConnector,
Flow::ConfigKeyCreate
| Flow::ConfigKeyFetch
| Flow::ConfigKeyUpdate
| Flow::ConfigKeyDelete
| Flow::CreateConfigKey => Self::Configs,
Flow::CustomersCreate
| Flow::CustomersRetrieve
| Flow::CustomersUpdate
| Flow::CustomersDelete
| Flow::CustomersGetMandates
| Flow::CustomersList => Self::Customers,
Flow::EphemeralKeyCreate | Flow::EphemeralKeyDelete => Self::Ephemeral,
Flow::DeepHealthCheck | Flow::HealthCheck => Self::Health,
Flow::MandatesRetrieve | Flow::MandatesRevoke | Flow::MandatesList => Self::Mandates,
Flow::PaymentMethodsCreate
| Flow::PaymentMethodsMigrate
| Flow::PaymentMethodsList
| Flow::CustomerPaymentMethodsList
| Flow::PaymentMethodsRetrieve
| Flow::PaymentMethodsUpdate
| Flow::PaymentMethodsDelete
| Flow::PaymentMethodCollectLink
| Flow::ValidatePaymentMethod
| Flow::ListCountriesCurrencies
| Flow::DefaultPaymentMethodsSet
| Flow::PaymentMethodSave
| Flow::TotalPaymentMethodCount => Self::PaymentMethods,
Flow::PmAuthLinkTokenCreate | Flow::PmAuthExchangeToken => Self::PaymentMethodAuth,
Flow::PaymentsCreate
| Flow::PaymentsRetrieve
| Flow::PaymentsRetrieveForceSync
| Flow::PaymentsUpdate
| Flow::PaymentsConfirm
| Flow::PaymentsCapture
| Flow::PaymentsCancel
| Flow::PaymentsApprove
| Flow::PaymentsReject
| Flow::PaymentsSessionToken
| Flow::PaymentsStart
| Flow::PaymentsList
| Flow::PaymentsFilters
| Flow::PaymentsAggregate
| Flow::PaymentsRedirect
| Flow::PaymentsIncrementalAuthorization
| Flow::PaymentsExternalAuthentication
| Flow::PaymentsAuthorize
| Flow::GetExtendedCardInfo
| Flow::PaymentsCompleteAuthorize
| Flow::PaymentsManualUpdate
| Flow::SessionUpdateTaxCalculation
| Flow::PaymentsConfirmIntent
| Flow::PaymentsCreateIntent
| Flow::PaymentsGetIntent
| Flow::PaymentsPostSessionTokens
| Flow::PaymentsUpdateIntent
| Flow::PaymentsCreateAndConfirmIntent
| Flow::PaymentStartRedirection
| Flow::ProxyConfirmIntent
| Flow::PaymentsRetrieveUsingMerchantReferenceId => Self::Payments,
Flow::PayoutsCreate
| Flow::PayoutsRetrieve
| Flow::PayoutsUpdate
| Flow::PayoutsCancel
| Flow::PayoutsFulfill
| Flow::PayoutsList
| Flow::PayoutsFilter
| Flow::PayoutsAccounts
| Flow::PayoutsConfirm
| Flow::PayoutLinkInitiate => Self::Payouts,
Flow::RefundsCreate
| Flow::RefundsRetrieve
| Flow::RefundsRetrieveForceSync
| Flow::RefundsUpdate
| Flow::RefundsList
| Flow::RefundsFilters
| Flow::RefundsAggregate
| Flow::RefundsManualUpdate => Self::Refunds,
Flow::Relay | Flow::RelayRetrieve => Self::Relay,
Flow::FrmFulfillment
| Flow::IncomingWebhookReceive
| Flow::IncomingRelayWebhookReceive
| Flow::WebhookEventInitialDeliveryAttemptList
| Flow::WebhookEventDeliveryAttemptList
| Flow::WebhookEventDeliveryRetry
| Flow::RecoveryIncomingWebhookReceive => Self::Webhooks,
Flow::ApiKeyCreate
| Flow::ApiKeyRetrieve
| Flow::ApiKeyUpdate
| Flow::ApiKeyRevoke
| Flow::ApiKeyList => Self::ApiKeys,
Flow::DisputesRetrieve
| Flow::DisputesList
| Flow::DisputesFilters
| Flow::DisputesEvidenceSubmit
| Flow::AttachDisputeEvidence
| Flow::RetrieveDisputeEvidence
| Flow::DisputesAggregate
| Flow::DeleteDisputeEvidence => Self::Disputes,
Flow::CardsInfo
| Flow::CardsInfoCreate
| Flow::CardsInfoUpdate
| Flow::CardsInfoMigrate => Self::CardsInfo,
Flow::CreateFile | Flow::DeleteFile | Flow::RetrieveFile => Self::Files,
Flow::CacheInvalidate => Self::Cache,
Flow::ProfileCreate
| Flow::ProfileUpdate
| Flow::ProfileRetrieve
| Flow::ProfileDelete
| Flow::ProfileList
| Flow::ToggleExtendedCardInfo
| Flow::ToggleConnectorAgnosticMit => Self::Profile,
Flow::PaymentLinkRetrieve
| Flow::PaymentLinkInitiate
| Flow::PaymentSecureLinkInitiate
| Flow::PaymentLinkList
| Flow::PaymentLinkStatus => Self::PaymentLink,
Flow::Verification => Self::Verification,
Flow::RustLockerMigration => Self::RustLockerMigration,
Flow::GsmRuleCreate
| Flow::GsmRuleRetrieve
| Flow::GsmRuleUpdate
| Flow::GsmRuleDelete => Self::Gsm,
Flow::ApplePayCertificatesMigration => Self::ApplePayCertificatesMigration,
Flow::UserConnectAccount
| Flow::UserSignUp
| Flow::UserSignIn
| Flow::Signout
| Flow::ChangePassword
| Flow::SetDashboardMetadata
| Flow::GetMultipleDashboardMetadata
| Flow::VerifyPaymentConnector
| Flow::InternalUserSignup
| Flow::TenantUserCreate
| Flow::SwitchOrg
| Flow::SwitchMerchantV2
| Flow::SwitchProfile
| Flow::UserOrgMerchantCreate
| Flow::UserMerchantAccountCreate
| Flow::GenerateSampleData
| Flow::DeleteSampleData
| Flow::GetUserDetails
| Flow::GetUserRoleDetails
| Flow::ForgotPassword
| Flow::ResetPassword
| Flow::RotatePassword
| Flow::InviteMultipleUser
| Flow::ReInviteUser
| Flow::UserSignUpWithMerchantId
| Flow::VerifyEmail
| Flow::AcceptInviteFromEmail
| Flow::VerifyEmailRequest
| Flow::UpdateUserAccountDetails
| Flow::TotpBegin
| Flow::TotpReset
| Flow::TotpVerify
| Flow::TotpUpdate
| Flow::RecoveryCodeVerify
| Flow::RecoveryCodesGenerate
| Flow::TerminateTwoFactorAuth
| Flow::TwoFactorAuthStatus
| Flow::CreateUserAuthenticationMethod
| Flow::UpdateUserAuthenticationMethod
| Flow::ListUserAuthenticationMethods
| Flow::UserTransferKey
| Flow::GetSsoAuthUrl
| Flow::SignInWithSso
| Flow::ListOrgForUser
| Flow::ListMerchantsForUserInOrg
| Flow::ListProfileForUserInOrgAndMerchant
| Flow::ListInvitationsForUser
| Flow::AuthSelect
| Flow::GetThemeUsingLineage
| Flow::GetThemeUsingThemeId
| Flow::UploadFileToThemeStorage
| Flow::CreateTheme
| Flow::UpdateTheme
| Flow::DeleteTheme => Self::User,
Flow::ListRolesV2
| Flow::ListInvitableRolesAtEntityLevel
| Flow::ListUpdatableRolesAtEntityLevel
| Flow::GetRole
| Flow::GetRoleV2
| Flow::GetRoleFromToken
| Flow::GetRoleFromTokenV2
| Flow::UpdateUserRole
| Flow::GetAuthorizationInfo
| Flow::GetRolesInfo
| Flow::GetParentGroupInfo
| Flow::AcceptInvitationsV2
| Flow::AcceptInvitationsPreAuth
| Flow::DeleteUserRole
| Flow::CreateRole
| Flow::UpdateRole
| Flow::UserFromEmail
| Flow::ListUsersInLineage => Self::UserRole,
Flow::GetActionUrl | Flow::SyncOnboardingStatus | Flow::ResetTrackingId => {
Self::ConnectorOnboarding
}
Flow::ReconMerchantUpdate
| Flow::ReconTokenRequest
| Flow::ReconServiceRequest
| Flow::ReconVerifyToken => Self::Recon,
Flow::RetrievePollStatus => Self::Poll,
Flow::FeatureMatrix => Self::Documentation,
Flow::TokenizeCard
| Flow::TokenizeCardUsingPaymentMethodId
| Flow::TokenizeCardBatch => Self::CardNetworkTokenization,
Flow::HypersenseTokenRequest
| Flow::HypersenseVerifyToken
| Flow::HypersenseSignoutToken => Self::Hypersense,
Flow::PaymentMethodSessionCreate
| Flow::PaymentMethodSessionRetrieve
| Flow::PaymentMethodSessionConfirm
| Flow::PaymentMethodSessionUpdateSavedPaymentMethod
| Flow::PaymentMethodSessionDeleteSavedPaymentMethod
| Flow::PaymentMethodSessionUpdate => Self::PaymentMethodSession,
Flow::RevenueRecoveryRetrieve => Self::ProcessTracker,
}
}
}
| 2,604 | 1,259 |
hyperswitch | crates/router/src/routes/app.rs | .rs | use std::{collections::HashMap, sync::Arc};
use actix_web::{web, Scope};
#[cfg(all(feature = "olap", feature = "v1"))]
use api_models::routing::RoutingRetrieveQuery;
#[cfg(feature = "olap")]
use common_enums::TransactionType;
#[cfg(feature = "partial-auth")]
use common_utils::crypto::Blake3;
use common_utils::id_type;
#[cfg(feature = "email")]
use external_services::email::{
no_email::NoEmailClient, ses::AwsSes, smtp::SmtpServer, EmailClientConfigs, EmailService,
};
use external_services::{
file_storage::FileStorageInterface,
grpc_client::{GrpcClients, GrpcHeaders},
};
use hyperswitch_interfaces::{
encryption_interface::EncryptionManagementInterface,
secrets_interface::secret_state::{RawSecret, SecuredSecret},
};
use router_env::tracing_actix_web::RequestId;
use scheduler::SchedulerInterface;
use storage_impl::{config::TenantConfig, 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",
any(feature = "v1", feature = "v2"),
not(feature = "customer_v2")
))]
use super::pm_auth;
#[cfg(feature = "oltp")]
use super::poll;
#[cfg(all(feature = "v2", feature = "revenue_recovery", feature = "oltp"))]
use super::recovery_webhooks::*;
#[cfg(feature = "olap")]
use super::routing;
#[cfg(all(feature = "olap", feature = "v1"))]
use super::verification::{apple_pay_merchant_registration, retrieve_apple_pay_verified_domains};
#[cfg(feature = "oltp")]
use super::webhooks::*;
use super::{
admin, api_keys, cache::*, connector_onboarding, disputes, files, gsm, health::*, profiles,
relay, user, user_role,
};
#[cfg(feature = "v1")]
use super::{apple_pay_certificates_migration, blocklist, payment_link, 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 = "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 = "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,
};
#[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,
}
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 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;
}
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()
}
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()
}
}
#[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>,
}
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()
}
}
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 grpc_client = conf.grpc_client.get_grpc_client_interface().await;
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,
}
})
.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()),
})
}
}
pub struct Health;
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 = "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)
}
}
pub struct Payments;
#[cfg(all(
any(feature = "olap", feature = "oltp"),
feature = "v2",
feature = "payment_methods_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("/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)),
)
.service(
web::resource("/proxy-confirm-intent")
.route(web::post().to(payments::proxy_confirm_intent)),
)
.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)))
.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)),
),
);
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 = "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}/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("/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}/{merchant_id}/authorize/{connector}").route(web::post().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)),
);
}
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-algorithm")
.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,
&TransactionType::Payment,
)
})),
)
.service(
web::resource("")
.route(
web::get().to(|state, req, path: web::Query<RoutingRetrieveQuery>| {
routing::list_routing_configs(
state,
req,
path,
&TransactionType::Payment,
)
}),
)
.route(web::post().to(|state, req, payload| {
routing::routing_create_config(
state,
req,
payload,
TransactionType::Payment,
)
})),
)
.service(web::resource("/list/profile").route(web::get().to(
|state, req, query: web::Query<RoutingRetrieveQuery>| {
routing::list_routing_configs_for_profile(
state,
req,
query,
&TransactionType::Payment,
)
},
)))
.service(
web::resource("/default").route(web::post().to(|state, req, payload| {
routing::routing_update_default_config(
state,
req,
payload,
&TransactionType::Payment,
)
})),
)
.service(
web::resource("/deactivate").route(web::post().to(|state, req, payload| {
routing::routing_unlink_config(state, req, payload, &TransactionType::Payment)
})),
)
.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 = "payouts")]
{
route = route
.service(
web::resource("/payouts")
.route(web::get().to(
|state, req, path: web::Query<RoutingRetrieveQuery>| {
routing::list_routing_configs(
state,
req,
path,
&TransactionType::Payout,
)
},
))
.route(web::post().to(|state, req, payload| {
routing::routing_create_config(
state,
req,
payload,
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,
&TransactionType::Payout,
)
},
)))
.service(web::resource("/payouts/active").route(web::get().to(
|state, req, query_params| {
routing::routing_retrieve_linked_config(
state,
req,
query_params,
&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| {
routing::routing_link_config(state, req, path, &TransactionType::Payout)
},
)),
)
.service(web::resource("/payouts/deactivate").route(web::post().to(
|state, req, payload| {
routing::routing_unlink_config(
state,
req,
payload,
&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, path| {
routing::routing_link_config(state, req, path, &TransactionType::Payment)
},
)),
);
route
}
}
pub struct Customers;
#[cfg(all(
feature = "v2",
feature = "customer_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", feature = "customer_v2"))]
{
route = route
.service(web::resource("/list").route(web::get().to(customers::customers_list)))
.service(
web::resource("/total-payment-methods")
.route(web::get().to(payment_methods::get_total_payment_method_count)),
)
}
#[cfg(all(feature = "oltp", feature = "v2", feature = "customer_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)),
)
.service(
web::resource("/{id}/saved-payment-methods")
.route(web::get().to(payment_methods::list_customer_payment_method_api)),
)
}
route
}
}
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "customer_v2"),
not(feature = "payment_methods_v2"),
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)))
}
#[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(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 = "oltp", feature = "v2", feature = "payment_methods_v2",))]
impl PaymentMethods {
pub fn server(state: AppState) -> Scope {
let mut route = web::scope("/v2/payment-methods").app_data(web::Data::new(state));
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)),
);
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)),
),
);
route
}
}
pub struct PaymentMethods;
#[cfg(all(
any(feature = "v1", feature = "v2"),
any(feature = "olap", feature = "oltp"),
not(feature = "customer_v2")
))]
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("/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-methods-session").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 = "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/organization")
.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)),
),
)
}
}
#[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(
any(feature = "v1", feature = "v2"),
not(feature = "customer_v2"),
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("/{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(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)),
)
}
}
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)),
)
}
}
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("/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::scope("/elimination").service(
web::resource("/toggle")
.route(web::post().to(routing::toggle_elimination_routing)),
),
)
.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 = "olap", feature = "v1"))]
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(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)),
)
}
}
pub struct User;
#[cfg(all(feature = "olap", feature = "v2"))]
impl User {
pub fn server(state: AppState) -> Scope {
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
}
}
#[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));
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)),
);
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)),
),
);
// Role information
route =
route.service(
web::scope("/role")
.service(
web::resource("")
.route(web::get().to(user_role::get_role_from_token))
.route(web::post().to(user_role::create_role)),
)
.service(web::resource("/v2").route(
web::get().to(user_role::get_groups_and_resources_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)),
)
}
route = route.service(
web::scope("/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)),
),
);
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::get().to(webhook_events::list_initial_webhook_delivery_attempts_with_jwtauth),
)))
.service(
web::scope("/{merchant_id}")
.service(web::resource("").route(
web::get().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 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_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)),
)
}
}
| 19,539 | 1,260 |
hyperswitch | crates/router/src/routes/user_role.rs | .rs | 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 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 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,
) -> HttpResponse {
let flow = Flow::GetParentGroupInfo;
Box::pin(api::server_wrap(
flow,
state.clone(),
&http_req,
(),
|state, user_from_token, _, _| async move {
user_role_core::get_parent_group_info(state, user_from_token).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::ListRolesRequest>,
) -> 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
}
| 2,608 | 1,261 |
hyperswitch | crates/router/src/routes/health.rs | .rs | use actix_web::{web, HttpRequest};
use api_models::health_check::RouterHealthCheckResponse;
use router_env::{instrument, logger, tracing, Flow};
use super::app;
use crate::{
core::{api_locking, health_check::HealthCheckInterface},
errors::{self, RouterResponse},
routes::metrics,
services::{api, authentication as auth},
};
/// .
// #[logger::instrument(skip_all, name = "name1", level = "warn", fields( key1 = "val1" ))]
#[instrument(skip_all, fields(flow = ?Flow::HealthCheck))]
// #[actix_web::get("/health")]
pub async fn health() -> impl actix_web::Responder {
metrics::HEALTH_METRIC.add(1, &[]);
logger::info!("Health was called");
actix_web::HttpResponse::Ok().body("health is good")
}
#[instrument(skip_all, fields(flow = ?Flow::DeepHealthCheck))]
pub async fn deep_health_check(
state: web::Data<app::AppState>,
request: HttpRequest,
) -> impl actix_web::Responder {
metrics::HEALTH_METRIC.add(1, &[]);
let flow = Flow::DeepHealthCheck;
Box::pin(api::server_wrap(
flow,
state,
&request,
(),
|state, _: (), _, _| deep_health_check_func(state),
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
async fn deep_health_check_func(
state: app::SessionState,
) -> RouterResponse<RouterHealthCheckResponse> {
logger::info!("Deep health check was called");
logger::debug!("Database health check begin");
let db_status = state.health_check_db().await.map_err(|error| {
let message = error.to_string();
error.change_context(errors::ApiErrorResponse::HealthCheckError {
component: "Database",
message,
})
})?;
logger::debug!("Database health check end");
logger::debug!("Redis health check begin");
let redis_status = state.health_check_redis().await.map_err(|error| {
let message = error.to_string();
error.change_context(errors::ApiErrorResponse::HealthCheckError {
component: "Redis",
message,
})
})?;
logger::debug!("Redis health check end");
logger::debug!("Locker health check begin");
let locker_status = state.health_check_locker().await.map_err(|error| {
let message = error.to_string();
error.change_context(errors::ApiErrorResponse::HealthCheckError {
component: "Locker",
message,
})
})?;
logger::debug!("Locker health check end");
logger::debug!("Analytics health check begin");
#[cfg(feature = "olap")]
let analytics_status = state.health_check_analytics().await.map_err(|error| {
let message = error.to_string();
error.change_context(errors::ApiErrorResponse::HealthCheckError {
component: "Analytics",
message,
})
})?;
logger::debug!("Analytics health check end");
logger::debug!("gRPC health check begin");
#[cfg(feature = "dynamic_routing")]
let grpc_health_check = state.health_check_grpc().await.map_err(|error| {
let message = error.to_string();
error.change_context(errors::ApiErrorResponse::HealthCheckError {
component: "gRPC services",
message,
})
})?;
logger::debug!("gRPC health check end");
logger::debug!("Opensearch health check begin");
#[cfg(feature = "olap")]
let opensearch_status = state.health_check_opensearch().await.map_err(|error| {
let message = error.to_string();
error.change_context(errors::ApiErrorResponse::HealthCheckError {
component: "Opensearch",
message,
})
})?;
logger::debug!("Opensearch health check end");
logger::debug!("Outgoing Request health check begin");
let outgoing_check = state.health_check_outgoing().await.map_err(|error| {
let message = error.to_string();
error.change_context(errors::ApiErrorResponse::HealthCheckError {
component: "Outgoing Request",
message,
})
})?;
logger::debug!("Outgoing Request health check end");
let response = RouterHealthCheckResponse {
database: db_status.into(),
redis: redis_status.into(),
vault: locker_status.into(),
#[cfg(feature = "olap")]
analytics: analytics_status.into(),
#[cfg(feature = "olap")]
opensearch: opensearch_status.into(),
outgoing_request: outgoing_check.into(),
#[cfg(feature = "dynamic_routing")]
grpc_health_check,
};
Ok(api::ApplicationResponse::Json(response))
}
| 1,011 | 1,262 |
hyperswitch | crates/router/src/routes/feature_matrix.rs | .rs | 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::ConnectorData::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();
connector_integration_features.map(|connector_integration_feature_data| {
let supported_payment_methods = 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 connector_about = connector.get_connector_about();
let supported_webhook_flows = connector
.get_supported_webhook_flows()
.map(|webhook_flows| webhook_flows.to_vec());
feature_matrix::ConnectorFeatureMatrixResponse {
name: connector_name.to_uppercase(),
display_name: connector_about.map(|about| about.display_name.to_string()),
description: connector_about.map(|about| about.description.to_string()),
category: connector_about.map(|about| 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()
}
| 1,110 | 1,263 |
hyperswitch | crates/router/src/routes/verification.rs | .rs | use actix_web::{web, HttpRequest, Responder};
use api_models::verifications;
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
use crate::{
core::{api_locking, verification},
services::{api, authentication as auth, authorization::permissions::Permission},
};
#[cfg(all(feature = "olap", feature = "v1"))]
#[instrument(skip_all, fields(flow = ?Flow::Verification))]
pub async fn apple_pay_merchant_registration(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<verifications::ApplepayMerchantVerificationRequest>,
path: web::Path<common_utils::id_type::MerchantId>,
) -> impl Responder {
let flow = Flow::Verification;
let merchant_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, body, _| {
verification::verify_merchant_creds_for_applepay(
state.clone(),
body,
merchant_id.clone(),
auth.profile_id,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::ProfileAccountWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::Verification))]
pub async fn retrieve_apple_pay_verified_domains(
state: web::Data<AppState>,
req: HttpRequest,
params: web::Query<verifications::ApplepayGetVerifiedDomainsParam>,
) -> impl Responder {
let flow = Flow::Verification;
let merchant_id = ¶ms.merchant_id;
let mca_id = ¶ms.merchant_connector_account_id;
Box::pin(api::server_wrap(
flow,
state,
&req,
merchant_id.clone(),
|state, _: auth::AuthenticationData, _, _| {
verification::get_verified_apple_domains_with_mid_mca_id(
state,
merchant_id.to_owned(),
mca_id.clone(),
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::MerchantAccountRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
| 529 | 1,264 |
hyperswitch | crates/router/src/routes/payment_methods.rs | .rs | #[cfg(all(
any(feature = "v1", feature = "v2", feature = "olap", feature = "oltp"),
all(not(feature = "customer_v2"), not(feature = "payment_methods_v2"))
))]
use actix_multipart::form::MultipartForm;
use actix_web::{web, HttpRequest, HttpResponse};
use common_utils::{errors::CustomResult, id_type, transformers::ForeignFrom};
use diesel_models::enums::IntentStatus;
use error_stack::ResultExt;
use hyperswitch_domain_models::{
bulk_tokenization::CardNetworkTokenizeRequest, merchant_key_store::MerchantKeyStore,
};
use router_env::{instrument, logger, tracing, Flow};
use super::app::{AppState, SessionState};
use crate::{
core::{
api_locking,
errors::{self, utils::StorageErrorExt},
payment_methods::{self as payment_methods_routes, cards},
},
services::{self, api, authentication as auth, authorization::permissions::Permission},
types::{
api::payment_methods::{self, PaymentMethodId},
domain,
storage::payment_method::PaymentTokenData,
},
};
#[cfg(all(
any(feature = "v1", feature = "v2", feature = "olap", feature = "oltp"),
not(feature = "customer_v2")
))]
use crate::{
core::{
customers,
payment_methods::{migration, tokenize},
},
types::api::customers::CustomerRequest,
};
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsCreate))]
pub async fn create_payment_method_api(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payment_methods::PaymentMethodCreate>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsCreate;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| async move {
Box::pin(cards::get_client_secret_or_add_payment_method(
&state,
req,
&auth.merchant_account,
&auth.key_store,
))
.await
},
&auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsCreate))]
pub async fn create_payment_method_api(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payment_methods::PaymentMethodCreate>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsCreate;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, req, req_state| async move {
Box::pin(payment_methods_routes::create_payment_method(
&state,
&req_state,
req,
&auth.merchant_account,
&auth.key_store,
&auth.profile,
))
.await
},
&auth::V2ApiKeyAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsCreate))]
pub async fn create_payment_method_intent_api(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payment_methods::PaymentMethodIntentCreate>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsCreate;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| async move {
Box::pin(payment_methods_routes::payment_method_intent_create(
&state,
req,
&auth.merchant_account,
&auth.key_store,
))
.await
},
&auth::V2ApiKeyAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
/// This struct is used internally only
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct PaymentMethodIntentConfirmInternal {
pub id: id_type::GlobalPaymentMethodId,
pub request: payment_methods::PaymentMethodIntentConfirm,
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
impl From<PaymentMethodIntentConfirmInternal> for payment_methods::PaymentMethodIntentConfirm {
fn from(item: PaymentMethodIntentConfirmInternal) -> Self {
item.request
}
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
impl common_utils::events::ApiEventMetric for PaymentMethodIntentConfirmInternal {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::PaymentMethod {
payment_method_id: self.id.clone(),
payment_method_type: Some(self.request.payment_method_type),
payment_method_subtype: Some(self.request.payment_method_subtype),
})
}
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsUpdate))]
pub async fn payment_method_update_api(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::GlobalPaymentMethodId>,
json_payload: web::Json<payment_methods::PaymentMethodUpdate>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsUpdate;
let payment_method_id = path.into_inner();
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
payment_methods_routes::update_payment_method(
state,
auth.merchant_account,
auth.key_store,
req,
&payment_method_id,
)
},
&auth::V2ApiKeyAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsRetrieve))]
pub async fn payment_method_retrieve_api(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsRetrieve;
let payload = web::Json(PaymentMethodId {
payment_method_id: path.into_inner(),
})
.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, pm, _| {
payment_methods_routes::retrieve_payment_method(
state,
pm,
auth.key_store,
auth.merchant_account,
)
},
&auth::V2ApiKeyAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsDelete))]
pub async fn payment_method_delete_api(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsDelete;
let payload = web::Json(PaymentMethodId {
payment_method_id: path.into_inner(),
})
.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, pm, _| {
payment_methods_routes::delete_payment_method(
state,
pm,
auth.key_store,
auth.merchant_account,
)
},
&auth::V2ApiKeyAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsMigrate))]
pub async fn migrate_payment_method_api(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payment_methods::PaymentMethodMigrate>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsMigrate;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, _, req, _| async move {
let merchant_id = req.merchant_id.clone();
let (key_store, merchant_account) = get_merchant_account(&state, &merchant_id).await?;
Box::pin(cards::migrate_payment_method(
state,
req,
&merchant_id,
&merchant_account,
&key_store,
))
.await
},
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
async fn get_merchant_account(
state: &SessionState,
merchant_id: &id_type::MerchantId,
) -> CustomResult<(MerchantKeyStore, domain::MerchantAccount), errors::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(errors::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(errors::ApiErrorResponse::MerchantAccountNotFound)?;
Ok((key_store, merchant_account))
}
#[cfg(all(
any(feature = "v1", feature = "v2", feature = "olap", feature = "oltp"),
not(feature = "customer_v2")
))]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsMigrate))]
pub async fn migrate_payment_methods(
state: web::Data<AppState>,
req: HttpRequest,
MultipartForm(form): MultipartForm<migration::PaymentMethodsMigrateForm>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsMigrate;
let (merchant_id, records, merchant_connector_id) =
match migration::get_payment_method_records(form) {
Ok((merchant_id, records, merchant_connector_id)) => {
(merchant_id, records, merchant_connector_id)
}
Err(e) => return api::log_and_return_error_response(e.into()),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
records,
|state, _, req, _| {
let merchant_id = merchant_id.clone();
let merchant_connector_id = merchant_connector_id.clone();
async move {
let (key_store, merchant_account) =
get_merchant_account(&state, &merchant_id).await?;
// Create customers if they are not already present
customers::migrate_customers(
state.clone(),
req.iter()
.map(|e| CustomerRequest::from((e.clone(), merchant_id.clone())))
.collect(),
merchant_account.clone(),
key_store.clone(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
Box::pin(migration::migrate_payment_methods(
state,
req,
&merchant_id,
&merchant_account,
&key_store,
merchant_connector_id,
))
.await
}
},
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSave))]
pub async fn save_payment_method_api(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payment_methods::PaymentMethodCreate>,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::PaymentMethodSave;
let payload = json_payload.into_inner();
let pm_id = path.into_inner();
let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload) {
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, _| {
Box::pin(cards::add_payment_method_data(
state,
req,
auth.merchant_account,
auth.key_store,
pm_id.clone(),
))
},
&*auth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsList))]
pub async fn list_payment_method_api(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Query<payment_methods::PaymentMethodListRequest>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsList;
let payload = json_payload.into_inner();
let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload) {
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, _| {
// TODO (#7195): Fill platform_merchant_account in the client secret auth and pass it here.
cards::list_payment_methods(state, auth.merchant_account, auth.key_store, req)
},
&*auth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(
any(feature = "v2", feature = "v1"),
not(feature = "payment_methods_v2"),
not(feature = "customer_v2")
))]
/// List payment methods for a Customer
///
/// To filter and list the applicable payment methods for a particular Customer ID
#[utoipa::path(
get,
path = "/customers/{customer_id}/payment_methods",
params (
("accepted_country" = Vec<String>, Query, description = "The two-letter ISO currency code"),
("accepted_currency" = Vec<Currency>, Path, description = "The three-letter ISO currency code"),
("minimum_amount" = i64, Query, description = "The minimum amount accepted for processing by the particular payment method."),
("maximum_amount" = i64, Query, description = "The maximum amount amount accepted for processing by the particular payment method."),
("recurring_payment_enabled" = bool, Query, description = "Indicates whether the payment method is eligible for recurring payments"),
("installment_payment_enabled" = bool, Query, description = "Indicates whether the payment method is eligible for installment payments"),
),
responses(
(status = 200, description = "Payment Methods retrieved", body = CustomerPaymentMethodsListResponse),
(status = 400, description = "Invalid Data"),
(status = 404, description = "Payment Methods does not exist in records")
),
tag = "Payment Methods",
operation_id = "List all Payment Methods for a Customer",
security(("api_key" = []))
)]
#[instrument(skip_all, fields(flow = ?Flow::CustomerPaymentMethodsList))]
pub async fn list_customer_payment_method_api(
state: web::Data<AppState>,
customer_id: web::Path<(id_type::CustomerId,)>,
req: HttpRequest,
query_payload: web::Query<payment_methods::PaymentMethodListRequest>,
) -> HttpResponse {
let flow = Flow::CustomerPaymentMethodsList;
let payload = query_payload.into_inner();
let customer_id = customer_id.into_inner().0;
let ephemeral_auth = match auth::is_ephemeral_auth(req.headers()) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(err),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
cards::do_list_customer_pm_fetch_customer_if_not_passed(
state,
auth.merchant_account,
auth.key_store,
Some(req),
Some(&customer_id),
None,
)
},
&*ephemeral_auth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(
any(feature = "v2", feature = "v1"),
not(feature = "payment_methods_v2"),
not(feature = "customer_v2")
))]
/// List payment methods for a Customer
///
/// To filter and list the applicable payment methods for a particular Customer ID
#[utoipa::path(
get,
path = "/customers/payment_methods",
params (
("client-secret" = String, Path, description = "A secret known only to your application and the authorization server"),
("accepted_country" = Vec<String>, Query, description = "The two-letter ISO currency code"),
("accepted_currency" = Vec<Currency>, Path, description = "The three-letter ISO currency code"),
("minimum_amount" = i64, Query, description = "The minimum amount accepted for processing by the particular payment method."),
("maximum_amount" = i64, Query, description = "The maximum amount amount accepted for processing by the particular payment method."),
("recurring_payment_enabled" = bool, Query, description = "Indicates whether the payment method is eligible for recurring payments"),
("installment_payment_enabled" = bool, Query, description = "Indicates whether the payment method is eligible for installment payments"),
),
responses(
(status = 200, description = "Payment Methods retrieved for customer tied to its respective client-secret passed in the param", body = CustomerPaymentMethodsListResponse),
(status = 400, description = "Invalid Data"),
(status = 404, description = "Payment Methods does not exist in records")
),
tag = "Payment Methods",
operation_id = "List all Payment Methods for a Customer",
security(("publishable_key" = []))
)]
#[instrument(skip_all, fields(flow = ?Flow::CustomerPaymentMethodsList))]
pub async fn list_customer_payment_method_api_client(
state: web::Data<AppState>,
req: HttpRequest,
query_payload: web::Query<payment_methods::PaymentMethodListRequest>,
) -> HttpResponse {
let flow = Flow::CustomerPaymentMethodsList;
let payload = query_payload.into_inner();
let api_key = auth::get_api_key(req.headers()).ok();
let (auth, _, is_ephemeral_auth) =
match auth::get_ephemeral_or_other_auth(req.headers(), false, Some(&payload)).await {
Ok((auth, _auth_flow, is_ephemeral_auth)) => (auth, _auth_flow, is_ephemeral_auth),
Err(e) => return api::log_and_return_error_response(e),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
cards::do_list_customer_pm_fetch_customer_if_not_passed(
state,
auth.merchant_account,
auth.key_store,
Some(req),
None,
is_ephemeral_auth.then_some(api_key).flatten(),
)
},
&*auth,
api_locking::LockAction::NotApplicable,
))
.await
}
/// Generate a form link for collecting payment methods for a customer
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodCollectLink))]
pub async fn initiate_pm_collect_link_flow(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payment_methods::PaymentMethodCollectLinkRequest>,
) -> HttpResponse {
let flow = Flow::PaymentMethodCollectLink;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| {
payment_methods_routes::initiate_pm_collect_link(
state,
auth.merchant_account,
auth.key_store,
req,
)
},
&auth::ApiKeyAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v2", feature = "olap"))]
#[instrument(skip_all, fields(flow = ?Flow::CustomerPaymentMethodsList))]
pub async fn list_customer_payment_method_api(
state: web::Data<AppState>,
customer_id: web::Path<id_type::GlobalCustomerId>,
req: HttpRequest,
query_payload: web::Query<api_models::payment_methods::PaymentMethodListRequest>,
) -> HttpResponse {
let flow = Flow::CustomerPaymentMethodsList;
let payload = query_payload.into_inner();
let customer_id = customer_id.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, _, _| {
payment_methods_routes::list_saved_payment_methods_for_customer(
state,
auth.merchant_account,
auth.key_store,
customer_id.clone(),
)
},
auth::auth_type(
&auth::V2ApiKeyAuth,
&auth::JWTAuth {
permission: Permission::MerchantCustomerRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v2", feature = "olap"))]
#[instrument(skip_all, fields(flow = ?Flow::TotalPaymentMethodCount))]
pub async fn get_total_payment_method_count(
state: web::Data<AppState>,
req: HttpRequest,
) -> HttpResponse {
let flow = Flow::TotalPaymentMethodCount;
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
|state, auth: auth::AuthenticationData, _, _| {
payment_methods_routes::get_total_saved_payment_methods_for_merchant(
state,
auth.merchant_account,
)
},
auth::auth_type(
&auth::V2ApiKeyAuth,
&auth::JWTAuth {
permission: Permission::MerchantCustomerRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
/// Generate a form link for collecting payment methods for a customer
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodCollectLink))]
pub async fn render_pm_collect_link(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<(id_type::MerchantId, String)>,
) -> HttpResponse {
let flow = Flow::PaymentMethodCollectLink;
let (merchant_id, pm_collect_link_id) = path.into_inner();
let payload = payment_methods::PaymentMethodCollectLinkRenderRequest {
merchant_id: merchant_id.clone(),
pm_collect_link_id,
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
payment_methods_routes::render_pm_collect_link(
state,
auth.merchant_account,
auth.key_store,
req,
)
},
&auth::MerchantIdAuth(merchant_id),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsRetrieve))]
pub async fn payment_method_retrieve_api(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsRetrieve;
let payload = web::Json(PaymentMethodId {
payment_method_id: path.into_inner(),
})
.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, pm, _| {
cards::retrieve_payment_method(state, pm, auth.key_store, auth.merchant_account)
},
&auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsUpdate))]
pub async fn payment_method_update_api(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
json_payload: web::Json<payment_methods::PaymentMethodUpdate>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsUpdate;
let payment_method_id = path.into_inner();
let payload = json_payload.into_inner();
let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload) {
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, _| {
cards::update_customer_payment_method(
state,
auth.merchant_account,
req,
&payment_method_id,
auth.key_store,
)
},
&*auth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsDelete))]
pub async fn payment_method_delete_api(
state: web::Data<AppState>,
req: HttpRequest,
payment_method_id: web::Path<(String,)>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsDelete;
let pm = PaymentMethodId {
payment_method_id: payment_method_id.into_inner().0,
};
let ephemeral_auth = match auth::is_ephemeral_auth(req.headers()) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(err),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
pm,
|state, auth: auth::AuthenticationData, req, _| {
cards::delete_payment_method(state, auth.merchant_account, req, auth.key_store)
},
&*ephemeral_auth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::ListCountriesCurrencies))]
pub async fn list_countries_currencies_for_connector_payment_method(
state: web::Data<AppState>,
req: HttpRequest,
query_payload: web::Query<payment_methods::ListCountriesCurrenciesRequest>,
) -> HttpResponse {
let flow = Flow::ListCountriesCurrencies;
let payload = query_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
cards::list_countries_currencies_for_connector_payment_method(
state,
req,
auth.profile_id,
)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::ProfileConnectorWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
permission: Permission::ProfileConnectorWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::DefaultPaymentMethodsSet))]
pub async fn default_payment_method_set_api(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<payment_methods::DefaultPaymentMethod>,
) -> HttpResponse {
let flow = Flow::DefaultPaymentMethodsSet;
let payload = path.into_inner();
let pc = payload.clone();
let customer_id = &pc.customer_id;
let ephemeral_auth = match auth::is_ephemeral_auth(req.headers()) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(err),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, default_payment_method, _| async move {
cards::set_default_payment_method(
&state,
auth.merchant_account.get_id(),
auth.key_store,
customer_id,
default_payment_method.payment_method_id,
auth.merchant_account.storage_scheme,
)
.await
},
&*ephemeral_auth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use api_models::payment_methods::PaymentMethodListRequest;
use super::*;
// #[test]
// fn test_custom_list_deserialization() {
// let dummy_data = "amount=120&recurring_enabled=true&installment_payment_enabled=true";
// let de_query: web::Query<PaymentMethodListRequest> =
// web::Query::from_query(dummy_data).unwrap();
// let de_struct = de_query.into_inner();
// assert_eq!(de_struct.installment_payment_enabled, Some(true))
// }
#[test]
fn test_custom_list_deserialization_multi_amount() {
let dummy_data = "amount=120&recurring_enabled=true&amount=1000";
let de_query: Result<web::Query<PaymentMethodListRequest>, _> =
web::Query::from_query(dummy_data);
assert!(de_query.is_err())
}
}
#[derive(Clone)]
pub struct ParentPaymentMethodToken {
key_for_token: String,
}
impl ParentPaymentMethodToken {
pub fn create_key_for_token(
(parent_pm_token, payment_method): (&String, api_models::enums::PaymentMethod),
) -> Self {
Self {
key_for_token: format!(
"pm_token_{}_{}_hyperswitch",
parent_pm_token, payment_method
),
}
}
pub async fn insert(
&self,
fulfillment_time: i64,
token: PaymentTokenData,
state: &SessionState,
) -> CustomResult<(), errors::ApiErrorResponse> {
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
redis_conn
.serialize_and_set_key_with_expiry(
&self.key_for_token.as_str().into(),
token,
fulfillment_time,
)
.await
.change_context(errors::StorageError::KVError)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add token in redis")?;
Ok(())
}
pub fn should_delete_payment_method_token(&self, status: IntentStatus) -> bool {
// RequiresMerchantAction: When the payment goes for merchant review incase of potential fraud allow payment_method_token to be stored until resolved
![
IntentStatus::RequiresCustomerAction,
IntentStatus::RequiresMerchantAction,
]
.contains(&status)
}
pub async fn delete(&self, state: &SessionState) -> CustomResult<(), errors::ApiErrorResponse> {
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
match redis_conn
.delete_key(&self.key_for_token.as_str().into())
.await
{
Ok(_) => Ok(()),
Err(err) => {
{
logger::info!("Error while deleting redis key: {:?}", err)
};
Ok(())
}
}
}
}
#[cfg(all(
any(feature = "v1", feature = "v2", feature = "olap", feature = "oltp"),
not(feature = "payment_methods_v2")
))]
#[instrument(skip_all, fields(flow = ?Flow::TokenizeCard))]
pub async fn tokenize_card_api(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payment_methods::CardNetworkTokenizeRequest>,
) -> HttpResponse {
let flow = Flow::TokenizeCard;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, _, req, _| async move {
let merchant_id = req.merchant_id.clone();
let (key_store, merchant_account) = get_merchant_account(&state, &merchant_id).await?;
let res = Box::pin(cards::tokenize_card_flow(
&state,
CardNetworkTokenizeRequest::foreign_from(req),
&merchant_account,
&key_store,
))
.await?;
Ok(services::ApplicationResponse::Json(res))
},
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(
any(feature = "v1", feature = "v2", feature = "olap", feature = "oltp"),
not(feature = "payment_methods_v2")
))]
#[instrument(skip_all, fields(flow = ?Flow::TokenizeCardUsingPaymentMethodId))]
pub async fn tokenize_card_using_pm_api(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
json_payload: web::Json<payment_methods::CardNetworkTokenizeRequest>,
) -> HttpResponse {
let flow = Flow::TokenizeCardUsingPaymentMethodId;
let pm_id = path.into_inner();
let mut payload = json_payload.into_inner();
if let payment_methods::TokenizeDataRequest::ExistingPaymentMethod(ref mut pm_data) =
payload.data
{
pm_data.payment_method_id = pm_id;
} else {
return api::log_and_return_error_response(error_stack::report!(
errors::ApiErrorResponse::InvalidDataValue { field_name: "card" }
));
}
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, _, req, _| async move {
let merchant_id = req.merchant_id.clone();
let (key_store, merchant_account) = get_merchant_account(&state, &merchant_id).await?;
let res = Box::pin(cards::tokenize_card_flow(
&state,
CardNetworkTokenizeRequest::foreign_from(req),
&merchant_account,
&key_store,
))
.await?;
Ok(services::ApplicationResponse::Json(res))
},
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(
any(feature = "v1", feature = "v2", feature = "olap", feature = "oltp"),
not(feature = "payment_methods_v2")
))]
#[instrument(skip_all, fields(flow = ?Flow::TokenizeCardBatch))]
pub async fn tokenize_card_batch_api(
state: web::Data<AppState>,
req: HttpRequest,
MultipartForm(form): MultipartForm<tokenize::CardNetworkTokenizeForm>,
) -> HttpResponse {
let flow = Flow::TokenizeCardBatch;
let (merchant_id, records) = match tokenize::get_tokenize_card_form_records(form) {
Ok(res) => res,
Err(e) => return api::log_and_return_error_response(e.into()),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
records,
|state, _, req, _| {
let merchant_id = merchant_id.clone();
async move {
let (key_store, merchant_account) =
get_merchant_account(&state, &merchant_id).await?;
Box::pin(tokenize::tokenize_cards(
&state,
req,
&merchant_account,
&key_store,
))
.await
}
},
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSessionCreate))]
pub async fn payment_methods_session_create(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<api_models::payment_methods::PaymentMethodSessionRequest>,
) -> HttpResponse {
let flow = Flow::PaymentMethodSessionCreate;
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, request, _| async move {
payment_methods_routes::payment_methods_session_create(
state,
auth.merchant_account,
auth.key_store,
request,
)
.await
},
&auth::V2ApiKeyAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSessionUpdate))]
pub async fn payment_methods_session_update(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::GlobalPaymentMethodSessionId>,
json_payload: web::Json<api_models::payment_methods::PaymentMethodsSessionUpdateRequest>,
) -> HttpResponse {
let flow = Flow::PaymentMethodSessionUpdate;
let payment_method_session_id = path.into_inner();
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
let value = payment_method_session_id.clone();
async move {
payment_methods_routes::payment_methods_session_update(
state,
auth.merchant_account,
auth.key_store,
value.clone(),
req,
)
.await
}
},
&auth::V2ApiKeyAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSessionRetrieve))]
pub async fn payment_methods_session_retrieve(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::GlobalPaymentMethodSessionId>,
) -> HttpResponse {
let flow = Flow::PaymentMethodSessionRetrieve;
let payment_method_session_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payment_method_session_id.clone(),
|state, auth: auth::AuthenticationData, payment_method_session_id, _| async move {
payment_methods_routes::payment_methods_session_retrieve(
state,
auth.merchant_account,
auth.key_store,
payment_method_session_id,
)
.await
},
auth::api_or_client_auth(
&auth::V2ApiKeyAuth,
&auth::V2ClientAuth(
common_utils::types::authentication::ResourceId::PaymentMethodSession(
payment_method_session_id,
),
),
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsList))]
pub async fn payment_method_session_list_payment_methods(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::GlobalPaymentMethodSessionId>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsList;
let payment_method_session_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payment_method_session_id.clone(),
|state, auth: auth::AuthenticationData, payment_method_session_id, _| {
payment_methods_routes::list_payment_methods_for_session(
state,
auth.merchant_account,
auth.key_store,
auth.profile,
payment_method_session_id,
)
},
&auth::V2ClientAuth(
common_utils::types::authentication::ResourceId::PaymentMethodSession(
payment_method_session_id,
),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, serde::Serialize)]
struct PaymentMethodsSessionGenericRequest<T: serde::Serialize> {
payment_method_session_id: id_type::GlobalPaymentMethodSessionId,
#[serde(flatten)]
request: T,
}
#[cfg(feature = "v2")]
impl<T: serde::Serialize> common_utils::events::ApiEventMetric
for PaymentMethodsSessionGenericRequest<T>
{
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::PaymentMethodSession {
payment_method_session_id: self.payment_method_session_id.clone(),
})
}
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSessionConfirm))]
pub async fn payment_method_session_confirm(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::GlobalPaymentMethodSessionId>,
json_payload: web::Json<api_models::payment_methods::PaymentMethodSessionConfirmRequest>,
) -> HttpResponse {
let flow = Flow::PaymentMethodSessionConfirm;
let payload = json_payload.into_inner();
let payment_method_session_id = path.into_inner();
let request = PaymentMethodsSessionGenericRequest {
payment_method_session_id: payment_method_session_id.clone(),
request: payload,
};
Box::pin(api::server_wrap(
flow,
state,
&req,
request,
|state, auth: auth::AuthenticationData, request, req_state| {
payment_methods_routes::payment_methods_session_confirm(
state,
req_state,
auth.merchant_account,
auth.key_store,
auth.profile,
request.payment_method_session_id,
request.request,
)
},
&auth::V2ClientAuth(
common_utils::types::authentication::ResourceId::PaymentMethodSession(
payment_method_session_id,
),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSessionUpdateSavedPaymentMethod))]
pub async fn payment_method_session_update_saved_payment_method(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::GlobalPaymentMethodSessionId>,
json_payload: web::Json<
api_models::payment_methods::PaymentMethodSessionUpdateSavedPaymentMethod,
>,
) -> HttpResponse {
let flow = Flow::PaymentMethodSessionUpdateSavedPaymentMethod;
let payload = json_payload.into_inner();
let payment_method_session_id = path.into_inner();
let request = PaymentMethodsSessionGenericRequest {
payment_method_session_id: payment_method_session_id.clone(),
request: payload,
};
Box::pin(api::server_wrap(
flow,
state,
&req,
request,
|state, auth: auth::AuthenticationData, request, _| {
payment_methods_routes::payment_methods_session_update_payment_method(
state,
auth.merchant_account,
auth.key_store,
request.payment_method_session_id,
request.request,
)
},
&auth::V2ClientAuth(
common_utils::types::authentication::ResourceId::PaymentMethodSession(
payment_method_session_id,
),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSessionUpdateSavedPaymentMethod))]
pub async fn payment_method_session_delete_saved_payment_method(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<id_type::GlobalPaymentMethodSessionId>,
json_payload: web::Json<
api_models::payment_methods::PaymentMethodSessionDeleteSavedPaymentMethod,
>,
) -> HttpResponse {
let flow = Flow::PaymentMethodSessionDeleteSavedPaymentMethod;
let payload = json_payload.into_inner();
let payment_method_session_id = path.into_inner();
let request = PaymentMethodsSessionGenericRequest {
payment_method_session_id: payment_method_session_id.clone(),
request: payload,
};
Box::pin(api::server_wrap(
flow,
state,
&req,
request,
|state, auth: auth::AuthenticationData, request, _| {
payment_methods_routes::payment_methods_session_delete_payment_method(
state,
auth.key_store,
auth.merchant_account,
request.request.payment_method_id,
request.payment_method_session_id,
)
},
&auth::V2ClientAuth(
common_utils::types::authentication::ResourceId::PaymentMethodSession(
payment_method_session_id,
),
),
api_locking::LockAction::NotApplicable,
))
.await
}
| 10,015 | 1,265 |
hyperswitch | crates/router/src/routes/configs.rs | .rs | use actix_web::{web, HttpRequest, Responder};
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
use crate::{
core::{api_locking, configs},
services::{api, authentication as auth},
types::api as api_types,
};
#[instrument(skip_all, fields(flow = ?Flow::CreateConfigKey))]
pub async fn config_key_create(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<api_types::Config>,
) -> impl Responder {
let flow = Flow::CreateConfigKey;
let payload = json_payload.into_inner();
api::server_wrap(
flow,
state,
&req,
payload,
|state, _, data, _| configs::set_config(state, data),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
)
.await
}
#[instrument(skip_all, fields(flow = ?Flow::ConfigKeyFetch))]
pub async fn config_key_retrieve(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> impl Responder {
let flow = Flow::ConfigKeyFetch;
let key = path.into_inner();
api::server_wrap(
flow,
state,
&req,
&key,
|state, _, key, _| configs::read_config(state, key),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
)
.await
}
#[instrument(skip_all, fields(flow = ?Flow::ConfigKeyUpdate))]
pub async fn config_key_update(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
json_payload: web::Json<api_types::ConfigUpdate>,
) -> impl Responder {
let flow = Flow::ConfigKeyUpdate;
let mut payload = json_payload.into_inner();
let key = path.into_inner();
payload.key = key;
api::server_wrap(
flow,
state,
&req,
&payload,
|state, _, payload, _| configs::update_config(state, payload),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
)
.await
}
#[instrument(skip_all, fields(flow = ?Flow::ConfigKeyDelete))]
pub async fn config_key_delete(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> impl Responder {
let flow = Flow::ConfigKeyDelete;
let key = path.into_inner();
api::server_wrap(
flow,
state,
&req,
key,
|state, _, key, _| configs::config_delete(state, key),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
)
.await
}
| 618 | 1,266 |
hyperswitch | crates/router/src/routes/blocklist.rs | .rs | use actix_web::{web, HttpRequest, HttpResponse};
use api_models::blocklist as api_blocklist;
use router_env::Flow;
use crate::{
core::{api_locking, blocklist},
routes::AppState,
services::{api, authentication as auth, authorization::permissions::Permission},
};
#[utoipa::path(
post,
path = "/blocklist",
request_body = BlocklistRequest,
responses(
(status = 200, description = "Fingerprint Blocked", body = BlocklistResponse),
(status = 400, description = "Invalid Data")
),
tag = "Blocklist",
operation_id = "Block a Fingerprint",
security(("api_key" = []))
)]
pub async fn add_entry_to_blocklist(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<api_blocklist::AddToBlocklistRequest>,
) -> HttpResponse {
let flow = Flow::AddToBlocklist;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, body, _| {
blocklist::add_entry_to_blocklist(state, auth.merchant_account, body)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::MerchantAccountWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[utoipa::path(
delete,
path = "/blocklist",
request_body = BlocklistRequest,
responses(
(status = 200, description = "Fingerprint Unblocked", body = BlocklistResponse),
(status = 400, description = "Invalid Data")
),
tag = "Blocklist",
operation_id = "Unblock a Fingerprint",
security(("api_key" = []))
)]
pub async fn remove_entry_from_blocklist(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<api_blocklist::DeleteFromBlocklistRequest>,
) -> HttpResponse {
let flow = Flow::DeleteFromBlocklist;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, body, _| {
blocklist::remove_entry_from_blocklist(state, auth.merchant_account, body)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::MerchantAccountWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[utoipa::path(
get,
path = "/blocklist",
params (
("data_kind" = BlocklistDataKind, Query, description = "Kind of the fingerprint list requested"),
),
responses(
(status = 200, description = "Blocked Fingerprints", body = BlocklistResponse),
(status = 400, description = "Invalid Data")
),
tag = "Blocklist",
operation_id = "List Blocked fingerprints of a particular kind",
security(("api_key" = []))
)]
pub async fn list_blocked_payment_methods(
state: web::Data<AppState>,
req: HttpRequest,
query_payload: web::Query<api_blocklist::ListBlocklistQuery>,
) -> HttpResponse {
let flow = Flow::ListBlocklist;
Box::pin(api::server_wrap(
flow,
state,
&req,
query_payload.into_inner(),
|state, auth: auth::AuthenticationData, query, _| {
blocklist::list_blocklist_entries(state, auth.merchant_account, query)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::MerchantAccountRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[utoipa::path(
post,
path = "/blocklist/toggle",
params (
("status" = bool, Query, description = "Boolean value to enable/disable blocklist"),
),
responses(
(status = 200, description = "Blocklist guard enabled/disabled", body = ToggleBlocklistResponse),
(status = 400, description = "Invalid Data")
),
tag = "Blocklist",
operation_id = "Toggle blocklist guard for a particular merchant",
security(("api_key" = []))
)]
pub async fn toggle_blocklist_guard(
state: web::Data<AppState>,
req: HttpRequest,
query_payload: web::Query<api_blocklist::ToggleBlocklistQuery>,
) -> HttpResponse {
let flow = Flow::ListBlocklist;
Box::pin(api::server_wrap(
flow,
state,
&req,
query_payload.into_inner(),
|state, auth: auth::AuthenticationData, query, _| {
blocklist::toggle_blocklist_guard(state, auth.merchant_account, query)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::MerchantAccountWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
| 1,182 | 1,267 |
hyperswitch | crates/router/src/routes/webhook_events.rs | .rs | 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>,
query: web::Query<EventListConstraints>,
) -> impl Responder {
let flow = Flow::WebhookEventInitialDeliveryAttemptList;
let merchant_id = path.into_inner();
let constraints = query.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,
query: web::Query<EventListConstraints>,
) -> impl Responder {
let flow = Flow::WebhookEventInitialDeliveryAttemptList;
let constraints = query.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
}
| 1,131 | 1,268 |
hyperswitch | crates/router/src/routes/poll.rs | .rs | 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,
};
#[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, _| poll::retrieve_poll_status(state, req, auth.merchant_account),
&auth::HeaderAuth(auth::PublishableKeyAuth),
api_locking::LockAction::NotApplicable,
))
.await
}
| 340 | 1,269 |
hyperswitch | crates/router/src/routes/files.rs | .rs | use actix_multipart::Multipart;
use actix_web::{web, HttpRequest, HttpResponse};
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,
};
#[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, _| {
files_create_core(state, auth.merchant_account, auth.key_store, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&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, _| {
files_delete_core(state, auth.merchant_account, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&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>,
) -> HttpResponse {
let flow = Flow::RetrieveFile;
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, _| {
files_retrieve_core(state, auth.merchant_account, auth.key_store, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::DashboardNoPermissionAuth,
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
| 1,010 | 1,270 |
hyperswitch | crates/router/src/routes/cards_info.rs | .rs | use actix_multipart::form::MultipartForm;
use actix_web::{web, HttpRequest, HttpResponse, Responder};
use api_models::cards_info as cards_info_api_types;
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
use crate::{
core::{api_locking, cards_info},
services::{api, authentication as auth},
};
#[cfg(feature = "v1")]
/// Cards Info - Retrieve
///
/// Retrieve the card information given the card bin
#[utoipa::path(
get,
path = "/cards/{bin}",
params(("bin" = String, Path, description = "The first 6 or 9 digits of card")),
responses(
(status = 200, description = "Card iin data found", body = CardInfoResponse),
(status = 404, description = "Card iin data not found")
),
operation_id = "Retrieve card information",
security(("api_key" = []), ("publishable_key" = []))
)]
#[instrument(skip_all, fields(flow = ?Flow::CardsInfo))]
pub async fn card_iin_info(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
payload: web::Query<api_models::cards_info::CardsInfoRequestParams>,
) -> impl Responder {
let card_iin = path.into_inner();
let request_params = payload.into_inner();
let payload = api_models::cards_info::CardsInfoRequest {
client_secret: request_params.client_secret,
card_iin,
};
let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload) {
Ok((auth, _auth_flow)) => (auth, _auth_flow),
Err(e) => return api::log_and_return_error_response(e),
};
Box::pin(api::server_wrap(
Flow::CardsInfo,
state,
&req,
payload,
|state, auth, req, _| {
cards_info::retrieve_card_info(state, auth.merchant_account, auth.key_store, req)
},
&*auth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::CardsInfoCreate))]
pub async fn create_cards_info(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<cards_info_api_types::CardInfoCreateRequest>,
) -> impl Responder {
let payload = json_payload.into_inner();
let flow = Flow::CardsInfoCreate;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
payload,
|state, _, payload, _| cards_info::create_card_info(state, payload),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::CardsInfoUpdate))]
pub async fn update_cards_info(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<cards_info_api_types::CardInfoUpdateRequest>,
) -> impl Responder {
let payload = json_payload.into_inner();
let flow = Flow::CardsInfoUpdate;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
payload,
|state, _, payload, _| cards_info::update_card_info(state, payload),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(
any(feature = "v1", feature = "v2", feature = "olap", feature = "oltp"),
not(feature = "customer_v2")
))]
#[instrument(skip_all, fields(flow = ?Flow::CardsInfoMigrate))]
pub async fn migrate_cards_info(
state: web::Data<AppState>,
req: HttpRequest,
MultipartForm(form): MultipartForm<cards_info::CardsInfoUpdateForm>,
) -> HttpResponse {
let flow = Flow::CardsInfoMigrate;
let records = match cards_info::get_cards_bin_records(form) {
Ok(records) => records,
Err(e) => return api::log_and_return_error_response(e.into()),
};
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
records,
|state, _, payload, _| cards_info::migrate_cards_info(state, payload),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
| 987 | 1,271 |
hyperswitch | crates/router/src/routes/payments/helpers.rs | .rs | 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,
});
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(())
}
| 605 | 1,272 |
hyperswitch | crates/router/src/routes/process_tracker/revenue_recovery.rs | .rs | 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
}
| 248 | 1,273 |
hyperswitch | crates/router/src/routes/files/transformers.rs | .rs | 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,
})
}
| 669 | 1,274 |
hyperswitch | crates/router/src/routes/disputes/utils.rs | .rs | 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,
})
}
| 804 | 1,275 |
hyperswitch | crates/router/src/routes/dummy_connector/core.rs | .rs | 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(all(feature = "dummy_connector", feature = "v1"))]
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))
}
| 1,643 | 1,276 |
hyperswitch | crates/router/src/routes/dummy_connector/utils.rs | .rs | 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::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()? {
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 types::DummyConnectorCard {
pub fn get_flow_from_card_number(
self,
) -> 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" => Ok(types::DummyConnectorCardFlow::NoThreeDS(
types::DummyConnectorStatus::Failed,
Some(errors::DummyConnectorErrors::PaymentDeclined {
message: "Insufficient funds",
}),
)),
"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::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)
}
}
| 2,937 | 1,277 |
hyperswitch | crates/router/src/routes/dummy_connector/consts.rs | .rs | 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");
| 47 | 1,278 |
hyperswitch | crates/router/src/routes/dummy_connector/types.rs | .rs | use api_models::enums::Currency;
use common_utils::{errors::CustomResult, generate_id_with_default_len};
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),
Wallet(DummyConnectorWallet),
PayLater(DummyConnectorPayLater),
}
#[derive(
Default, serde::Serialize, serde::Deserialize, strum::Display, PartialEq, Debug, Clone,
)]
#[serde(rename_all = "lowercase")]
pub enum DummyConnectorPaymentMethodType {
#[default]
Card,
Wallet(DummyConnectorWallet),
PayLater(DummyConnectorPayLater),
}
impl From<DummyConnectorPaymentMethodData> for DummyConnectorPaymentMethodType {
fn from(value: DummyConnectorPaymentMethodData) -> Self {
match value {
DummyConnectorPaymentMethodData::Card(_) => Self::Card,
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::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::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>,
}
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,
}
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>;
| 2,717 | 1,279 |
hyperswitch | crates/router/src/routes/dummy_connector/errors.rs | .rs | #[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))
}
}
}
}
| 872 | 1,280 |
hyperswitch | crates/router/src/routes/dummy_connector/threeds_page.css | .css | @import url('https://fonts.googleapis.com/css2?family=Inter:wght@200;300;400;500;600;700&display=swap');
body {
font-family: Inter;
background-image: url('https://app.hyperswitch.io/images/hyperswitchImages/PostLoginBackground.svg');
display: flex;
background-size: cover;
height: 100%;
padding-top: 3rem;
margin: 0;
align-items: center;
flex-direction: column;
}
.authorize {
color: white;
background-color: #006DF9;
border: 1px solid #006DF9;
box-sizing: border-box;
margin: 1.5rem 0.5rem 1rem 0;
border-radius: 0.25rem;
padding: 0.75rem 1rem;
font-weight: 500;
font-size: 1.1rem;
}
.authorize:hover {
background-color: #0099FF;
border: 1px solid #0099FF;
cursor: pointer;
}
.reject {
background-color: #F7F7F7;
color: black;
border: 1px solid #E8E8E8;
box-sizing: border-box;
border-radius: 0.25rem;
margin-left: 0.5rem;
font-size: 1.1rem;
padding: 0.75rem 1rem;
font-weight: 500;
}
.reject:hover {
cursor: pointer;
background-color: #E8E8E8;
border: 1px solid #E8E8E8;
}
.container {
background-color: white;
width: 33rem;
margin: 1rem 0;
border: 1px solid #E8E8E8;
color: black;
border-radius: 0.25rem;
padding: 1rem 1.4rem 1rem 1.4rem;
font-family: Inter;
}
.container p {
font-weight: 400;
margin-top: 0.5rem 1rem 0.5rem 0.5rem;
color: #151A1F;
opacity: 0.5;
}
b {
font-weight: 600;
}
.disclaimer {
font-size: 1.25rem;
font-weight: 500 !important;
margin-top: 0.5rem !important;
margin-bottom: 0.5rem;
opacity: 1 !important;
}
.heading {
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
margin-bottom: 1rem;
}
.logo {
width: 8rem;
}
.payment_details {
height: 2rem;
display: flex;
margin: 1rem 0 2rem 0;
}
.border_horizontal {
border-top: 1px dashed #151a1f80;
height: 1px;
margin: 0 1rem;
margin-top: 1rem;
width: 20%;
}
.contact {
display: flex;
gap: 10%;
margin: 2rem 0 1rem 0;
height: 3rem;
}
.contact img {
aspect-ratio: 1/1;
height: 2rem;
}
.contact_item {
display: flex;
height: 100%;
flex-direction: column;
justify-content: center;
}
.contact_item p {
margin: 0;
}
.border_vertical {
border-left: 1px solid #151a1f80;
width: 1px;
height: 100%;
}
.email {
justify-content: space-between;
}
.hover_cursor:hover {
cursor: pointer
}
a {
text-decoration: none;
opacity: 0.8;
}
| 902 | 1,281 |
hyperswitch | crates/router/src/routes/metrics/bg_metrics_collector.rs | .rs | 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
}
});
}
| 240 | 1,282 |
hyperswitch | crates/router/src/routes/metrics/utils.rs | .rs | use std::time;
#[inline]
pub async fn time_future<F, R>(future: F) -> (R, time::Duration)
where
F: futures::Future<Output = R>,
{
let start = time::Instant::now();
let result = future.await;
let time_spent = start.elapsed();
(result, time_spent)
}
| 78 | 1,283 |
hyperswitch | crates/router/src/routes/metrics/request.rs | .rs | use super::utils as metric_utils;
use crate::services::ApplicationResponse;
pub async fn record_request_time_metric<F, R>(
future: F,
flow: &impl router_env::types::FlowMetric,
) -> R
where
F: futures::Future<Output = R>,
{
let key = "request_type";
super::REQUESTS_RECEIVED.add(1, router_env::metric_attributes!((key, flow.to_string())));
let (result, time) = metric_utils::time_future(future).await;
super::REQUEST_TIME.record(
time.as_secs_f64(),
router_env::metric_attributes!((key, flow.to_string())),
);
result
}
pub fn status_code_metrics(
status_code: String,
flow: String,
merchant_id: common_utils::id_type::MerchantId,
) {
super::REQUEST_STATUS.add(
1,
router_env::metric_attributes!(
("status_code", status_code),
("flow", flow),
("merchant_id", merchant_id.clone()),
),
)
}
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,
}
}
| 343 | 1,284 |
hyperswitch | crates/router/src/routes/user/theme.rs | .rs | use actix_multipart::form::MultipartForm;
use actix_web::{web, HttpRequest, HttpResponse};
use api_models::user::theme as theme_api;
use common_utils::types::theme::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},
};
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>,
query: web::Query<ThemeLineage>,
) -> HttpResponse {
let flow = Flow::UploadFileToThemeStorage;
let theme_id = path.into_inner();
let payload = theme_api::UploadFileRequest {
lineage: query.into_inner(),
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>,
query: web::Query<ThemeLineage>,
) -> HttpResponse {
let flow = Flow::DeleteTheme;
let theme_id = path.into_inner();
let lineage = query.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
lineage,
|state, _, lineage, _| theme_core::delete_theme(state, theme_id.clone(), lineage),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
| 948 | 1,285 |
hyperswitch | crates/router/src/services/kafka.rs | .rs | use std::{collections::HashMap, sync::Arc};
use common_utils::errors::CustomResult;
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;
use storage_impl::config::TenantConfig;
#[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;
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,
}
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(),
))
},
)?;
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>,
}
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,
})
}
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,
) -> MQResult<()> {
if let Some(negative_event) = old_intent {
self.log_event(&KafkaEvent::old(
&KafkaPaymentIntent::from_storage(&negative_event),
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),
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),
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,
) -> MQResult<()> {
self.log_event(&KafkaEvent::old(
&KafkaPaymentIntent::from_storage(delete_old_intent),
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,
}
}
}
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)
}
}
| 5,485 | 1,286 |
hyperswitch | crates/router/src/services/authorization.rs | .rs | 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(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(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<A: SessionStateInfo>(state: &A) -> RouterResult<Arc<RedisConnectionPool>> {
state
.store()
.get_redis_conn()
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")
}
| 1,028 | 1,287 |
hyperswitch | crates/router/src/services/encryption.rs | .rs | 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)
}
}
| 4,381 | 1,288 |
hyperswitch | crates/router/src/services/api.rs | .rs | pub mod client;
pub mod generic_link_response;
pub mod request;
use std::{
collections::{HashMap, HashSet},
error::Error,
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},
request::RequestContent,
};
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,
},
connector_integration_v2::{
BoxedConnectorIntegrationV2, ConnectorIntegrationAnyV2, ConnectorIntegrationV2,
},
};
use masking::{Maskable, PeekInterface};
use router_env::{instrument, tracing, tracing_actix_web::RequestId, Tag};
use serde::Serialize;
use serde_json::json;
use tera::{Context, Error as TeraError, Tera};
use self::request::{HeaderExt, RequestBuilderExt};
use super::{
authentication::AuthenticateAndFetch,
connector_integration_interface::BoxedConnectorIntegrationInterface,
};
use crate::{
configs::Settings,
consts,
core::{
api_locking,
errors::{self, CustomResult},
payments,
},
events::{
api_logs::{ApiEvent, ApiEventMetric, ApiEventsType},
connector_api_logs::ConnectorEvent,
},
headers, logger,
routes::{
app::{AppStateInfo, ReqState, SessionStateInfo},
metrics, AppState, SessionState,
},
services::{
connector_integration_interface::RouterDataConversion,
generic_link_response::build_generic_link_html,
},
types::{self, api, ErrorResponse},
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 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::RevenueRecoveryRecordBackData, 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,
>;
/// Handle the flow by interacting with connector module
/// `connector_request` is applicable only in case if the `CallConnectorAction` is `Trigger`
/// In other cases, It will be created if required, even if it is not passed
#[instrument(skip_all, fields(connector_name, payment_method))]
pub async fn execute_connector_processing_step<
'b,
'a,
T,
ResourceCommonData: Clone + RouterDataConversion<T, Req, Resp> + 'static,
Req: Debug + Clone + 'static,
Resp: Debug + Clone + 'static,
>(
state: &'b SessionState,
connector_integration: BoxedConnectorIntegrationInterface<T, ResourceCommonData, Req, Resp>,
req: &'b types::RouterData<T, Req, Resp>,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<Request>,
) -> CustomResult<types::RouterData<T, Req, Resp>, errors::ConnectorError>
where
T: Clone + Debug + 'static,
// BoxedConnectorIntegration<T, Req, Resp>: 'b,
{
// If needed add an error stack as follows
// connector_integration.build_request(req).attach_printable("Failed to build request");
tracing::Span::current().record("connector_name", &req.connector);
tracing::Span::current().record("payment_method", req.payment_method.to_string());
logger::debug!(connector_request=?connector_request);
let mut router_data = req.clone();
match call_connector_action {
payments::CallConnectorAction::HandleResponse(res) => {
let response = types::Response {
headers: None,
response: res.into(),
status_code: 200,
};
connector_integration.handle_response(req, None, response)
}
payments::CallConnectorAction::Avoid => Ok(router_data),
payments::CallConnectorAction::StatusUpdate {
status,
error_code,
error_message,
} => {
router_data.status = status;
let error_response = if error_code.is_some() | error_message.is_some() {
Some(ErrorResponse {
code: error_code.unwrap_or(consts::NO_ERROR_CODE.to_string()),
message: error_message.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
status_code: 200, // This status code is ignored in redirection response it will override with 302 status code.
reason: None,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
} else {
None
};
router_data.response = error_response.map(Err).unwrap_or(router_data.response);
Ok(router_data)
}
payments::CallConnectorAction::Trigger => {
metrics::CONNECTOR_CALL_COUNT.add(
1,
router_env::metric_attributes!(
("connector", req.connector.to_string()),
(
"flow",
std::any::type_name::<T>()
.split("::")
.last()
.unwrap_or_default()
),
),
);
let connector_request = match connector_request {
Some(connector_request) => Some(connector_request),
None => connector_integration
.build_request(req, &state.conf.connectors)
.inspect_err(|error| {
if matches!(
error.current_context(),
&errors::ConnectorError::RequestEncodingFailed
| &errors::ConnectorError::RequestEncodingFailedWithReason(_)
) {
metrics::REQUEST_BUILD_FAILURE.add(
1,
router_env::metric_attributes!((
"connector",
req.connector.clone()
)),
)
}
})?,
};
match connector_request {
Some(request) => {
let masked_request_body = match &request.body {
Some(request) => match request {
RequestContent::Json(i)
| RequestContent::FormUrlEncoded(i)
| RequestContent::Xml(i) => i
.masked_serialize()
.unwrap_or(json!({ "error": "failed to mask serialize"})),
RequestContent::FormData(_) => json!({"request_type": "FORM_DATA"}),
RequestContent::RawBytes(_) => json!({"request_type": "RAW_BYTES"}),
},
None => serde_json::Value::Null,
};
let request_url = request.url.clone();
let request_method = request.method;
let current_time = Instant::now();
let response =
call_connector_api(state, request, "execute_connector_processing_step")
.await;
let external_latency = current_time.elapsed().as_millis();
logger::info!(raw_connector_request=?masked_request_body);
let status_code = response
.as_ref()
.map(|i| {
i.as_ref()
.map_or_else(|value| value.status_code, |value| value.status_code)
})
.unwrap_or_default();
let mut connector_event = ConnectorEvent::new(
state.tenant.tenant_id.clone(),
req.connector.clone(),
std::any::type_name::<T>(),
masked_request_body,
request_url,
request_method,
req.payment_id.clone(),
req.merchant_id.clone(),
state.request_id.as_ref(),
external_latency,
req.refund_id.clone(),
req.dispute_id.clone(),
status_code,
);
match response {
Ok(body) => {
let response = match body {
Ok(body) => {
let connector_http_status_code = Some(body.status_code);
let handle_response_result = connector_integration
.handle_response(req, Some(&mut connector_event), body)
.inspect_err(|error| {
if error.current_context()
== &errors::ConnectorError::ResponseDeserializationFailed
{
metrics::RESPONSE_DESERIALIZATION_FAILURE.add(
1,
router_env::metric_attributes!((
"connector",
req.connector.clone(),
)),
)
}
});
match handle_response_result {
Ok(mut data) => {
state.event_handler().log_event(&connector_event);
data.connector_http_status_code =
connector_http_status_code;
// Add up multiple external latencies in case of multiple external calls within the same request.
data.external_latency = Some(
data.external_latency
.map_or(external_latency, |val| {
val + external_latency
}),
);
Ok(data)
}
Err(err) => {
connector_event
.set_error(json!({"error": err.to_string()}));
state.event_handler().log_event(&connector_event);
Err(err)
}
}?
}
Err(body) => {
router_data.connector_http_status_code = Some(body.status_code);
router_data.external_latency = Some(
router_data
.external_latency
.map_or(external_latency, |val| val + external_latency),
);
metrics::CONNECTOR_ERROR_RESPONSE_COUNT.add(
1,
router_env::metric_attributes!((
"connector",
req.connector.clone(),
)),
);
let error = match body.status_code {
500..=511 => {
let error_res = connector_integration
.get_5xx_error_response(
body,
Some(&mut connector_event),
)?;
state.event_handler().log_event(&connector_event);
error_res
}
_ => {
let error_res = connector_integration
.get_error_response(
body,
Some(&mut connector_event),
)?;
if let Some(status) = error_res.attempt_status {
router_data.status = status;
};
state.event_handler().log_event(&connector_event);
error_res
}
};
router_data.response = Err(error);
router_data
}
};
Ok(response)
}
Err(error) => {
connector_event.set_error(json!({"error": error.to_string()}));
state.event_handler().log_event(&connector_event);
if error.current_context().is_upstream_timeout() {
let error_response = 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,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
};
router_data.response = Err(error_response);
router_data.connector_http_status_code = Some(504);
router_data.external_latency = Some(
router_data
.external_latency
.map_or(external_latency, |val| val + external_latency),
);
Ok(router_data)
} else {
Err(error.change_context(
errors::ConnectorError::ProcessingStepFailed(None),
))
}
}
}
}
None => Ok(router_data),
}
}
}
}
#[instrument(skip_all)]
pub async fn call_connector_api(
state: &SessionState,
request: Request,
flow_name: &str,
) -> CustomResult<Result<types::Response, types::Response>, errors::ApiClientError> {
let current_time = Instant::now();
let headers = request.headers.clone();
let url = request.url.clone();
let response = state
.api_client
.send_request(state, request, None, true)
.await;
match response.as_ref() {
Ok(resp) => {
let status_code = resp.status().as_u16();
let elapsed_time = current_time.elapsed();
logger::info!(
?headers,
url,
status_code,
flow=?flow_name,
?elapsed_time
);
}
Err(err) => {
logger::info!(
call_connector_api_error=?err
);
}
}
handle_response(response).await
}
#[instrument(skip_all)]
pub async fn send_request(
state: &SessionState,
request: Request,
option_timeout_secs: Option<u64>,
) -> CustomResult<reqwest::Response, errors::ApiClientError> {
logger::info!(method=?request.method, headers=?request.headers, payload=?request.body, ?request);
let url =
url::Url::parse(&request.url).change_context(errors::ApiClientError::UrlParsingFailed)?;
let client = client::create_client(
&state.conf.proxy,
request.certificate,
request.certificate_key,
)?;
let headers = request.headers.construct_header_map()?;
let metrics_tag = router_env::metric_attributes!((
consts::METRICS_HOST_TAG_NAME,
url.host_str().unwrap_or_default().to_owned()
));
let request = {
match request.method {
Method::Get => client.get(url),
Method::Post => {
let client = client.post(url);
match request.body {
Some(RequestContent::Json(payload)) => client.json(&payload),
Some(RequestContent::FormData(form)) => client.multipart(form),
Some(RequestContent::FormUrlEncoded(payload)) => client.form(&payload),
Some(RequestContent::Xml(payload)) => {
let body = quick_xml::se::to_string(&payload)
.change_context(errors::ApiClientError::BodySerializationFailed)?;
client.body(body).header("Content-Type", "application/xml")
}
Some(RequestContent::RawBytes(payload)) => client.body(payload),
None => client,
}
}
Method::Put => {
let client = client.put(url);
match request.body {
Some(RequestContent::Json(payload)) => client.json(&payload),
Some(RequestContent::FormData(form)) => client.multipart(form),
Some(RequestContent::FormUrlEncoded(payload)) => client.form(&payload),
Some(RequestContent::Xml(payload)) => {
let body = quick_xml::se::to_string(&payload)
.change_context(errors::ApiClientError::BodySerializationFailed)?;
client.body(body).header("Content-Type", "application/xml")
}
Some(RequestContent::RawBytes(payload)) => client.body(payload),
None => client,
}
}
Method::Patch => {
let client = client.patch(url);
match request.body {
Some(RequestContent::Json(payload)) => client.json(&payload),
Some(RequestContent::FormData(form)) => client.multipart(form),
Some(RequestContent::FormUrlEncoded(payload)) => client.form(&payload),
Some(RequestContent::Xml(payload)) => {
let body = quick_xml::se::to_string(&payload)
.change_context(errors::ApiClientError::BodySerializationFailed)?;
client.body(body).header("Content-Type", "application/xml")
}
Some(RequestContent::RawBytes(payload)) => client.body(payload),
None => client,
}
}
Method::Delete => client.delete(url),
}
.add_headers(headers)
.timeout(Duration::from_secs(
option_timeout_secs.unwrap_or(consts::REQUEST_TIME_OUT),
))
};
// We cannot clone the request type, because it has Form trait which is not cloneable. So we are cloning the request builder here.
let cloned_send_request = request.try_clone().map(|cloned_request| async {
cloned_request
.send()
.await
.map_err(|error| match error {
error if error.is_timeout() => {
metrics::REQUEST_BUILD_FAILURE.add(1, &[]);
errors::ApiClientError::RequestTimeoutReceived
}
error if is_connection_closed_before_message_could_complete(&error) => {
metrics::REQUEST_BUILD_FAILURE.add(1, &[]);
errors::ApiClientError::ConnectionClosedIncompleteMessage
}
_ => errors::ApiClientError::RequestNotSent(error.to_string()),
})
.attach_printable("Unable to send request to connector")
});
let send_request = async {
request
.send()
.await
.map_err(|error| match error {
error if error.is_timeout() => {
metrics::REQUEST_BUILD_FAILURE.add(1, &[]);
errors::ApiClientError::RequestTimeoutReceived
}
error if is_connection_closed_before_message_could_complete(&error) => {
metrics::REQUEST_BUILD_FAILURE.add(1, &[]);
errors::ApiClientError::ConnectionClosedIncompleteMessage
}
_ => errors::ApiClientError::RequestNotSent(error.to_string()),
})
.attach_printable("Unable to send request to connector")
};
let response = common_utils::metrics::utils::record_operation_time(
send_request,
&metrics::EXTERNAL_REQUEST_TIME,
metrics_tag,
)
.await;
// Retry once if the response is connection closed.
//
// This is just due to the racy nature of networking.
// hyper has a connection pool of idle connections, and it selected one to send your request.
// Most of the time, hyper will receive the server’s FIN and drop the dead connection from its pool.
// But occasionally, a connection will be selected from the pool
// and written to at the same time the server is deciding to close the connection.
// Since hyper already wrote some of the request,
// it can’t really retry it automatically on a new connection, since the server may have acted already
match response {
Ok(response) => Ok(response),
Err(error)
if error.current_context()
== &errors::ApiClientError::ConnectionClosedIncompleteMessage =>
{
metrics::AUTO_RETRY_CONNECTION_CLOSED.add(1, &[]);
match cloned_send_request {
Some(cloned_request) => {
logger::info!(
"Retrying request due to connection closed before message could complete"
);
common_utils::metrics::utils::record_operation_time(
cloned_request,
&metrics::EXTERNAL_REQUEST_TIME,
metrics_tag,
)
.await
}
None => {
logger::info!("Retrying request due to connection closed before message could complete failed as request is not cloneable");
Err(error)
}
}
}
err @ Err(_) => err,
}
}
fn is_connection_closed_before_message_could_complete(error: &reqwest::Error) -> bool {
let mut source = error.source();
while let Some(err) = source {
if let Some(hyper_err) = err.downcast_ref::<hyper::Error>() {
if hyper_err.is_incomplete_message() {
return true;
}
}
source = err.source();
}
false
}
#[instrument(skip_all)]
async fn handle_response(
response: CustomResult<reqwest::Response, errors::ApiClientError>,
) -> CustomResult<Result<types::Response, types::Response>, errors::ApiClientError> {
response
.map(|response| async {
logger::info!(?response);
let status_code = response.status().as_u16();
let headers = Some(response.headers().to_owned());
match status_code {
200..=202 | 302 | 204 => {
// If needed add log line
// logger:: error!( error_parsing_response=?err);
let response = response
.bytes()
.await
.change_context(errors::ApiClientError::ResponseDecodingFailed)
.attach_printable("Error while waiting for response")?;
Ok(Ok(types::Response {
headers,
response,
status_code,
}))
}
status_code @ 500..=599 => {
let bytes = response.bytes().await.map_err(|error| {
report!(error)
.change_context(errors::ApiClientError::ResponseDecodingFailed)
.attach_printable("Client error response received")
})?;
// let error = match status_code {
// 500 => errors::ApiClientError::InternalServerErrorReceived,
// 502 => errors::ApiClientError::BadGatewayReceived,
// 503 => errors::ApiClientError::ServiceUnavailableReceived,
// 504 => errors::ApiClientError::GatewayTimeoutReceived,
// _ => errors::ApiClientError::UnexpectedServerResponse,
// };
Ok(Err(types::Response {
headers,
response: bytes,
status_code,
}))
}
status_code @ 400..=499 => {
let bytes = response.bytes().await.map_err(|error| {
report!(error)
.change_context(errors::ApiClientError::ResponseDecodingFailed)
.attach_printable("Client error response received")
})?;
/* let error = match status_code {
400 => errors::ApiClientError::BadRequestReceived(bytes),
401 => errors::ApiClientError::UnauthorizedReceived(bytes),
403 => errors::ApiClientError::ForbiddenReceived,
404 => errors::ApiClientError::NotFoundReceived(bytes),
405 => errors::ApiClientError::MethodNotAllowedReceived,
408 => errors::ApiClientError::RequestTimeoutReceived,
422 => errors::ApiClientError::UnprocessableEntityReceived(bytes),
429 => errors::ApiClientError::TooManyRequestsReceived,
_ => errors::ApiClientError::UnexpectedServerResponse,
};
Err(report!(error).attach_printable("Client error response received"))
*/
Ok(Err(types::Response {
headers,
response: bytes,
status_code,
}))
}
_ => Err(report!(errors::ApiClientError::UnexpectedServerResponse)
.attach_printable("Unexpected response from server")),
}
})?
.await
}
#[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 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(),
);
state.event_handler().log_event(&api_event);
metrics::request::status_code_metrics(
status_code.to_string(),
flow.to_string(),
merchant_id.to_owned(),
);
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 = metrics::request::record_request_time_metric(
server_wrap_util(
&flow,
state.clone(),
incoming_request_header,
request,
payload,
func,
api_auth,
lock_action,
),
&flow,
)
.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 {} HTML page", link_type))
}
}
}
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
}
});
match serde_json::to_string(&response) {
Ok(res) => http_response_json_with_headers(res, headers, request_elapsed_time),
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>,
) -> HttpResponse {
let mut response_builder = HttpResponse::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
}
}
#[cfg(feature = "v1")]
impl Authenticate for api_models::payments::PaymentsRequest {
fn get_client_secret(&self) -> Option<&String> {
self.client_secret.as_ref()
}
}
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::PaymentsRetrieveRequest {}
impl Authenticate for api_models::payments::PaymentsCancelRequest {}
impl Authenticate for api_models::payments::PaymentsCaptureRequest {}
impl Authenticate for api_models::payments::PaymentsIncrementalAuthorizationRequest {}
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!(
"{} <script>{}</script>",
html_data, logging_template
)),
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#"
function submitCollectionReference(collectionReference) {{
var redirectPathname = window.location.pathname.replace(/payments\/redirect\/(\w+)\/(\w+)\/\w+/, "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) {{
window.location.replace(redirectUrl);
}}
}}
var allowedHost = "{}";
var collectionField = "{}";
window.addEventListener("message", function(event) {{
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("");
}});
// Redirect within 8 seconds if no collection reference is received
window.setTimeout(submitCollectionReference, 8000);
"#,
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 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: &str) -> String {
format!("<script src=\"{sdk_url}\" onload=\"initializeSDK()\"></script>")
}
fn get_preload_link_html_template(sdk_url: &str) -> 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">"#,
sdk_url = sdk_url
)
}
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)?
}
}
}
#[cfg(test)]
mod tests {
#[test]
fn test_mime_essence() {
assert_eq!(mime::APPLICATION_JSON.essence_str(), "application/json");
}
}
| 36,319 | 1,289 |
hyperswitch | crates/router/src/services/authentication.rs | .rs | use std::str::FromStr;
use actix_web::http::header::HeaderMap;
#[cfg(all(
any(feature = "v2", feature = "v1"),
not(feature = "payment_methods_v2")
))]
use api_models::payment_methods::PaymentMethodCreate;
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
use api_models::payment_methods::PaymentMethodIntentConfirm;
#[cfg(feature = "payouts")]
use api_models::payouts;
use api_models::{payment_methods::PaymentMethodListRequest, payments};
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::{
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)]
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,
},
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 } => 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)]
pub struct ApiKeyAuth;
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)
};
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)?;
// 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(
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 (auth_data, auth_type) = ApiKeyAuth
.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))
}
}
#[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;
#[cfg(feature = "v1")]
#[async_trait]
impl<A> AuthenticateAndFetch<(), A> for AdminApiAuthWithApiKeyFallback
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<((), 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(((), 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");
}
if fallback_merchant_ids
.merchant_ids
.contains(&stored_api_key.merchant_id)
{
return Ok((
(),
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!("`{}` header is invalid", key),
},
)
})
}
#[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_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!("`{}` header is invalid", key),
},
)
})
.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)]
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(),
},
))
}
}
#[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 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,
&self.0,
&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.0,
&profile_id,
)
.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,
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 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;
#[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)
};
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 db_client_secret.resource_id {
common_utils::types::authentication::ResourceId::Payment(global_payment_id) => {
return Err(errors::ApiErrorResponse::Unauthorized.into())
}
common_utils::types::authentication::ResourceId::Customer(global_customer_id) => {
if global_customer_id.get_string_repr() != self.0.to_str() {
return Err(errors::ApiErrorResponse::Unauthorized.into());
}
}
common_utils::types::authentication::ResourceId::PaymentMethodSession(
global_payment_method_session_id,
) => {
if global_payment_method_session_id.get_string_repr() != self.0.to_str() {
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
}
}
#[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,
}
#[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 = "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::PaymentsRetrieveRequest {
fn get_client_secret(&self) -> Option<&String> {
self.client_secret.as_ref()
}
}
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(all(
any(feature = "v2", feature = "v1"),
not(feature = "payment_methods_v2")
))]
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()
}
}
pub fn get_auth_type_and_flow<A: SessionStateInfo + Sync + Send>(
headers: &HeaderMap,
) -> 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(ApiKeyAuth)), api::AuthFlow::Merchant))
}
pub fn check_client_secret_and_get_auth<T>(
headers: &HeaderMap,
payload: &impl ClientSecretFetch,
) -> 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(ApiKeyAuth)), api::AuthFlow::Merchant))
}
pub async fn get_ephemeral_or_other_auth<T>(
headers: &HeaderMap,
is_merchant_flow: bool,
payload: Option<&impl ClientSecretFetch>,
) -> 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(ApiKeyAuth)),
api::AuthFlow::Merchant,
false,
))
} else {
let payload = payload.get_required_value("ClientSecretFetch")?;
let (auth, auth_flow) = check_client_secret_and_get_auth(headers, payload)?;
Ok((auth, auth_flow, false))
}
}
#[cfg(feature = "v1")]
pub fn is_ephemeral_auth<A: SessionStateInfo + Sync + Send>(
headers: &HeaderMap,
) -> RouterResult<Box<dyn AuthenticateAndFetch<AuthenticationData, A>>> {
let api_key = get_api_key(headers)?;
if !api_key.starts_with("epk") {
Ok(Box::new(HeaderAuth(ApiKeyAuth)))
} 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 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(),
})
},
)?)
}
}
| 29,178 | 1,290 |
hyperswitch | crates/router/src/services/email.rs | .rs | pub mod types;
| 4 | 1,291 |
hyperswitch | crates/router/src/services/jwt.rs | .rs | 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)
}
| 221 | 1,292 |
hyperswitch | crates/router/src/services/pm_auth.rs | .rs | 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),
}
}
| 621 | 1,293 |
hyperswitch | crates/router/src/services/openidconnect.rs | .rs | use error_stack::ResultExt;
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,
services::api::client,
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(&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
.change_context(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(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)
.map_err(|e| e.current_context().to_owned())?;
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(state: &SessionState) -> UserResult<std::sync::Arc<RedisConnectionPool>> {
state
.store
.get_redis_conn()
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to get redis connection")
}
| 1,585 | 1,294 |
hyperswitch | crates/router/src/services/logger.rs | .rs | //! Logger of the system.
pub use crate::logger::*;
| 12 | 1,295 |
hyperswitch | crates/router/src/services/connector_integration_interface.rs | .rs | pub use hyperswitch_interfaces::{
authentication::ExternalAuthenticationPayload, connector_integration_interface::*,
connector_integration_v2::ConnectorIntegrationV2, webhooks::IncomingWebhookFlowError,
};
| 39 | 1,296 |
hyperswitch | crates/router/src/services/card_testing_guard.rs | .rs | 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)
}
| 464 | 1,297 |
hyperswitch | crates/router/src/services/authorization/permission_groups.rs | .rs | use std::collections::HashMap;
use common_enums::{EntityType, ParentGroup, PermissionGroup, PermissionScope, Resource};
use strum::IntoEnumIterator;
use super::permissions::{self, ResourceExt};
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::MerchantDetailsView
| Self::AccountView
| Self::ReconOpsView
| Self::ReconReportsView => PermissionScope::Read,
Self::OperationsManage
| Self::ConnectorsManage
| Self::WorkflowsManage
| Self::UsersManage
| Self::MerchantDetailsManage
| Self::OrganizationManage
| Self::AccountManage
| Self::ReconOpsManage
| Self::ReconReportsManage => 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::MerchantDetailsView
| Self::OrganizationManage
| Self::MerchantDetailsManage
| Self::AccountView
| Self::AccountManage => ParentGroup::Account,
Self::ReconOpsView | Self::ReconOpsManage => ParentGroup::ReconOps,
Self::ReconReportsView | Self::ReconReportsManage => ParentGroup::ReconReports,
}
}
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::MerchantDetailsView => vec![Self::MerchantDetailsView],
Self::MerchantDetailsManage => {
vec![Self::MerchantDetailsView, Self::MerchantDetailsManage]
}
Self::OrganizationManage => vec![Self::OrganizationManage],
Self::AccountView => vec![Self::AccountView],
Self::AccountManage => vec![Self::AccountView, Self::AccountManage],
}
}
}
pub trait ParentGroupExt {
fn resources(&self) -> Vec<Resource>;
fn get_descriptions_for_groups(
entity_type: EntityType,
groups: Vec<PermissionGroup>,
) -> HashMap<ParentGroup, String>;
}
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(),
}
}
fn get_descriptions_for_groups(
entity_type: EntityType,
groups: Vec<PermissionGroup>,
) -> HashMap<Self, String> {
Self::iter()
.filter_map(|parent| {
let scopes = groups
.iter()
.filter(|group| group.parent() == parent)
.map(|group| group.scope())
.max()?;
let resources = parent
.resources()
.iter()
.filter(|res| res.entities().iter().any(|entity| entity <= &entity_type))
.map(|res| permissions::get_resource_name(*res, entity_type))
.collect::<Vec<_>>()
.join(", ");
Some((
parent,
format!("{} {}", permissions::get_scope_name(scopes), resources),
))
})
.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 RECON_REPORTS: [Resource; 4] = [
Resource::ReconToken,
Resource::ReconAndSettlementAnalytics,
Resource::ReconReports,
Resource::Account,
];
| 1,510 | 1,298 |
hyperswitch | crates/router/src/services/authorization/permissions.rs | .rs | 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]
},
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]
}
]
}
pub fn get_resource_name(resource: Resource, entity_type: EntityType) -> &'static str {
match (resource, entity_type) {
(Resource::Payment, _) => "Payments",
(Resource::Refund, _) => "Refunds",
(Resource::Dispute, _) => "Disputes",
(Resource::Mandate, _) => "Mandates",
(Resource::Customer, _) => "Customers",
(Resource::Payout, _) => "Payouts",
(Resource::ApiKey, _) => "Api Keys",
(Resource::Connector, _) => "Payment Processors, Payout Processors, Fraud & Risk Managers",
(Resource::Routing, _) => "Routing",
(Resource::RevenueRecovery, _) => "Revenue Recovery",
(Resource::ThreeDsDecisionManager, _) => "3DS Decision Manager",
(Resource::SurchargeDecisionManager, _) => "Surcharge Decision Manager",
(Resource::Analytics, _) => "Analytics",
(Resource::Report, _) => "Operation Reports",
(Resource::User, _) => "Users",
(Resource::WebhookEvent, _) => "Webhook Events",
(Resource::ReconUpload, _) => "Reconciliation File Upload",
(Resource::RunRecon, _) => "Run Reconciliation Process",
(Resource::ReconConfig, _) => "Reconciliation Configurations",
(Resource::ReconToken, _) => "Generate & Verify Reconciliation Token",
(Resource::ReconFiles, _) => "Reconciliation Process Manager",
(Resource::ReconReports, _) => "Reconciliation Reports",
(Resource::ReconAndSettlementAnalytics, _) => "Reconciliation Analytics",
(Resource::Account, EntityType::Profile) => "Business Profile Account",
(Resource::Account, EntityType::Merchant) => "Merchant Account",
(Resource::Account, EntityType::Organization) => "Organization Account",
(Resource::Account, EntityType::Tenant) => "Tenant Account",
}
}
pub fn get_scope_name(scope: PermissionScope) -> &'static str {
match scope {
PermissionScope::Read => "View",
PermissionScope::Write => "View and Manage",
}
}
| 1,027 | 1,299 |
hyperswitch | crates/router/src/services/authorization/info.rs | .rs | use api_models::user_role::GroupInfo;
use common_enums::{ParentGroup, PermissionGroup};
use strum::IntoEnumIterator;
// TODO: To be deprecated
pub fn get_group_authorization_info() -> Vec<GroupInfo> {
PermissionGroup::iter()
.map(get_group_info_from_permission_group)
.collect()
}
// TODO: To be deprecated
fn get_group_info_from_permission_group(group: PermissionGroup) -> GroupInfo {
let description = get_group_description(group);
GroupInfo { group, description }
}
// TODO: To be deprecated
fn get_group_description(group: PermissionGroup) -> &'static str {
match group {
PermissionGroup::OperationsView => {
"View Payments, Refunds, Payouts, Mandates, Disputes and Customers"
}
PermissionGroup::OperationsManage => {
"Create, modify and delete Payments, Refunds, Payouts, Mandates, Disputes and Customers"
}
PermissionGroup::ConnectorsView => {
"View connected Payment Processors, Payout Processors and Fraud & Risk Manager details"
}
PermissionGroup::ConnectorsManage => "Create, modify and delete connectors like Payment Processors, Payout Processors and Fraud & Risk Manager",
PermissionGroup::WorkflowsView => {
"View Routing, 3DS Decision Manager, Surcharge Decision Manager"
}
PermissionGroup::WorkflowsManage => {
"Create, modify and delete Routing, 3DS Decision Manager, Surcharge Decision Manager"
}
PermissionGroup::AnalyticsView => "View Analytics",
PermissionGroup::UsersView => "View Users",
PermissionGroup::UsersManage => "Manage and invite Users to the Team",
PermissionGroup::MerchantDetailsView | PermissionGroup::AccountView => "View Merchant Details",
PermissionGroup::MerchantDetailsManage | PermissionGroup::AccountManage => "Create, modify and delete Merchant Details like api keys, webhooks, etc",
PermissionGroup::OrganizationManage => "Manage organization level tasks like create new Merchant accounts, Organization level roles, etc",
PermissionGroup::ReconReportsView => "View reconciliation reports and analytics",
PermissionGroup::ReconReportsManage => "Manage reconciliation reports",
PermissionGroup::ReconOpsView => "View and access all reconciliation operations including reports and analytics",
PermissionGroup::ReconOpsManage => "Manage all reconciliation operations including reports and analytics",
}
}
pub fn get_parent_group_description(group: ParentGroup) -> &'static str {
match group {
ParentGroup::Operations => "Payments, Refunds, Payouts, Mandates, Disputes and Customers",
ParentGroup::Connectors => "Create, modify and delete connectors like Payment Processors, Payout Processors and Fraud & Risk Manager",
ParentGroup::Workflows => "Create, modify and delete Routing, 3DS Decision Manager, Surcharge Decision Manager",
ParentGroup::Analytics => "View Analytics",
ParentGroup::Users => "Manage and invite Users to the Team",
ParentGroup::Account => "Create, modify and delete Merchant Details like api keys, webhooks, etc",
ParentGroup::ReconOps => "View, manage reconciliation operations like upload and process files, run reconciliation etc",
ParentGroup::ReconReports => "View, manage reconciliation reports and analytics",
}
}
| 699 | 1,300 |
hyperswitch | crates/router/src/services/authorization/roles.rs | .rs | #[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 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,
}
}
}
| 1,176 | 1,301 |
hyperswitch | crates/router/src/services/authorization/roles/predefined_roles.rs | .rs | use std::collections::HashMap;
use common_enums::{EntityType, PermissionGroup, RoleScope};
use once_cell::sync::Lazy;
use super::RoleInfo;
use crate::consts;
pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::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::MerchantDetailsView,
PermissionGroup::AccountView,
PermissionGroup::MerchantDetailsManage,
PermissionGroup::AccountManage,
PermissionGroup::OrganizationManage,
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::MerchantDetailsView,
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,
},
);
// 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::MerchantDetailsView,
PermissionGroup::AccountView,
PermissionGroup::MerchantDetailsManage,
PermissionGroup::AccountManage,
PermissionGroup::OrganizationManage,
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::MerchantDetailsView,
PermissionGroup::AccountView,
PermissionGroup::MerchantDetailsManage,
PermissionGroup::AccountManage,
PermissionGroup::OrganizationManage,
PermissionGroup::ReconOpsView,
PermissionGroup::ReconOpsManage,
PermissionGroup::ReconReportsView,
PermissionGroup::ReconReportsManage,
],
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::MerchantDetailsView,
PermissionGroup::AccountView,
PermissionGroup::MerchantDetailsManage,
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::MerchantDetailsView,
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::MerchantDetailsView,
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::MerchantDetailsView,
PermissionGroup::AccountView,
PermissionGroup::MerchantDetailsManage,
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::MerchantDetailsView,
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::MerchantDetailsView,
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::MerchantDetailsView,
PermissionGroup::AccountView,
PermissionGroup::MerchantDetailsManage,
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::MerchantDetailsView,
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::MerchantDetailsView,
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::MerchantDetailsView,
PermissionGroup::AccountView,
PermissionGroup::MerchantDetailsManage,
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::MerchantDetailsView,
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::MerchantDetailsView,
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
});
| 3,073 | 1,302 |
hyperswitch | crates/router/src/services/api/client.rs | .rs | use std::time::Duration;
use base64::Engine;
use error_stack::ResultExt;
use http::{HeaderValue, Method};
use masking::{ExposeInterface, PeekInterface};
use once_cell::sync::OnceCell;
use reqwest::multipart::Form;
use router_env::tracing_actix_web::RequestId;
use super::{request::Maskable, Request};
use crate::{
configs::settings::Proxy,
consts::BASE64_ENGINE,
core::errors::{ApiClientError, CustomResult},
routes::SessionState,
};
static DEFAULT_CLIENT: OnceCell<reqwest::Client> = OnceCell::new();
fn get_client_builder(
proxy_config: &Proxy,
) -> CustomResult<reqwest::ClientBuilder, ApiClientError> {
let mut client_builder = reqwest::Client::builder()
.redirect(reqwest::redirect::Policy::none())
.pool_idle_timeout(Duration::from_secs(
proxy_config
.idle_pool_connection_timeout
.unwrap_or_default(),
));
let proxy_exclusion_config =
reqwest::NoProxy::from_string(&proxy_config.bypass_proxy_hosts.clone().unwrap_or_default());
// Proxy all HTTPS traffic through the configured HTTPS proxy
if let Some(url) = proxy_config.https_url.as_ref() {
client_builder = client_builder.proxy(
reqwest::Proxy::https(url)
.change_context(ApiClientError::InvalidProxyConfiguration)
.attach_printable("HTTPS proxy configuration error")?
.no_proxy(proxy_exclusion_config.clone()),
);
}
// Proxy all HTTP traffic through the configured HTTP proxy
if let Some(url) = proxy_config.http_url.as_ref() {
client_builder = client_builder.proxy(
reqwest::Proxy::http(url)
.change_context(ApiClientError::InvalidProxyConfiguration)
.attach_printable("HTTP proxy configuration error")?
.no_proxy(proxy_exclusion_config),
);
}
Ok(client_builder)
}
fn get_base_client(proxy_config: &Proxy) -> CustomResult<reqwest::Client, ApiClientError> {
Ok(DEFAULT_CLIENT
.get_or_try_init(|| {
get_client_builder(proxy_config)?
.build()
.change_context(ApiClientError::ClientConstructionFailed)
.attach_printable("Failed to construct base client")
})?
.clone())
}
// We may need to use outbound proxy to connect to external world.
// Precedence will be the environment variables, followed by the config.
pub fn create_client(
proxy_config: &Proxy,
client_certificate: Option<masking::Secret<String>>,
client_certificate_key: Option<masking::Secret<String>>,
) -> CustomResult<reqwest::Client, ApiClientError> {
match (client_certificate, client_certificate_key) {
(Some(encoded_certificate), Some(encoded_certificate_key)) => {
let client_builder = get_client_builder(proxy_config)?;
let identity = create_identity_from_certificate_and_key(
encoded_certificate.clone(),
encoded_certificate_key,
)?;
let certificate_list = create_certificate(encoded_certificate)?;
let client_builder = certificate_list
.into_iter()
.fold(client_builder, |client_builder, certificate| {
client_builder.add_root_certificate(certificate)
});
client_builder
.identity(identity)
.use_rustls_tls()
.build()
.change_context(ApiClientError::ClientConstructionFailed)
.attach_printable("Failed to construct client with certificate and certificate key")
}
_ => get_base_client(proxy_config),
}
}
pub fn create_identity_from_certificate_and_key(
encoded_certificate: masking::Secret<String>,
encoded_certificate_key: masking::Secret<String>,
) -> Result<reqwest::Identity, error_stack::Report<ApiClientError>> {
let decoded_certificate = BASE64_ENGINE
.decode(encoded_certificate.expose())
.change_context(ApiClientError::CertificateDecodeFailed)?;
let decoded_certificate_key = BASE64_ENGINE
.decode(encoded_certificate_key.expose())
.change_context(ApiClientError::CertificateDecodeFailed)?;
let certificate = String::from_utf8(decoded_certificate)
.change_context(ApiClientError::CertificateDecodeFailed)?;
let certificate_key = String::from_utf8(decoded_certificate_key)
.change_context(ApiClientError::CertificateDecodeFailed)?;
let key_chain = format!("{}{}", certificate_key, certificate);
reqwest::Identity::from_pem(key_chain.as_bytes())
.change_context(ApiClientError::CertificateDecodeFailed)
}
pub fn create_certificate(
encoded_certificate: masking::Secret<String>,
) -> Result<Vec<reqwest::Certificate>, error_stack::Report<ApiClientError>> {
let decoded_certificate = BASE64_ENGINE
.decode(encoded_certificate.expose())
.change_context(ApiClientError::CertificateDecodeFailed)?;
let certificate = String::from_utf8(decoded_certificate)
.change_context(ApiClientError::CertificateDecodeFailed)?;
reqwest::Certificate::from_pem_bundle(certificate.as_bytes())
.change_context(ApiClientError::CertificateDecodeFailed)
}
pub trait RequestBuilder: Send + Sync {
fn json(&mut self, body: serde_json::Value);
fn url_encoded_form(&mut self, body: serde_json::Value);
fn timeout(&mut self, timeout: Duration);
fn multipart(&mut self, form: Form);
fn header(&mut self, key: String, value: Maskable<String>) -> CustomResult<(), ApiClientError>;
fn send(
self,
) -> CustomResult<
Box<
(dyn core::future::Future<Output = Result<reqwest::Response, reqwest::Error>>
+ 'static),
>,
ApiClientError,
>;
}
#[async_trait::async_trait]
pub trait ApiClient: dyn_clone::DynClone
where
Self: Send + Sync,
{
fn request(
&self,
method: Method,
url: String,
) -> CustomResult<Box<dyn RequestBuilder>, ApiClientError>;
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>;
async fn send_request(
&self,
state: &SessionState,
request: Request,
option_timeout_secs: Option<u64>,
forward_to_kafka: bool,
) -> CustomResult<reqwest::Response, ApiClientError>;
fn add_request_id(&mut self, request_id: RequestId);
fn get_request_id(&self) -> Option<String>;
fn add_flow_name(&mut self, flow_name: String);
}
dyn_clone::clone_trait_object!(ApiClient);
#[derive(Clone)]
pub struct ProxyClient {
proxy_config: Proxy,
client: reqwest::Client,
request_id: Option<String>,
}
impl ProxyClient {
pub fn new(proxy_config: &Proxy) -> CustomResult<Self, ApiClientError> {
let client = get_client_builder(proxy_config)?
.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 = get_client_builder(&self.proxy_config)?;
let identity =
create_identity_from_certificate_and_key(certificate, certificate_key)?;
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,
state: &SessionState,
request: Request,
option_timeout_secs: Option<u64>,
_forward_to_kafka: bool,
) -> CustomResult<reqwest::Response, ApiClientError> {
crate::services::send_request(state, request, option_timeout_secs).await
}
fn add_request_id(&mut self, request_id: RequestId) {
self.request_id
.replace(request_id.as_hyphenated().to_string());
}
fn get_request_id(&self) -> Option<String> {
self.request_id.clone()
}
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: &SessionState,
_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<String> {
// [#2066]: Add Mock implementation for ApiClient
None
}
fn add_flow_name(&mut self, _flow_name: String) {}
}
| 2,825 | 1,303 |
hyperswitch | crates/router/src/services/api/request.rs | .rs | use std::str::FromStr;
pub use common_utils::request::ContentType;
use common_utils::request::Headers;
use error_stack::ResultExt;
pub use masking::{Mask, Maskable};
use router_env::{instrument, tracing};
use crate::core::errors::{self, CustomResult};
pub(super) trait HeaderExt {
fn construct_header_map(
self,
) -> CustomResult<reqwest::header::HeaderMap, errors::ApiClientError>;
}
impl HeaderExt for Headers {
fn construct_header_map(
self,
) -> CustomResult<reqwest::header::HeaderMap, errors::ApiClientError> {
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
self.into_iter().try_fold(
HeaderMap::new(),
|mut header_map, (header_name, header_value)| {
let header_name = HeaderName::from_str(&header_name)
.change_context(errors::ApiClientError::HeaderMapConstructionFailed)?;
let header_value = header_value.into_inner();
let header_value = HeaderValue::from_str(&header_value)
.change_context(errors::ApiClientError::HeaderMapConstructionFailed)?;
header_map.append(header_name, header_value);
Ok(header_map)
},
)
}
}
pub(super) trait RequestBuilderExt {
fn add_headers(self, headers: reqwest::header::HeaderMap) -> Self;
}
impl RequestBuilderExt for reqwest::RequestBuilder {
#[instrument(skip_all)]
fn add_headers(mut self, headers: reqwest::header::HeaderMap) -> Self {
self = self.headers(headers);
self
}
}
| 342 | 1,304 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.