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
use reqwest::{header, Client, Method, StatusCode};

use crate::{Error, Result};

pub struct Info {
    pub account_id: String,
    pub user_id: String,
    pub token: String,
}

pub async fn auth(url: &str, value: &str) -> Result<Info> {
    let response = Client::new()
        .request(Method::POST, url)
        .header(header::AUTHORIZATION, value)
        .send()
        .await
        .map_err(Error::any)?;
    match response.status() {
        StatusCode::OK => {}
        StatusCode::FORBIDDEN => {
            return Err(Error::Forbidden(response.text().await.map_err(Error::any)?))
        }
        StatusCode::INTERNAL_SERVER_ERROR => {
            return Err(Error::Any(anyhow::anyhow!(response
                .text()
                .await
                .map_err(Error::any)?)))
        }
        _ => return Err(Error::NotFound("not right status code".to_string())),
    };
    let headers = response.headers();
    let account_id = headers
        .get("X-Account-Id")
        .ok_or_else(|| Error::NotFound("not found X-Account-Id".to_string()))?
        .to_str()
        .map_err(Error::any)?;
    let user_id = headers
        .get("X-User-Id")
        .ok_or_else(|| Error::NotFound("not found X-User-Id".to_string()))?
        .to_str()
        .map_err(Error::any)?;
    let token = match headers.get("X-Auth-Token") {
        Some(v) => v.to_str().map_err(Error::any)?,
        None => "",
    };

    Ok(Info {
        account_id: account_id.to_string(),
        user_id: user_id.to_string(),
        token: token.to_string(),
    })
}