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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
use async_trait::async_trait;
use std::convert::Infallible;
use std::fmt::{Debug, Display};
#[cfg(feature = "refreshing-token")]
use {
chrono::DateTime, chrono::Utc, serde::Deserialize, serde::Serialize, std::time::Duration,
thiserror::Error, tokio::sync::Mutex,
};
#[derive(Debug, Clone)]
pub struct CredentialsPair {
pub login: String,
pub token: Option<String>,
}
#[async_trait]
pub trait LoginCredentials: Debug + Send + Sync + 'static {
type Error: Send + Sync + Debug + Display;
async fn get_credentials(&self) -> Result<CredentialsPair, Self::Error>;
}
#[derive(Debug, Clone)]
pub struct StaticLoginCredentials {
pub credentials: CredentialsPair,
}
impl StaticLoginCredentials {
pub fn new(login: String, token: Option<String>) -> StaticLoginCredentials {
StaticLoginCredentials {
credentials: CredentialsPair { login, token },
}
}
pub fn anonymous() -> StaticLoginCredentials {
StaticLoginCredentials::new("justinfan12345".to_owned(), None)
}
}
#[async_trait]
impl LoginCredentials for StaticLoginCredentials {
type Error = Infallible;
async fn get_credentials(&self) -> Result<CredentialsPair, Infallible> {
Ok(self.credentials.clone())
}
}
#[cfg(feature = "refreshing-token")]
#[derive(Debug, Serialize, Deserialize)]
pub struct UserAccessToken {
access_token: String,
refresh_token: String,
created_at: DateTime<Utc>,
expires_at: Option<DateTime<Utc>>,
}
#[cfg(feature = "refreshing-token")]
#[derive(Deserialize)]
struct RefreshAccessTokenResponse {
access_token: String,
refresh_token: String,
expires_in: Option<u64>,
}
#[cfg(feature = "refreshing-token")]
impl From<RefreshAccessTokenResponse> for UserAccessToken {
fn from(response: RefreshAccessTokenResponse) -> Self {
let now = Utc::now();
UserAccessToken {
access_token: response.access_token,
refresh_token: response.refresh_token,
created_at: now,
expires_at: response
.expires_in
.map(|d| now + chrono::Duration::from_std(Duration::from_secs(d)).unwrap()),
}
}
}
#[cfg(feature = "refreshing-token")]
#[async_trait]
pub trait TokenStorage: Debug + Send + 'static {
type LoadError: Send + Sync + Debug + Display;
type UpdateError: Send + Sync + Debug + Display;
async fn load_token(&mut self) -> Result<UserAccessToken, Self::LoadError>;
async fn update_token(&mut self, token: &UserAccessToken) -> Result<(), Self::UpdateError>;
}
#[cfg(feature = "refreshing-token")]
#[derive(Debug)]
pub struct RefreshingLoginCredentials<S: TokenStorage> {
http_client: reqwest::Client,
user_login: String,
client_id: String,
client_secret: String,
token_storage: Mutex<S>,
}
#[cfg(feature = "refreshing-token")]
impl<S: TokenStorage> RefreshingLoginCredentials<S> {
pub fn new(
user_login: String,
client_id: String,
client_secret: String,
token_storage: S,
) -> RefreshingLoginCredentials<S> {
RefreshingLoginCredentials {
http_client: reqwest::Client::new(),
user_login,
client_id,
client_secret,
token_storage: Mutex::new(token_storage),
}
}
}
#[cfg(feature = "refreshing-token")]
#[derive(Error, Debug)]
pub enum RefreshingLoginError<S: TokenStorage> {
#[error("Failed to retrieve token from storage: {0}")]
LoadError(S::LoadError),
#[error("Failed to refresh token: {0}")]
RefreshError(reqwest::Error),
#[error("Failed to update token in storage: {0}")]
UpdateError(S::UpdateError),
}
#[cfg(feature = "refreshing-token")]
const SHOULD_REFRESH_AFTER_FACTOR: f64 = 0.9;
#[cfg(feature = "refreshing-token")]
#[async_trait]
impl<S: TokenStorage> LoginCredentials for RefreshingLoginCredentials<S> {
type Error = RefreshingLoginError<S>;
async fn get_credentials(&self) -> Result<CredentialsPair, RefreshingLoginError<S>> {
let mut token_storage = self.token_storage.lock().await;
let mut current_token = token_storage
.load_token()
.await
.map_err(RefreshingLoginError::LoadError)?;
let token_expires_after = if let Some(expires_at) = current_token.expires_at {
(expires_at - current_token.created_at).to_std().unwrap()
} else {
Duration::from_secs(24 * 60 * 60)
};
let token_age = (Utc::now() - current_token.created_at).to_std().unwrap();
let max_token_age = token_expires_after.mul_f64(SHOULD_REFRESH_AFTER_FACTOR);
let is_token_expired = token_age >= max_token_age;
if is_token_expired {
let response = self
.http_client
.post("https://id.twitch.tv/oauth2/token")
.query(&[
("grant_type", "refresh_token"),
("refresh_token", ¤t_token.refresh_token),
("client_id", &self.client_id),
("client_secret", &self.client_secret),
])
.send()
.await
.map_err(RefreshingLoginError::RefreshError)?
.json::<RefreshAccessTokenResponse>()
.await
.map_err(RefreshingLoginError::RefreshError)?;
current_token = UserAccessToken::from(response);
token_storage
.update_token(¤t_token)
.await
.map_err(RefreshingLoginError::UpdateError)?;
}
Ok(CredentialsPair {
login: self.user_login.clone(),
token: Some(current_token.access_token.clone()),
})
}
}