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
use crate::api::rcos::users::accounts::link::LinkUserAccount;
use crate::api::rcos::users::accounts::lookup::AccountLookup;
use crate::api::rcos::users::accounts::reverse_lookup::ReverseLookup;
use crate::api::rcos::users::UserAccountType;
use crate::error::TelescopeError;
use crate::web::services::auth::identity::{AuthenticationCookie, RootIdentity};
use crate::web::services::auth::{identity::Identity, make_redirect_url, IdentityProvider};
use actix_web::http::header::LOCATION;
use actix_web::{web::Query, FromRequest};
use actix_web::{HttpRequest, HttpResponse};
use futures::future::LocalBoxFuture;
use futures::future::{ready, Ready};
use regex::Regex;
use uuid::Uuid;
const RPI_CAS_ENDPOINT: &'static str = "https://cas.auth.rpi.edu/cas";
#[derive(Deserialize, Clone, Debug)]
struct CasAuthenticatedParameters {
ticket: String,
}
#[derive(Serialize, Clone, Debug)]
struct CasIdentificationParameters {
ticket: String,
service: String,
}
fn make_cas_user_regex() -> Regex {
Regex::new(r"<cas:user>([[:alnum:]]+)</cas:user>").expect("Could not create CAS RCS ID Regex")
}
lazy_static! {
static ref CAS_USER_REGEX: Regex = make_cas_user_regex();
}
fn extract_rcs_id(xml: &str) -> Option<String> {
Some(
CAS_USER_REGEX
.captures(xml)?
.get(1)?
.as_str()
.to_lowercase(),
)
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RpiCasIdentity {
pub rcs_id: String,
}
impl RpiCasIdentity {
pub async fn get_rcos_user_id(&self) -> Result<Option<Uuid>, TelescopeError> {
ReverseLookup::execute(UserAccountType::Rpi, self.rcs_id.clone()).await
}
}
async fn cas_authenticated(
req: &HttpRequest,
redir_path: String,
) -> Result<String, TelescopeError> {
let Query(params): Query<CasAuthenticatedParameters> =
Query::<CasAuthenticatedParameters>::extract(req)
.await
.map_err(|err| {
error!(
"Could not extract CAS ticket from request parameters: {}",
err
);
TelescopeError::BadRequest {
header: "Malformed CAS request".into(),
message: format!(
"The RPI CAS endpoint did not respond with the appropriate \
data. Please try again. If this error persists, contact a coordinator and file \
an issue on Telescope's GitHub. Internal error: {}",
err
),
show_status_code: true,
}
})?;
let validation_params = CasIdentificationParameters {
service: make_redirect_url(req, redir_path).to_string(),
ticket: params.ticket,
};
let validation_query: String = serde_urlencoded::to_string(validation_params)
.expect("Could not URL-encode CAS validation parameters");
let validation_url: String =
format!("{}/serviceValidate?{}", RPI_CAS_ENDPOINT, validation_query);
let cas_xml: String = reqwest::get(validation_url.as_str())
.await
.map_err(TelescopeError::rpi_cas_error)?
.text()
.await
.map_err(TelescopeError::rpi_cas_error)?;
return extract_rcs_id(cas_xml.as_str()).ok_or(TelescopeError::RpiCasError(format!(
"Could not extract RCS ID from RPI CAS response. Response xml: {}",
cas_xml
)));
}
fn make_authentication_url(req: &HttpRequest, redir_path: String) -> String {
let redirect_url = make_redirect_url(&req, redir_path);
let encoded: String = serde_urlencoded::to_string(&[("service", redirect_url.as_str())])
.expect("Could not URL-encode CAS parameters.");
return format!("{}/login?{}", RPI_CAS_ENDPOINT, encoded);
}
pub struct RpiCas;
impl IdentityProvider for RpiCas {
const SERVICE_NAME: &'static str = "rpi_cas";
const USER_ACCOUNT_TY: UserAccountType = UserAccountType::Rpi;
type LoginResponse = HttpResponse;
type RegistrationResponse = HttpResponse;
type LinkResponse = Result<HttpResponse, TelescopeError>;
type LoginFut = Ready<Self::LoginResponse>;
type RegistrationFut = Ready<Self::RegistrationResponse>;
type LinkFut = LocalBoxFuture<'static, Self::LinkResponse>;
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 {
ready(
HttpResponse::Found()
.header(
LOCATION,
make_authentication_url(&req, Self::login_redirect_path()),
)
.finish(),
)
}
fn registration_handler(req: HttpRequest) -> Self::RegistrationFut {
ready(
HttpResponse::Found()
.header(
LOCATION,
make_authentication_url(&req, Self::registration_redirect_path()),
)
.finish(),
)
}
fn link_handler(req: HttpRequest, ident: Identity) -> Self::LinkFut {
return Box::pin(async move {
if let Some(authenticated_identity) = ident.identity().await {
if let RootIdentity::RpiCas(_) = authenticated_identity.root {
return Err(TelescopeError::BadRequest {
header: "RPI CAS already linked".into(),
message: "You are already signed into an RPI CAS account.".into(),
show_status_code: false,
});
}
let auth_url = make_authentication_url(&req, Self::link_redirect_path());
Ok(HttpResponse::Found().header(LOCATION, auth_url).finish())
} else {
Err(TelescopeError::NotAuthenticated)
}
});
}
fn login_authenticated_handler(req: HttpRequest) -> Self::LoginAuthenticatedFut {
return Box::pin(async move {
let rcs_id: String = cas_authenticated(&req, Self::login_redirect_path()).await?;
let token = RpiCasIdentity { rcs_id };
let user_id = token
.get_rcos_user_id()
.await?
.ok_or(TelescopeError::resource_not_found(
"Could not find associated user account",
format!(
"Could not find a Telescope account for {}@rpi.edu. Please \
create an account or login using another provider.",
token.rcs_id
),
))?;
let identity: Identity = Identity::extract(&req).await?;
identity.save(&RootIdentity::RpiCas(token).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 rcs_id: String =
cas_authenticated(&req, Self::registration_redirect_path()).await?;
let cookie: RootIdentity = RootIdentity::RpiCas(RpiCasIdentity { rcs_id });
let identity: Identity = Identity::extract(&req).await?;
identity.save(&cookie.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 authenticated: AuthenticationCookie = ident
.identity()
.await
.ok_or(TelescopeError::NotAuthenticated)?;
let user_id = authenticated.get_user_id_or_error().await?;
let existing_rcs_id: Option<String> =
AccountLookup::send(user_id, Self::USER_ACCOUNT_TY).await?;
let new_rcs_id: String = cas_authenticated(&req, Self::link_redirect_path()).await?;
let add_new_to_db: bool = existing_rcs_id.is_none();
let new_matches_existing: bool = existing_rcs_id
.as_ref()
.map(|existing| existing.as_str() == new_rcs_id.as_str())
.unwrap_or(true);
if add_new_to_db {
LinkUserAccount::send(user_id, Self::USER_ACCOUNT_TY, new_rcs_id.clone()).await?;
}
if !new_matches_existing {
return Err(TelescopeError::BadRequest {
header: "Different RCS ID already linked".into(),
message: format!(
"This account is already linked to the RPI CAS system \
as {}@rpi.edu. Please unlink this RCS id before linking a different one. \
If you did not link this account please contact a coordinator.\
",
existing_rcs_id.unwrap()
),
show_status_code: false,
});
}
return Ok(HttpResponse::Found()
.header(LOCATION, format!("/user/{}", user_id))
.finish());
});
}
}