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
use reqwest::{Client, Method, RequestBuilder};
use serde::de::DeserializeOwned;
use crate::rate::{RateLimit, RateLimitResponse};
use crate::token::TokenManager;
use crate::Auth0Error;
use crate::{Auth0ErrorResponse, Auth0Result};
#[derive(Debug)]
pub struct Auth0Client {
rate: RateLimit,
token: TokenManager,
client: Client,
domain: String,
}
impl Auth0Client {
pub fn new(rate: RateLimit, token: TokenManager, client: Client, domain: &str) -> Self {
Self {
rate,
token,
client,
domain: domain.to_owned(),
}
}
pub async fn send<R>(&self, req: RequestBuilder) -> Auth0Result<R>
where
R: DeserializeOwned,
{
let token = self.token.get_token().await?;
let res = req
.bearer_auth(&token)
.send()
.await?;
if res.status().is_success() {
let body = res.rate_limit(&self.rate)?.bytes().await?;
let body = body.to_vec();
let body = std::str::from_utf8(&body).unwrap();
let body = if body.is_empty() { "null" } else { body };
Ok(serde_json::from_str::<R>(body)?)
} else {
let body = res.bytes().await?;
let body = body.to_vec();
let body = std::str::from_utf8(&body).unwrap();
let err = serde_json::from_str::<Auth0ErrorResponse>(body);
if let Ok(err) = err {
Err(Auth0Error::from(err))
} else {
Err(Auth0Error::Auth0(body.to_owned()))
}
}
}
pub fn begin(&self, method: Method, path: &str) -> RequestBuilder {
self
.client
.request(method, &format!("https://{}/{}", self.domain, path))
}
}