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(),
})
}