Skip to content

Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation

feat(core): diesel models and db interface changes for authentication table (#3859)

Hrithikesh816266819928
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index e0b6a1cc5a..6b25b692c1 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -2172,6 +2172,91 @@ pub enum ApplePayFlow {
Manual,
}
+#[derive(
+ Clone,
+ Debug,
+ Eq,
+ Default,
+ Hash,
+ PartialEq,
+ serde::Deserialize,
+ serde::Serialize,
+ strum::Display,
+ strum::EnumString,
+ utoipa::ToSchema,
+ Copy,
+)]
+#[router_derive::diesel_enum(storage_type = "text")]
+#[serde(rename_all = "snake_case")]
+#[strum(serialize_all = "snake_case")]
+pub enum AuthenticationStatus {
+ #[default]
+ Started,
+ Pending,
+ Success,
+ Failed,
+}
+
+impl AuthenticationStatus {
+ pub fn is_terminal_status(&self) -> bool {
+ match self {
+ Self::Started | Self::Pending => false,
+ Self::Success | Self::Failed => true,
+ }
+ }
+
+ pub fn is_failed(&self) -> bool {
+ self == &Self::Failed
+ }
+}
+
+#[derive(
+ Clone,
+ Debug,
+ Eq,
+ Default,
+ Hash,
+ PartialEq,
+ serde::Deserialize,
+ serde::Serialize,
+ strum::Display,
+ strum::EnumString,
+ utoipa::ToSchema,
+ Copy,
+)]
+#[router_derive::diesel_enum(storage_type = "text")]
+#[serde(rename_all = "snake_case")]
+#[strum(serialize_all = "snake_case")]
+pub enum DecoupledAuthenticationType {
+ #[default]
+ Challenge,
+ Frictionless,
+}
+
+#[derive(
+ Clone,
+ Debug,
+ Eq,
+ Default,
+ Hash,
+ PartialEq,
+ serde::Deserialize,
+ serde::Serialize,
+ strum::Display,
+ strum::EnumString,
+ utoipa::ToSchema,
+ Copy,
+)]
+#[router_derive::diesel_enum(storage_type = "text")]
+#[serde(rename_all = "snake_case")]
+#[strum(serialize_all = "snake_case")]
+pub enum AuthenticationLifecycleStatus {
+ Used,
+ #[default]
+ Unused,
+ Expired,
+}
+
#[derive(
Clone,
Copy,
diff --git a/crates/diesel_models/src/authentication.rs b/crates/diesel_models/src/authentication.rs
new file mode 100644
index 0000000000..f9380cf398
--- /dev/null
+++ b/crates/diesel_models/src/authentication.rs
@@ -0,0 +1,170 @@
+use diesel::{AsChangeset, Identifiable, Insertable, Queryable};
+use serde::{self, Deserialize, Serialize};
+use serde_json;
+
+use crate::schema::authentication;
+
+#[derive(Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Serialize, Deserialize)]
+#[diesel(table_name = authentication, primary_key(authentication_id))]
+pub struct Authentication {
+ pub authentication_id: String,
+ pub merchant_id: String,
+ pub authentication_connector: String,
+ pub connector_authentication_id: Option<String>,
+ pub authentication_data: Option<serde_json::Value>,
+ pub payment_method_id: String,
+ pub authentication_type: Option<common_enums::DecoupledAuthenticationType>,
+ pub authentication_status: common_enums::AuthenticationStatus,
+ pub authentication_lifecycle_status: common_enums::AuthenticationLifecycleStatus,
+ #[serde(with = "common_utils::custom_serde::iso8601")]
+ pub created_at: time::PrimitiveDateTime,
+ #[serde(with = "common_utils::custom_serde::iso8601")]
+ pub modified_at: time::PrimitiveDateTime,
+ pub error_message: Option<String>,
+ pub error_code: Option<String>,
+ pub connector_metadata: Option<serde_json::Value>,
+}
+
+#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Insertable)]
+#[diesel(table_name = authentication)]
+pub struct AuthenticationNew {
+ pub authentication_id: String,
+ pub merchant_id: String,
+ pub authentication_connector: String,
+ pub connector_authentication_id: Option<String>,
+ pub authentication_data: Option<serde_json::Value>,
+ pub payment_method_id: String,
+ pub authentication_type: Option<common_enums::DecoupledAuthenticationType>,
+ pub authentication_status: common_enums::AuthenticationStatus,
+ pub authentication_lifecycle_status: common_enums::AuthenticationLifecycleStatus,
+ pub error_message: Option<String>,
+ pub error_code: Option<String>,
+ pub connector_metadata: Option<serde_json::Value>,
+}
+
+#[derive(Debug)]
+pub enum AuthenticationUpdate {
+ AuthenticationDataUpdate {
+ authentication_data: Option<serde_json::Value>,
+ connector_authentication_id: Option<String>,
+ payment_method_id: Option<String>,
+ authentication_type: Option<common_enums::DecoupledAuthenticationType>,
+ authentication_status: Option<common_enums::AuthenticationStatus>,
+ authentication_lifecycle_status: Option<common_enums::AuthenticationLifecycleStatus>,
+ connector_metadata: Option<serde_json::Value>,
+ },
+ PostAuthorizationUpdate {
+ authentication_lifecycle_status: common_enums::AuthenticationLifecycleStatus,
+ },
+ ErrorUpdate {
+ error_message: Option<String>,
+ error_code: Option<String>,
+ authentication_status: common_enums::AuthenticationStatus,
+ connector_authentication_id: Option<String>,
+ },
+}
+
+#[derive(Clone, Debug, Eq, PartialEq, AsChangeset, Serialize, Deserialize)]
+#[diesel(table_name = authentication)]
+pub struct AuthenticationUpdateInternal {
+ pub connector_authentication_id: Option<String>,
+ pub authentication_data: Option<serde_json::Value>,
+ pub payment_method_id: Option<String>,
+ pub authentication_type: Option<common_enums::DecoupledAuthenticationType>,
+ pub authentication_status: Option<common_enums::AuthenticationStatus>,
+ pub authentication_lifecycle_status: Option<common_enums::AuthenticationLifecycleStatus>,
+ pub modified_at: time::PrimitiveDateTime,
+ pub error_message: Option<String>,
+ pub error_code: Option<String>,
+ pub connector_metadata: Option<serde_json::Value>,
+}
+
+impl AuthenticationUpdateInternal {
+ pub fn apply_changeset(self, source: Authentication) -> Authentication {
+ let Self {
+ connector_authentication_id,
+ authentication_data,
+ payment_method_id,
+ authentication_type,
+ authentication_status,
+ authentication_lifecycle_status,
+ modified_at: _,
+ error_code,
+ error_message,
+ connector_metadata,
+ } = self;
+ Authentication {
+ connector_authentication_id: connector_authentication_id
+ .or(source.connector_authentication_id),
+ authentication_data: authentication_data.or(source.authentication_data),
+ payment_method_id: payment_method_id.unwrap_or(source.payment_method_id),
+ authentication_type: authentication_type.or(source.authentication_type),
+ authentication_status: authentication_status.unwrap_or(source.authentication_status),
+ authentication_lifecycle_status: authentication_lifecycle_status
+ .unwrap_or(source.authentication_lifecycle_status),
+ modified_at: common_utils::date_time::now(),
+ error_code: error_code.or(source.error_code),
+ error_message: error_message.or(source.error_message),
+ connector_metadata: connector_metadata.or(source.connector_metadata),
+ ..source
+ }
+ }
+}
+
+impl From<AuthenticationUpdate> for AuthenticationUpdateInternal {
+ fn from(auth_update: AuthenticationUpdate) -> Self {
+ match auth_update {
+ AuthenticationUpdate::AuthenticationDataUpdate {
+ authentication_data,
+ connector_authentication_id,
+ authentication_type,
+ authentication_status,
+ payment_method_id,
+ authentication_lifecycle_status,
+ connector_metadata,
+ } => Self {
+ authentication_data,
+ connector_authentication_id,
+ authentication_type,
+ authentication_status,
+ authentication_lifecycle_status,
+ modified_at: common_utils::date_time::now(),
+ payment_method_id,
+ error_message: None,
+ error_code: None,
+ connector_metadata,
+ },
+ AuthenticationUpdate::ErrorUpdate {
+ error_message,
+ error_code,
+ authentication_status,
+ connector_authentication_id,
+ } => Self {
+ error_code,
+ error_message,
+ authentication_status: Some(authentication_status),
+ authentication_data: None,
+ connector_authentication_id,
+ authentication_type: None,
+ authentication_lifecycle_status: None,
+ modified_at: common_utils::date_time::now(),
+ payment_method_id: None,
+ connector_metadata: None,
+ },
+ AuthenticationUpdate::PostAuthorizationUpdate {
+ authentication_lifecycle_status,
+ } => Self {
+ connector_authentication_id: None,
+ authentication_data: None,
+ payment_method_id: None,
+ authentication_type: None,
+ authentication_status: None,
+ authentication_lifecycle_status: Some(authentication_lifecycle_status),
+ modified_at: common_utils::date_time::now(),
+ error_message: None,
+ error_code: None,
+ connector_metadata: None,
+ },
+ }
+ }
+}
diff --git a/crates/diesel_models/src/query/authentication.rs b/crates/diesel_models/src/query/authentication.rs
new file mode 100644
index 0000000000..60e635ad12
--- /dev/null
+++ b/crates/diesel_models/src/query/authentication.rs
@@ -0,0 +1,72 @@
+use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};
+
+use super::generics;
+use crate::{
+ authentication::{
+ Authentication, AuthenticationNew, AuthenticationUpdate, AuthenticationUpdateInternal,
+ },
+ errors,
+ schema::authentication::dsl,
+ PgPooledConn, StorageResult,
+};
+
+impl AuthenticationNew {
+ pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Authentication> {
+ generics::generic_insert(conn, self).await
+ }
+}
+
+impl Authentication {
+ pub async fn update_by_merchant_id_authentication_id(
+ conn: &PgPooledConn,
+ merchant_id: String,
+ authentication_id: String,
+ authorization_update: AuthenticationUpdate,
+ ) -> StorageResult<Self> {
+ match generics::generic_update_with_unique_predicate_get_result::<
+ <Self as HasTable>::Table,
+ _,
+ _,
+ _,
+ >(
+ conn,
+ dsl::merchant_id
+ .eq(merchant_id.to_owned())
+ .and(dsl::authentication_id.eq(authentication_id.to_owned())),
+ AuthenticationUpdateInternal::from(authorization_update),
+ )
+ .await
+ {
+ Err(error) => match error.current_context() {
+ errors::DatabaseError::NotFound => Err(error.attach_printable(
+ "Authentication with the given Authentication ID does not exist",
+ )),
+ errors::DatabaseError::NoFieldsToUpdate => {
+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
+ conn,
+ dsl::merchant_id
+ .eq(merchant_id.to_owned())
+ .and(dsl::authentication_id.eq(authentication_id.to_owned())),
+ )
+ .await
+ }
+ _ => Err(error),
+ },
+ result => result,
+ }
+ }
+
+ pub async fn find_by_merchant_id_authentication_id(
+ conn: &PgPooledConn,
+ merchant_id: &str,
+ authentication_id: &str,
+ ) -> StorageResult<Self> {
+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
+ conn,
+ dsl::merchant_id
+ .eq(merchant_id.to_owned())
+ .and(dsl::authentication_id.eq(authentication_id.to_owned())),
+ )
+ .await
+ }
+}
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 35239ce026..49ba814709 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -58,6 +58,38 @@ diesel::table! {
}
}
+diesel::table! {
+ use diesel::sql_types::*;
+ use crate::enums::diesel_exports::*;
+
+ authentication (authentication_id) {
+ #[max_length = 64]
+ authentication_id -> Varchar,
+ #[max_length = 64]
+ merchant_id -> Varchar,
+ #[max_length = 64]
+ authentication_connector -> Varchar,
+ #[max_length = 64]
+ connector_authentication_id -> Nullable<Varchar>,
+ authentication_data -> Nullable<Jsonb>,
+ #[max_length = 64]
+ payment_method_id -> Varchar,
+ #[max_length = 64]
+ authentication_type -> Nullable<Varchar>,
+ #[max_length = 64]
+ authentication_status -> Varchar,
+ #[max_length = 64]
+ authentication_lifecycle_status -> Varchar,
+ created_at -> Timestamp,
+ modified_at -> Timestamp,
+ #[max_length = 64]
+ error_message -> Nullable<Varchar>,
+ #[max_length = 64]
+ error_code -> Nullable<Varchar>,
+ connector_metadata -> Nullable<Jsonb>,
+ }
+}
+
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
@@ -1108,6 +1140,7 @@ diesel::table! {
diesel::allow_tables_to_appear_in_same_query!(
address,
api_keys,
+ authentication,
blocklist,
blocklist_fingerprint,
blocklist_lookup,
diff --git a/crates/router/src/db/authentication.rs b/crates/router/src/db/authentication.rs
new file mode 100644
index 0000000000..1916a326c7
--- /dev/null
+++ b/crates/router/src/db/authentication.rs
@@ -0,0 +1,159 @@
+use diesel_models::authentication::AuthenticationUpdateInternal;
+use error_stack::IntoReport;
+use router_env::{instrument, tracing};
+
+use super::{MockDb, Store};
+use crate::{
+ connection,
+ core::errors::{self, CustomResult},
+ types::storage,
+};
+
+#[async_trait::async_trait]
+pub trait AuthenticationInterface {
+ async fn insert_authentication(
+ &self,
+ authentication: storage::AuthenticationNew,
+ ) -> CustomResult<storage::Authentication, errors::StorageError>;
+
+ async fn find_authentication_by_merchant_id_authentication_id(
+ &self,
+ merchant_id: String,
+ authentication_id: String,
+ ) -> CustomResult<storage::Authentication, errors::StorageError>;
+
+ async fn update_authentication_by_merchant_id_authentication_id(
+ &self,
+ previous_state: storage::Authentication,
+ authentication_update: storage::AuthenticationUpdate,
+ ) -> CustomResult<storage::Authentication, errors::StorageError>;
+}
+
+#[async_trait::async_trait]
+impl AuthenticationInterface for Store {
+ #[instrument(skip_all)]
+ async fn insert_authentication(
+ &self,
+ authentication: storage::AuthenticationNew,
+ ) -> CustomResult<storage::Authentication, errors::StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+ authentication
+ .insert(&conn)
+ .await
+ .map_err(Into::into)
+ .into_report()
+ }
+
+ #[instrument(skip_all)]
+ async fn find_authentication_by_merchant_id_authentication_id(
+ &self,
+ merchant_id: String,
+ authentication_id: String,
+ ) -> CustomResult<storage::Authentication, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ storage::Authentication::find_by_merchant_id_authentication_id(
+ &conn,
+ &merchant_id,
+ &authentication_id,
+ )
+ .await
+ .map_err(Into::into)
+ .into_report()
+ }
+
+ #[instrument(skip_all)]
+ async fn update_authentication_by_merchant_id_authentication_id(
+ &self,
+ previous_state: storage::Authentication,
+ authentication_update: storage::AuthenticationUpdate,
+ ) -> CustomResult<storage::Authentication, errors::StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+ storage::Authentication::update_by_merchant_id_authentication_id(
+ &conn,
+ previous_state.merchant_id,
+ previous_state.authentication_id,
+ authentication_update,
+ )
+ .await
+ .map_err(Into::into)
+ .into_report()
+ }
+}
+
+#[async_trait::async_trait]
+impl AuthenticationInterface for MockDb {
+ async fn insert_authentication(
+ &self,
+ authentication: storage::AuthenticationNew,
+ ) -> CustomResult<storage::Authentication, errors::StorageError> {
+ let mut authentications = self.authentications.lock().await;
+ if authentications.iter().any(|authentication_inner| {
+ authentication_inner.authentication_id == authentication.authentication_id
+ }) {
+ Err(errors::StorageError::DuplicateValue {
+ entity: "authentication_id",
+ key: Some(authentication.authentication_id.clone()),
+ })?
+ }
+ let authentication = storage::Authentication {
+ created_at: common_utils::date_time::now(),
+ modified_at: common_utils::date_time::now(),
+ authentication_id: authentication.authentication_id,
+ merchant_id: authentication.merchant_id,
+ authentication_status: authentication.authentication_status,
+ authentication_connector: authentication.authentication_connector,
+ connector_authentication_id: authentication.connector_authentication_id,
+ authentication_data: authentication.authentication_data,
+ payment_method_id: authentication.payment_method_id,
+ authentication_type: authentication.authentication_type,
+ authentication_lifecycle_status: authentication.authentication_lifecycle_status,
+ error_code: authentication.error_code,
+ error_message: authentication.error_message,
+ connector_metadata: authentication.connector_metadata,
+ };
+ authentications.push(authentication.clone());
+ Ok(authentication)
+ }
+
+ async fn find_authentication_by_merchant_id_authentication_id(
+ &self,
+ merchant_id: String,
+ authentication_id: String,
+ ) -> CustomResult<storage::Authentication, errors::StorageError> {
+ let authentications = self.authentications.lock().await;
+ authentications
+ .iter()
+ .find(|a| a.merchant_id == merchant_id && a.authentication_id == authentication_id)
+ .ok_or(
+ errors::StorageError::ValueNotFound(format!(
+ "cannot find authentication for authentication_id = {authentication_id} and merchant_id = {merchant_id}"
+ )).into(),
+ ).cloned()
+ }
+
+ async fn update_authentication_by_merchant_id_authentication_id(
+ &self,
+ previous_state: storage::Authentication,
+ authentication_update: storage::AuthenticationUpdate,
+ ) -> CustomResult<storage::Authentication, errors::StorageError> {
+ let mut authentications = self.authentications.lock().await;
+ let authentication_id = previous_state.authentication_id.clone();
+ let merchant_id = previous_state.merchant_id.clone();
+ authentications
+ .iter_mut()
+ .find(|authentication| authentication.authentication_id == authentication_id && authentication.merchant_id == merchant_id)
+ .map(|authentication| {
+ let authentication_update_internal =
+ AuthenticationUpdateInternal::from(authentication_update);
+ let updated_authentication = authentication_update_internal.apply_changeset(previous_state);
+ *authentication = updated_authentication.clone();
+ updated_authentication
+ })
+ .ok_or(
+ errors::StorageError::ValueNotFound(format!(
+ "cannot find authentication for authentication_id = {authentication_id} and merchant_id = {merchant_id}"
+ ))
+ .into(),
+ )
+ }
+}
diff --git a/crates/router/src/types/storage/authentication.rs b/crates/router/src/types/storage/authentication.rs
new file mode 100644
index 0000000000..a2dc97536f
--- /dev/null
+++ b/crates/router/src/types/storage/authentication.rs
@@ -0,0 +1 @@
+pub use diesel_models::authentication::{Authentication, AuthenticationNew, AuthenticationUpdate};
diff --git a/migrations/2024-01-22-091431_create_authentication_table/down.sql b/migrations/2024-01-22-091431_create_authentication_table/down.sql
new file mode 100644
index 0000000000..4e6e99bb6b
--- /dev/null
+++ b/migrations/2024-01-22-091431_create_authentication_table/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+DROP TABLE IF EXISTS authentication;
diff --git a/migrations/2024-01-22-091431_create_authentication_table/up.sql b/migrations/2024-01-22-091431_create_authentication_table/up.sql
new file mode 100644
index 0000000000..553b8e5b0e
--- /dev/null
+++ b/migrations/2024-01-22-091431_create_authentication_table/up.sql
@@ -0,0 +1,16 @@
+CREATE TABLE IF NOT EXISTS authentication (
+ authentication_id VARCHAR(64) NOT NULL,
+ merchant_id VARCHAR(64) NOT NULL,
+ authentication_connector VARCHAR(64) NOT NULL,
+ connector_authentication_id VARCHAR(64),
+ authentication_data JSONB,
+ payment_method_id VARCHAR(64) NOT NULL,
+ authentication_type VARCHAR(64),
+ authentication_status VARCHAR(64) NOT NULL,
+ authentication_lifecycle_status VARCHAR(64) NOT NULL,
+ created_at TIMESTAMP NOT NULL DEFAULT now()::TIMESTAMP,
+ modified_at TIMESTAMP NOT NULL DEFAULT now()::TIMESTAMP,
+ error_message VARCHAR(64),
+ error_code VARCHAR(64),
+ PRIMARY KEY (authentication_id)
+);
diff --git a/migrations/2024-02-20-180952_add_connector_metadata_in_authentication/down.sql b/migrations/2024-02-20-180952_add_connector_metadata_in_authentication/down.sql
new file mode 100644
index 0000000000..0b9bf9a074
--- /dev/null
+++ b/migrations/2024-02-20-180952_add_connector_metadata_in_authentication/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE authentication DROP COLUMN IF EXISTS connector_metadata;
diff --git a/migrations/2024-02-20-180952_add_connector_metadata_in_authentication/up.sql b/migrations/2024-02-20-180952_add_connector_metadata_in_authentication/up.sql
new file mode 100644
index 0000000000..919b65e7e5
--- /dev/null
+++ b/migrations/2024-02-20-180952_add_connector_metadata_in_authentication/up.sql
@@ -0,0 +1,2 @@
+-- Your SQL goes here
+ALTER TABLE authentication ADD COLUMN IF NOT EXISTS connector_metadata JSONB DEFAULT NULL;