use std::sync::Arc;
use serde::Serialize;
use serde_json::Value;
use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::{DelopayError, Result};
use crate::core::models::authentication::AuthenticationResponse;
use crate::core::models::common::Currency;
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;
#[derive(Debug, Clone)]
pub struct Authentication {
inner: Arc<Inner>,
}
impl Authentication {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
pub async fn create(
&self,
params: &AuthenticationCreateRequest,
) -> Result<AuthenticationResponse> {
params.validate()?;
let body = to_json_vec(params)?;
self.inner
.request(HttpMethod::Post, "/authentication", Some(&body), &[], None)
.await
}
pub async fn check_eligibility(
&self,
authentication_id: &str,
) -> Result<AuthenticationResponse> {
let path = format!(
"/authentication/{}/eligibility",
encode_segment(authentication_id)
);
self.inner
.request(HttpMethod::Post, &path, None, &[], None)
.await
}
pub async fn authenticate(
&self,
authentication_id: &str,
params: &Value,
) -> Result<AuthenticationResponse> {
let path = format!(
"/authentication/{}/authenticate",
encode_segment(authentication_id)
);
let body = to_json_vec(params)?;
self.inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
pub async fn sync(
&self,
merchant_id: &str,
authentication_id: &str,
params: Option<&Value>,
) -> Result<AuthenticationResponse> {
let path = format!(
"/authentication/{}/{}/sync",
encode_segment(merchant_id),
encode_segment(authentication_id)
);
let body: Option<Vec<u8>> = match params {
Some(p) => Some(to_json_vec(p)?),
None => None,
};
self.inner
.request(HttpMethod::Post, &path, body.as_deref(), &[], None)
.await
}
pub async fn redirect(
&self,
merchant_id: &str,
authentication_id: &str,
params: &Value,
) -> Result<Value> {
let path = format!(
"/authentication/{}/{}/redirect",
encode_segment(merchant_id),
encode_segment(authentication_id)
);
let body = to_json_vec(params)?;
self.inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
pub async fn enabled_authn_methods_token(
&self,
authentication_id: &str,
params: &Value,
) -> Result<Value> {
let path = format!(
"/authentication/{}/enabled-authn-methods-token",
encode_segment(authentication_id)
);
let body = to_json_vec(params)?;
self.inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
pub async fn eligibility_check(
&self,
authentication_id: &str,
params: &Value,
) -> Result<Value> {
let path = format!(
"/authentication/{}/eligibility-check",
encode_segment(authentication_id)
);
let body = to_json_vec(params)?;
self.inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct AuthenticationCreateRequest {
pub amount: i64,
pub currency: Currency,
#[serde(skip_serializing_if = "Option::is_none")]
pub authentication_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub profile_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub customer: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub authentication_connector: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub return_url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub force_3ds_challenge: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub psd2_sca_exemption_type: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub profile_acquirer_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_method_data: Option<Value>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
const AUTHENTICATION_CREATE_REQUEST_NAMED: &[&str] = &[
"amount",
"currency",
"authentication_id",
"profile_id",
"customer",
"authentication_connector",
"return_url",
"force_3ds_challenge",
"psd2_sca_exemption_type",
"profile_acquirer_id",
"payment_method_data",
];
impl ValidateRequest for AuthenticationCreateRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if AUTHENTICATION_CREATE_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on \
AuthenticationCreateRequest"
)));
}
}
Ok(())
}
}
impl AuthenticationCreateRequest {
pub fn new(amount: i64, currency: impl Into<Currency>) -> Self {
Self {
amount,
currency: currency.into(),
..Default::default()
}
}
#[must_use]
pub fn return_url(mut self, return_url: impl Into<String>) -> Self {
self.return_url = Some(return_url.into());
self
}
#[must_use]
pub fn profile_id(mut self, profile_id: impl Into<String>) -> Self {
self.profile_id = Some(profile_id.into());
self
}
#[must_use]
pub fn force_3ds_challenge(mut self, force: bool) -> Self {
self.force_3ds_challenge = Some(force);
self
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::mock::{Step, client_with};
use serde_json::json;
const AUTH_JSON: &str = r#"{
"authentication_id": "auth_1", "merchant_id": "merch_1",
"status": "started", "amount": 1000, "currency": "USD",
"client_secret": "auth_1_secret", "three_ds_server_id": "srv_9"
}"#;
#[tokio::test]
async fn create_posts_to_the_authentication_root() {
let (client, mock) = client_with(vec![Step::ok(AUTH_JSON)]);
let out = client
.authentication()
.create(
&AuthenticationCreateRequest::new(1000, "USD")
.return_url("https://example.com/return")
.force_3ds_challenge(true),
)
.await
.unwrap();
assert_eq!(out.authentication_id, "auth_1");
assert_eq!(out.status, "started");
assert_eq!(out.amount, 1000);
assert_eq!(out.client_secret.as_deref(), Some("auth_1_secret"));
assert_eq!(out.extra["three_ds_server_id"], "srv_9");
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/authentication");
let body = seen[0].body_json();
assert_eq!(body["amount"], 1000);
assert_eq!(body["currency"], "USD");
assert_eq!(body["return_url"], "https://example.com/return");
assert_eq!(body["force_3ds_challenge"], true);
}
#[tokio::test]
async fn check_eligibility_posts_without_a_body() {
let (client, mock) = client_with(vec![Step::ok(AUTH_JSON)]);
client
.authentication()
.check_eligibility("auth/1")
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/authentication/auth%2F1/eligibility"
);
assert!(seen[0].body.is_none(), "eligibility takes no request body");
}
#[tokio::test]
async fn authenticate_posts_its_open_body() {
let (client, mock) = client_with(vec![Step::ok(AUTH_JSON)]);
client
.authentication()
.authenticate("auth/1", &json!({"device_channel": "BRW"}))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/authentication/auth%2F1/authenticate"
);
assert_eq!(seen[0].body_json()["device_channel"], "BRW");
}
#[tokio::test]
async fn sync_is_merchant_scoped_and_body_is_optional() {
let (client, mock) = client_with(vec![Step::ok(AUTH_JSON), Step::ok(AUTH_JSON)]);
let auth = client.authentication();
auth.sync("merch/1", "auth_1", Some(&json!({"force": true})))
.await
.unwrap();
auth.sync("merch/1", "auth_1", None).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/authentication/merch%2F1/auth_1/sync"
);
assert_eq!(seen[0].body_json()["force"], true);
assert!(seen[1].body.is_none(), "`None` params must send no body");
}
#[tokio::test]
async fn redirect_is_merchant_scoped() {
let (client, mock) = client_with(vec![Step::ok("{}")]);
client
.authentication()
.redirect("merch/1", "auth_1", &json!({"cres": "abc"}))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/authentication/merch%2F1/auth_1/redirect"
);
assert_eq!(seen[0].body_json()["cres"], "abc");
}
#[tokio::test]
async fn token_and_eligibility_check_hit_their_paths() {
let (client, mock) = client_with(vec![Step::ok("{}"), Step::ok("{}")]);
let auth = client.authentication();
auth.enabled_authn_methods_token("auth/1", &json!({"client_secret": "cs_1"}))
.await
.unwrap();
auth.eligibility_check("auth/1", &json!({"card_number": "4242"}))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/authentication/auth%2F1/enabled-authn-methods-token"
);
assert_eq!(seen[0].body_json()["client_secret"], "cs_1");
assert_eq!(seen[1].method, "POST");
assert_eq!(
seen[1].url,
"https://api.test/authentication/auth%2F1/eligibility-check"
);
assert_eq!(seen[1].body_json()["card_number"], "4242");
}
#[test]
fn authentication_create_request_named_fields_are_complete() {
let req = AuthenticationCreateRequest {
amount: 1000,
currency: "USD".to_string(),
authentication_id: Some("auth_1".to_string()),
profile_id: Some("pro_1".to_string()),
customer: Some(json!({"id": "cus_1"})),
authentication_connector: Some("threedsecureio".to_string()),
return_url: Some("https://example.com/return".to_string()),
force_3ds_challenge: Some(true),
psd2_sca_exemption_type: Some("low_value".to_string()),
profile_acquirer_id: Some("acq_1".to_string()),
payment_method_data: Some(json!({"card": {}})),
extra: serde_json::Map::new(),
};
let value = serde_json::to_value(req).unwrap();
for key in value.as_object().expect("serializes to an object").keys() {
assert!(
AUTHENTICATION_CREATE_REQUEST_NAMED.contains(&key.as_str()),
"AUTHENTICATION_CREATE_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn validate_rejects_extra_key_colliding_with_named_field() {
let mut req = AuthenticationCreateRequest::new(1000, "USD");
req.extra.insert("currency".to_string(), json!("EUR"));
match req.validate().unwrap_err() {
DelopayError::InvalidRequest(msg) => assert!(msg.contains("currency")),
other => panic!("expected InvalidRequest, got {other:?}"),
}
}
}