1use serde::{Deserialize, Serialize};
2
3use crate::http::{Client};
4use crate::user::User;
5use crate::MAIL_API_URL;
6use anyhow::Error;
7
8#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
9#[serde(rename_all = "camelCase")]
10pub struct Token {
11 pub token: String,
12 pub id: String,
13}
14
15pub(crate) async fn token(user: &User) -> Result<Token, Error> {
16 let client = Client::new()?
17 .build()?;
18
19 log::debug!("Getting token for user {:?}", user);
20
21 let create_as_string = serde_json::json!({
22 "address": format!("{}@{}", user.id, user.domain).to_lowercase(),
23 "password": user.password
24 });
25
26 let res = client
27 .post(format!("{}/token", MAIL_API_URL).as_str())
28 .body(create_as_string.to_string())
29 .send()
30 .await?;
31
32 let body = res.text().await?;
33 log::trace!("Retrieved email token: {:?}", body);
34
35 Ok(serde_json::from_str(&body)?)
36}
37
38#[cfg(test)]
39mod tests {
40 use super::*;
41 use crate::accounts;
42
43 #[tokio::test]
44 async fn test_token() -> Result<(), Error> {
45 pretty_env_logger::try_init().ok();
46 let user = User::default().with_domain(&crate::domains::domains().await?.any().domain);
47
48 let create = accounts::create(&user).await.unwrap();
49
50 let token = token(&user).await.unwrap();
51
52 assert_eq!(token.token.is_empty(), false);
53
54 accounts::delete(&token.token, &create.id.unwrap()).await.unwrap();
55
56 Ok(())
57 }
58}