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
232
233
use futures::executor::block_on;
use log::{debug, error};
use tiny_http::{Response, Server, StatusCode};
use twitch_oauth2::{
tokens::{errors::UserTokenExchangeError, UserTokenBuilder},
ClientId, ClientSecret, CsrfToken, Scope, UserToken,
};
use url::Url;
#[derive(Debug, thiserror::Error)]
pub enum AuthFlowError<ClientError>
where
ClientError: std::error::Error + Send + Sync + 'static,
{
#[error(transparent)]
HookError(#[from] HookError<ClientError>),
#[error("could not parse url")]
UrlParseError(#[from] url::ParseError),
}
#[derive(Debug, thiserror::Error)]
pub enum HookError<ClientError>
where
ClientError: std::error::Error + Send + Sync + 'static,
{
#[error("when constructing http server")]
TinyHttpError(#[source] Box<(dyn std::error::Error + Sync + Send + 'static)>),
#[error("could not parse url")]
UrlParseError(#[from] url::ParseError),
#[error("failed to do IO operation")]
IoError(#[from] std::io::Error),
#[error("talking with twitch authentication failed")]
ExchangeError(#[from] UserTokenExchangeError<ClientError>),
}
#[cfg(feature = "surf_client")]
pub fn auth_flow_surf(
client_id: &str,
client_secret: &str,
scopes: Option<Vec<Scope>>,
redirect_url: &str,
) -> Result<UserToken, AuthFlowError<twitch_oauth2::client::SurfError>> {
let redirect_url = Url::parse(&redirect_url)?;
let mut hook = TwitchAuthHook::new(
twitch_oauth2::client::surf_http_client,
String::from(client_id),
String::from(client_secret),
scopes,
redirect_url,
)?;
let (url, _) = hook.generate_url();
println!(
"To obtain an authentication token, please visit\n{}",
url.as_str().to_owned()
);
block_on(async { hook.receive_auth_token().await }).map_err(Into::into)
}
#[cfg(feature = "reqwest_client")]
pub fn auth_flow_reqwest(
client_id: &str,
client_secret: &str,
scopes: Option<Vec<Scope>>,
redirect_url: &str,
) -> Result<UserToken, AuthFlowError<twitch_oauth2::oauth2::reqwest::Error<reqwest::Error>>> {
let redirect_url = Url::parse(&redirect_url)?;
let mut hook = TwitchAuthHook::new(
twitch_oauth2::client::reqwest_http_client,
String::from(client_id),
String::from(client_secret),
scopes,
redirect_url,
)?;
let (url, _) = hook.generate_url();
println!(
"To obtain an authentication token, please visit\n{}",
url.as_str().to_owned()
);
block_on(async { hook.receive_auth_token().await }).map_err(Into::into)
}
pub struct TwitchAuthHook<C> {
builder: UserTokenBuilder,
redirect_url: Url,
port: u16,
client: C,
}
impl<RE, C, F> TwitchAuthHook<C>
where
RE: std::error::Error + Send + Sync + 'static,
C: Copy + FnOnce(twitch_oauth2::oauth2::HttpRequest) -> F,
F: std::future::Future<Output = Result<twitch_oauth2::oauth2::HttpResponse, RE>>,
{
pub fn new(
client: C,
client_id: String,
client_secret: String,
scopes: impl Into<Option<Vec<Scope>>>,
redirect_url: Url,
) -> Result<TwitchAuthHook<C>, HookError<RE>> {
let redirect = twitch_oauth2::RedirectUrl::from_url(redirect_url.clone());
let port = redirect.url().port_or_known_default().unwrap_or(80);
let mut builder = UserToken::builder(
ClientId::new(client_id),
ClientSecret::new(client_secret),
redirect,
)
.expect("unexpected failure to construct urls to twitch")
.force_verify(true);
if let Some(scopes) = scopes.into() {
builder = builder.set_scopes(scopes);
}
Ok(TwitchAuthHook {
builder,
redirect_url,
port,
client,
})
}
pub fn generate_url(&mut self) -> (Url, CsrfToken) {
self.builder.generate_url()
}
pub fn set_port(&mut self, port: u16) {
self.port = port;
}
pub async fn receive_auth_token(self) -> Result<UserToken, HookError<RE>> {
let http_server =
Server::http(format!("0.0.0.0:{}", self.port)).map_err(HookError::TinyHttpError)?;
let (code, state) = loop {
match http_server.recv() {
Ok(rq) => {
debug!("request: {:?}", rq);
let url = format!(
"http://localhost:{}{}",
http_server.server_addr().port(),
rq.url()
);
let url = Url::parse(&url)?;
if url.path() != self.redirect_url.path() {
rq.respond(Response::from_string("KO").with_status_code(StatusCode(500)))?;
continue;
}
let query: std::collections::HashMap<_, _> = url.query_pairs().collect();
match (query.get("code"), query.get("state")) {
(Some(code), Some(state)) => {
rq.respond(Response::from_string("OK"))?;
break (code.to_string(), state.to_string());
}
_ => match (query.get("error"), query.get("error_description")) {
(None, None) => {
rq.respond(
Response::from_string("KO").with_status_code(StatusCode(500)),
)?;
continue;
}
(e, d) => {
rq.respond(
Response::from_string(&format!(
"Error: {} - {}",
e.map(|e| e.as_ref()).unwrap_or(""),
d.map(|e| e.as_ref()).unwrap_or("")
))
.with_status_code(400),
)?;
continue;
}
},
}
}
Err(e) => {
error!("error: {}", e)
}
}
};
self.builder
.get_user_token(self.client, &state, &code)
.await
.map_err(Into::into)
}
}