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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
use super::{make_redirect_url, IdentityProvider};
use crate::api::rcos::users::accounts::for_user::UserAccounts;
use crate::api::rcos::users::accounts::link::LinkUserAccount;
use crate::api::rcos::users::accounts::reverse_lookup::ReverseLookup;
use crate::api::rcos::users::accounts::unlink::UnlinkUserAccount;
use crate::api::rcos::users::UserAccountType;
use crate::error::TelescopeError;
use crate::web::csrf;
use crate::web::services::auth::identity::{AuthenticationCookie, Identity, RootIdentity};
use crate::web::services::auth::AUTHENTICATOR_ACCOUNT_TYPES;
use actix_web::http::header::LOCATION;
use actix_web::web::Query;
use actix_web::FromRequest;
use actix_web::{HttpRequest, HttpResponse};
use futures::future::LocalBoxFuture;
use oauth2::basic::{BasicClient, BasicTokenResponse};
use oauth2::{AuthorizationCode, AuthorizationRequest, CsrfToken, RedirectUrl, Scope};
use std::borrow::Cow;
use std::collections::HashMap;
use std::sync::Arc;
pub mod discord;
pub mod github;
#[derive(Deserialize)]
struct AuthResponse {
code: AuthorizationCode,
state: CsrfToken,
}
pub trait Oauth2Identity {
const USER_ACCOUNT_TY: UserAccountType;
fn from_basic_token(token: &BasicTokenResponse) -> Self;
fn platform_user_id(&self) -> LocalBoxFuture<Result<String, TelescopeError>>;
fn into_root(self) -> RootIdentity;
fn add_to_cookie(self, cookie: &mut AuthenticationCookie);
}
pub trait Oauth2IdentityProvider {
type IdentityType: Oauth2Identity;
const SERVICE_NAME: &'static str;
fn get_client() -> Arc<BasicClient>;
fn scopes() -> Vec<Scope>;
fn auth_response(
redir_url: RedirectUrl,
http_req: &HttpRequest,
) -> Result<HttpResponse, TelescopeError> {
let client: Arc<BasicClient> = Self::get_client();
let mut auth_req: AuthorizationRequest = client
.authorize_url(CsrfToken::new_random)
.set_redirect_uri(Cow::Owned(redir_url));
for scope in Self::scopes() {
auth_req = auth_req.add_scope(scope);
}
let (url, csrf_token) = auth_req.url();
csrf::save(Self::SERVICE_NAME, http_req, csrf_token)?;
return Ok(HttpResponse::Found()
.header(LOCATION, url.as_str())
.finish());
}
fn token_exchange(
redirect_uri: RedirectUrl,
req: &HttpRequest,
) -> Result<BasicTokenResponse, TelescopeError> {
let params: Query<AuthResponse> = Query::extract(req)
.into_inner()
.map_err(|err: actix_web::Error| {
TelescopeError::BadRequest {
header: "Bad Authentication Request".into(),
message: format!(
"Could not get authentication parameters from request URL. \
Actix-web error: {}",
err
),
show_status_code: true,
}
})?;
let AuthResponse { code, state } = params.0;
csrf::verify(Self::SERVICE_NAME, req, state)?;
let oauth_client: Arc<BasicClient> = Self::get_client();
return oauth_client
.exchange_code(code)
.add_extra_param("redirect_uri", redirect_uri.as_str())
.request(oauth2::reqwest::http_client)
.map_err(|e| {
TelescopeError::ise(format!(
"OAuth2 token exchange error. If this \
persists, please contact a coordinator and file a GitHub issue. Internal error \
description: {:?}",
e
))
});
}
}
impl<T> IdentityProvider for T
where
T: Oauth2IdentityProvider + 'static,
{
const SERVICE_NAME: &'static str = <Self as Oauth2IdentityProvider>::SERVICE_NAME;
const USER_ACCOUNT_TY: UserAccountType =
<Self as Oauth2IdentityProvider>::IdentityType::USER_ACCOUNT_TY;
type LoginResponse = Result<HttpResponse, TelescopeError>;
type RegistrationResponse = Result<HttpResponse, TelescopeError>;
type LinkResponse = Result<HttpResponse, TelescopeError>;
type LoginFut = LocalBoxFuture<'static, Result<HttpResponse, TelescopeError>>;
type RegistrationFut = LocalBoxFuture<'static, Result<HttpResponse, TelescopeError>>;
type LinkFut = LocalBoxFuture<'static, Result<HttpResponse, TelescopeError>>;
type LoginAuthenticatedFut = LocalBoxFuture<'static, Result<HttpResponse, TelescopeError>>;
type RegistrationAuthenticatedFut =
LocalBoxFuture<'static, Result<HttpResponse, TelescopeError>>;
type LinkAuthenticatedFut = LocalBoxFuture<'static, Result<HttpResponse, TelescopeError>>;
fn login_handler(req: HttpRequest) -> Self::LoginFut {
return Box::pin(async move {
let redir_url: RedirectUrl = make_redirect_url(&req, Self::login_redirect_path());
return Self::auth_response(redir_url, &req);
});
}
fn registration_handler(req: HttpRequest) -> Self::RegistrationFut {
return Box::pin(async move {
let redir_url: RedirectUrl =
make_redirect_url(&req, Self::registration_redirect_path());
return Self::auth_response(redir_url, &req);
});
}
fn link_handler(req: HttpRequest, ident: Identity) -> Self::LinkFut {
return Box::pin(async move {
if ident.identity().await.is_some() {
let redir_url: RedirectUrl = make_redirect_url(&req, Self::link_redirect_path());
return Self::auth_response(redir_url, &req);
} else {
return Err(TelescopeError::NotAuthenticated);
}
});
}
fn login_authenticated_handler(
req: HttpRequest,
) -> LocalBoxFuture<'static, Result<HttpResponse, TelescopeError>> {
return Box::pin(async move {
let redir_uri: RedirectUrl = make_redirect_url(&req, Self::login_redirect_path());
let token_response: BasicTokenResponse = Self::token_exchange(redir_uri, &req)?;
let platform_identity: T::IdentityType =
T::IdentityType::from_basic_token(&token_response);
let root: RootIdentity = platform_identity.into_root();
let platform_id: String = root.get_platform_id().await?;
let user_id = ReverseLookup::execute(root.get_user_account_type(), platform_id)
.await?
.ok_or(TelescopeError::resource_not_found(
"Could not find associated user account.",
format!(
"Could not find user account associated with this {} account. \
Please create an account or sign in using another method.",
Self::SERVICE_NAME
),
))?;
let identity: Identity = Identity::extract(&req).await?;
identity.save(&root.make_authenticated_cookie());
Ok(HttpResponse::Found()
.header(LOCATION, format!("/user/{}", user_id))
.finish())
});
}
fn registration_authenticated_handler(req: HttpRequest) -> Self::RegistrationAuthenticatedFut {
return Box::pin(async move {
let redir_uri: RedirectUrl =
make_redirect_url(&req, Self::registration_redirect_path());
let token_response: BasicTokenResponse = Self::token_exchange(redir_uri, &req)?;
let platform_identity: T::IdentityType =
T::IdentityType::from_basic_token(&token_response);
let root: RootIdentity = platform_identity.into_root();
let identity: Identity = Identity::extract(&req).await?;
identity.save(&root.make_authenticated_cookie());
Ok(HttpResponse::Found()
.header(LOCATION, "/register/finish")
.finish())
});
}
fn linking_authenticated_handler(
req: HttpRequest,
ident: Identity,
) -> Self::LinkAuthenticatedFut {
return Box::pin(async move {
let redir_url: RedirectUrl = make_redirect_url(&req, Self::link_redirect_path());
let token: BasicTokenResponse = Self::token_exchange(redir_url, &req)?;
let mut cookie: AuthenticationCookie = ident
.identity()
.await
.ok_or(TelescopeError::NotAuthenticated)?;
let platform_identity: T::IdentityType = T::IdentityType::from_basic_token(&token);
let platform_id: String = platform_identity.platform_user_id().await?;
let user_id = cookie.get_user_id_or_error().await?;
info!(
"Linking {} account ID {} to Telescope User {}",
Self::USER_ACCOUNT_TY,
platform_id,
user_id
);
let linked_accounts = UserAccounts::send(user_id)
.await?
.into_iter()
.collect::<HashMap<UserAccountType, String>>();
if linked_accounts.contains_key(&Self::USER_ACCOUNT_TY) {
if linked_accounts[&Self::USER_ACCOUNT_TY] == platform_id {
info!("Already linked. Updating Cookie.");
platform_identity.add_to_cookie(&mut cookie);
ident.save(&cookie);
return Ok(HttpResponse::Found()
.header(LOCATION, format!("/user/{}", user_id))
.finish());
}
let other_authenticator_accounts: usize = linked_accounts
.iter()
.filter(|(ty, _)| **ty != Self::USER_ACCOUNT_TY)
.filter(|(ty, _)| AUTHENTICATOR_ACCOUNT_TYPES.contains(ty))
.count();
if other_authenticator_accounts >= 1 {
info!("Replacing currently linked account.");
UnlinkUserAccount::send(user_id, Self::USER_ACCOUNT_TY).await?;
}
}
LinkUserAccount::send(user_id, Self::USER_ACCOUNT_TY, platform_id).await?;
platform_identity.add_to_cookie(&mut cookie);
ident.save(&cookie);
Ok(HttpResponse::Found()
.header(LOCATION, format!("/user/{}", user_id))
.finish())
});
}
}