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
use crate::openid::Expires;
use core::fmt::{self, Debug, Formatter};
use std::{ops::Deref, sync::Arc};
use tokio::sync::RwLock;
#[derive(Clone)]
pub struct OpenIdTokenProvider {
pub client: Arc<openid::Client>,
current_token: Arc<RwLock<Option<openid::Bearer>>>,
refresh_before: chrono::Duration,
}
impl Debug for OpenIdTokenProvider {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("TokenProvider")
.field(
"client",
&format!("{} / {:?}", self.client.client_id, self.client.http_client),
)
.field("current_token", &"...")
.finish()
}
}
impl OpenIdTokenProvider {
pub fn new(client: openid::Client, refresh_before: chrono::Duration) -> Self {
Self {
client: Arc::new(client),
current_token: Arc::new(RwLock::new(None)),
refresh_before,
}
}
pub async fn provide_token(&self) -> Result<openid::Bearer, openid::error::Error> {
match self.current_token.read().await.deref() {
Some(token) if !token.expires_before(self.refresh_before) => {
log::debug!("Token still valid");
return Ok(token.clone());
}
_ => {}
}
self.fetch_fresh_token().await
}
async fn fetch_fresh_token(&self) -> Result<openid::Bearer, openid::error::Error> {
log::debug!("Fetching fresh token...");
let mut lock = self.current_token.write().await;
match lock.deref() {
Some(token) if !token.expires_before(self.refresh_before) => {
log::debug!("Token already got refreshed");
return Ok(token.clone());
}
_ => {}
}
let next_token = match lock.take() {
None => {
log::debug!("Fetching initial token... ");
self.initial_token().await?
}
Some(current_token) => {
log::debug!("Refreshing token ... ");
match current_token.refresh_token.is_some() {
true => self.client.refresh_token(current_token, None).await?,
false => self.initial_token().await?,
}
}
};
log::debug!("Next token: {:?}", next_token);
lock.replace(next_token.clone());
Ok(next_token)
}
async fn initial_token(&self) -> Result<openid::Bearer, openid::error::Error> {
Ok(self.client.request_token_using_client_credentials().await?)
}
}
#[cfg(all(feature = "reqwest", not(target_arch = "wasm32")))]
use crate::{
error::ClientError,
openid::{provider::TokenProvider, Credentials},
};
#[cfg(all(feature = "reqwest", not(target_arch = "wasm32")))]
#[async_trait::async_trait]
impl TokenProvider for OpenIdTokenProvider {
async fn provide_access_token(&self) -> Result<Option<Credentials>, ClientError> {
self.provide_token()
.await
.map(|token| Some(Credentials::Bearer(token.access_token)))
.map_err(|err| ClientError::Token(Box::new(err)))
}
}