1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
use crate::{
    config::Configuration,
    error::{self, Error},
    middleware::ErrorForStatus,
    totp,
};
use serde::{Deserialize, Serialize};
use std::time::Duration;
use surf::Client as SurfClient;

#[derive(Debug, Deserialize, Serialize)]
pub struct Credentials {
    pub username: String,
    pub password: String,
    pub totp_secret: String,
}

#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TotpBody {
    totp_code: String,
    method: String,
}

#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TotpResponse {
    authentication_session: String,
    push_subscription_id: String,
    customer_id: String,
    registration_complete: bool,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionUser {
    pub security_token: String,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TwoFactorLogin {
    pub transaction_id: String,
    pub method: String,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UserCredentialsResponse {
    pub two_factor_login: TwoFactorLogin,
}

#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct UserCredentialsRequest {
    pub username: String,
    pub password: String,
}

pub struct Client {
    pub(crate) http_client: SurfClient,
    pub(crate) config: Configuration,
}

impl Client {
    pub async fn authenticate(credentials: &Credentials) -> Result<Client, error::Error> {
        // Create default config.
        let config = Configuration::default();

        // Send initial auth request with username and password.
        let user_credentials_response = surf::post(config.urls.authenticate.as_str())
            .middleware(ErrorForStatus)
            .body_json(&UserCredentialsRequest {
                username: credentials.username.clone(),
                password: credentials.password.clone()
            })?
            .recv_json::<UserCredentialsResponse>()
            .await?;

        // Generate a totp code.
        let totp_code = totp::generate_totp(&credentials.totp_secret);

        // Send totp code and transaction id as cookie.
        let mut totp_response = surf::post(config.urls.totp.as_str())
            .middleware(ErrorForStatus)
            .header(
                "cookie",
                format!(
                    "AZAMFATRANSACTION={}",
                    user_credentials_response.two_factor_login.transaction_id
                ),
            )
            .body_json(&TotpBody {
                method: String::from("TOTP"),
                totp_code: totp_code.to_string(),
            })?
            .await?;

        // Parse the response body.
        let totp_data = totp_response.body_json::<TotpResponse>().await?;

        let authentication_token = totp_data.authentication_session.clone();

        // Extract security token from headers.
        let security_token = totp_response
            .header("x-securitytoken")
            .ok_or(Error::SecurityTokenError(String::from(
                "Header 'x-securitytoken was missing in totp request'.",
            )))?
            .as_str();

        // Create an http client.
        let http_client =
            Self::create_http_client(String::from(security_token), authentication_token.clone())?;

        // Create and return Client.
        let client = Client {
            http_client,
            config: config.clone(),
        };
        return Ok(client);
    }

    fn create_http_client(
        security_token: String,
        authentication_token: String,
    ) -> Result<SurfClient, Error> {
        let client: SurfClient = surf::Config::new()
            .set_timeout(Some(Duration::from_secs(5)))
            .add_header("X-Securitytoken", security_token)?
            .add_header("X-AuthenticationSession", authentication_token)?
            .try_into()
            .map_err(|_| {
                Error::CreateHTTPClientError(String::from("Could not create http client"))
            })?;
        let client = client.with(ErrorForStatus);

        return Ok(client);
    }
}