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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
use serde::{de::DeserializeOwned, Serialize};

use crate::{
    apis::{
        Authenticate, CurrentUser, Jwks, Login, MagicLink, OpenId, Otp, Register, Tokens, Users,
    },
    config::Config,
    error::ApiError,
    PassageError,
};

#[derive(Debug, Clone)]
pub struct Passage<Config> {
    http_client: reqwest::Client,
    config: Config,
}

impl Default for Passage<Config> {
    fn default() -> Self {
        Self::new()
    }
}

impl Passage<Config> {
    /// Creates a new [Passage] for interacting with the Passage API.
    pub fn new() -> Self {
        Self {
            http_client: reqwest::Client::new(),
            config: Config::default(),
        }
    }
}

impl Passage<Config> {
    /// Create client with a custom HTTP client if needed.
    pub fn build(http_client: reqwest::Client, config: Config) -> Self {
        Self {
            http_client,
            config,
        }
    }

    pub fn with_config(config: Config) -> Self {
        Self {
            http_client: reqwest::Client::new(),
            config,
        }
    }

    pub fn set_pub_jwk(mut self, pub_jwk: String) -> Self {
        self.config = self.config.with_pub_jwk(pub_jwk);
        self
    }

    /// Provide a custom [client] to make all HTTP requests with.
    ///
    /// [client]: reqwest::Client
    pub fn with_http_client(mut self, http_client: reqwest::Client) -> Self {
        self.http_client = http_client;
        self
    }

    // API groups

    /// To call the [Tokens] group related APIs using this client.
    pub fn tokens(&self) -> Tokens<Config> {
        Tokens::new(self)
    }

    /// To call [Register] group related APIs using this client.
    pub fn register(&self) -> Register<Config> {
        Register::new(self)
    }

    /// To call [Otp] group related APIs using this client.
    pub fn otp(&self) -> Otp<Config> {
        Otp::new(self)
    }

    /// To call [OpenId] group related APIs using this client.
    pub fn open_id(&self) -> OpenId<Config> {
        OpenId::new(self)
    }

    /// To call [MagicLink] group related APIs using this client.
    pub fn magic_link(&self) -> MagicLink<Config> {
        MagicLink::new(self)
    }

    /// To call [Login] group related APIs using this client.
    pub fn login(&self) -> Login<Config> {
        Login::new(self)
    }

    /// To call [Jwks] group related APIs using this client.
    pub fn jwks(&self) -> Jwks<Config> {
        Jwks::new(self)
    }

    /// To call [Authenticate] group related APIs using this client.
    pub fn authenticate(&self) -> Authenticate<Config> {
        Authenticate::new(self)
    }

    /// To call [CurrentUser] group related APIs using this client.
    pub fn current_user(&self) -> CurrentUser<Config> {
        CurrentUser::new(self)
    }

    /// To call [Users] group related APIs using this client.
    pub fn users(&self) -> Users<Config> {
        Users::new(self)
    }

    pub fn app_id(&self) -> &str {
        self.config.app_id()
    }

    pub fn config(&self) -> &Config {
        &self.config
    }

    pub fn pub_jwk(&self) -> Option<&String> {
        self.config.pub_jwk()
    }

    /// Make a GET request to {path} and deserialize the response body
    pub(crate) async fn get<O>(&self, path: &str) -> Result<O, PassageError>
    where
        O: DeserializeOwned,
    {
        let response = self
            .http_client
            .get(self.config.url(path))
            .query(&self.config.query())
            .headers(self.config.bearer_auth())
            .send()
            .await?;

        self.deserialize_response(response).await
    }

    /// Make a GET request to {path} with given Query and deserialize the
    /// response body
    pub(crate) async fn get_with_query<Q, O>(
        &self,
        path: &str,
        query: &Q,
    ) -> Result<O, PassageError>
    where
        O: DeserializeOwned,
        Q: Serialize + ?Sized,
    {
        let response = self
            .http_client
            .get(self.config.url(path))
            .query(&self.config.query())
            .query(query)
            .headers(self.config.bearer_auth())
            .send()
            .await?;

        self.deserialize_response(response).await
    }

    /// Make a GET request to the Passage management API and deserialize the
    /// response body
    ///
    /// This is temporary until the `passage-manage` crate is created
    pub(crate) async fn get_from_management_api<O>(&self, path: &str) -> Result<O, PassageError>
    where
        O: DeserializeOwned,
    {
        let response = self
            .http_client
            .get(format!("https://api.passage.id/v1{}", path))
            .query(&self.config.query())
            .headers(self.config.api_key_auth())
            .send()
            .await?;

        dbg!(&response);

        self.deserialize_response(response).await
    }

    /// Make a POST request to {path} and deserialize the response body
    pub(crate) async fn post<I, O>(&self, path: &str, request: I) -> Result<O, PassageError>
    where
        I: Serialize,
        O: DeserializeOwned,
    {
        let response = self
            .http_client
            .post(self.config.url(path))
            .query(&self.config.query())
            .headers(self.config.bearer_auth())
            .json(&request)
            .send()
            .await?;

        self.deserialize_response(response).await
    }

    /// Make a POST request to {patch} and deserialize the response body
    pub(crate) async fn patch<I, O>(&self, path: &str, request: I) -> Result<O, PassageError>
    where
        I: Serialize,
        O: DeserializeOwned,
    {
        let response = self
            .http_client
            .patch(self.config.url(path))
            .query(&self.config.query())
            .headers(self.config.bearer_auth())
            .json(&request)
            .send()
            .await?;

        self.deserialize_response(response).await
    }

    /// Make a DELETE request to {path}
    pub(crate) async fn delete<O>(&self, path: &str) -> Result<O, PassageError>
    where
        O: DeserializeOwned,
    {
        let response = self
            .http_client
            .delete(self.config.url(path))
            .query(&self.config.query())
            .headers(self.config.bearer_auth())
            .send()
            .await?;

        self.deserialize_response(response).await
    }

    /// Make a DELETE request to {path} with given Query and deserialize the
    /// response body
    pub(crate) async fn delete_with_query<Q, O>(
        &self,
        path: &str,
        query: &Q,
    ) -> Result<O, PassageError>
    where
        O: DeserializeOwned,
        Q: Serialize + ?Sized,
    {
        let response = self
            .http_client
            .delete(self.config.url(path))
            .query(&self.config.query())
            .query(query)
            .headers(self.config.bearer_auth())
            .send()
            .await?;

        self.deserialize_response(response).await
    }

    /// TODO: This needs some love
    async fn deserialize_response<O>(&self, response: reqwest::Response) -> Result<O, PassageError>
    where
        O: DeserializeOwned,
    {
        if response.status().is_success() {
            response.json::<O>().await.map_err(PassageError::from)
        } else {
            Err(response
                .json::<ApiError>()
                .await
                .map_err(PassageError::from)?
                .into())
        }
    }
}