-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.rs
More file actions
383 lines (307 loc) · 16 KB
/
handler.rs
File metadata and controls
383 lines (307 loc) · 16 KB
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
mod openid;
mod util;
use async_trait::async_trait;
use base64::Engine;
use rand::Rng;
use shared::{api::{auth::{AuthCheck, AuthCheckResetPassword, AuthCheckResetPasswordRequest, AuthCheckResetPasswordResponse, AuthCheckResponse, AuthConfirmResetPassword, AuthConfirmResetPasswordRequest, AuthConfirmResetPasswordResponse, AuthConfirmVerifyEmail, AuthConfirmVerifyEmailRequest, AuthOpenIdAccessTokenHook, AuthOpenIdConnect, AuthOpenIdConnectRequest, AuthOpenIdConnectResponse, AuthOpenIdFinalizeExec, AuthOpenIdFinalizeExecResponse, AuthOpenIdFinalizeQuery, AuthOpenIdFinalizeQueryResponse, AuthOpenIdFinalizeRequest, AuthRegister, AuthRegisterRequest, AuthRegisterResponse, AuthSendResetPasswordAny, AuthSendResetPasswordMe, AuthSendResetPasswordRequestAny, AuthSendVerifyEmail, AuthSignin, AuthSigninRequest, AuthSigninResponse, AuthSignout}, ApiBoth, ApiReq, ApiRes}, backend::{result::{ApiError, ApiResult, AuthError}, worker::ResponseExt}, frontend::route::NotFoundReason as FrontendNotFoundReason, user::UserId};
use web_sys::Response;
use crate::{
api_ext::{ApiBothExt, ApiBothWithExtraExt, ApiEmptyDynRouteWithExtraExt, ApiEmptyExt, ApiReqExt, ApiResExt}, auth::{durable_objects::token::{AuthTokenDO, AuthTokenKind}, handler::util::hash_password}, config::{AUTH_RESET_PASSWORD_TOKEN_EXPIRES, AUTH_SIGNIN_TOKEN_EXPIRES, AUTH_VERIFY_EMAIL_TOKEN_EXPIRES, FRONTEND_DOMAIN, FRONTEND_ROOT_PATH, OAUTH_REGISTER_PASSWORD_LENGTH}, db::user::UserAccount, mailer::{self, MailerKind}, ApiContext
};
use self::{openid::OpenIdProcessor, util::{delete_signin_cookie, set_signin_cookie, validate_oob_token}};
use super::durable_objects::{openid::{OpenIdSession, OpenIdSessionDO, OpenIdSessionFinalizeInfo}, token::{AuthTokenAfterValidation, AuthTokenCreateResponse}};
use shared::frontend::route::{Route as FrontendRoute, Landing as FrontendLanding, AuthRoute as FrontendAuthRoute};
#[async_trait(?Send)]
impl ApiBothWithExtraExt for AuthSignin {
type Req = <AuthSignin as ApiBoth>::Req;
type Res = <AuthSignin as ApiBoth>::Res;
type Extra = AuthTokenCreateResponse;
async fn handle(ctx: &ApiContext, data: AuthSigninRequest) -> ApiResult<(Self::Res, Self::Extra)> {
async fn inner(ctx: &ApiContext, data: AuthSigninRequest) -> ApiResult<(AuthSigninResponse, AuthTokenCreateResponse)> {
let AuthSigninRequest { email, password } = data;
let user = UserAccount::load_by_email(&ctx.env, &email).await?;
// see registration, this is *not* the user's plaintext password, it's just the argon2 output hash
// we need to get the salt from the db and hash it again for comparison, however
let db_salt = &base64::engine::general_purpose::URL_SAFE_NO_PAD
.decode(&user.password)
.map_err(|err| ApiError::from(err.to_string()))?
[0..32];
let req_password = hash_password(&password, Some(db_salt))?;
// see if they match
if user.password != req_password {
return Err("mismatched password".into())
}
// sign the user in and return
let uid = user.id;
let auth_token = AuthTokenDO::create(&ctx.env, AuthTokenKind::Signin, uid.clone(), user.user_token, AUTH_SIGNIN_TOKEN_EXPIRES).await?;
let auth_key = auth_token.key.clone();
Ok((AuthSigninResponse{
uid,
email_verified: user.email_verified,
auth_key
}, auth_token))
}
inner(ctx, data).await.map_err(|_| {
// can log the specific error here, but clients only see InvalidSignin
// to avoid leaking semi-sensitive info (like who has an account etc.)
AuthError::InvalidSignin.into()
})
}
fn response(_ctx: &ApiContext, data: AuthSigninResponse, auth_token: AuthTokenCreateResponse) -> Response {
let res = Response::new_json(&data);
set_signin_cookie(&res, &auth_token.id);
res
}
}
#[async_trait(?Send)]
impl ApiBothWithExtraExt for AuthRegister {
type Req = <AuthRegister as ApiBoth>::Req;
type Res = <AuthRegister as ApiBoth>::Res;
type Extra = AuthTokenCreateResponse;
async fn handle(ctx: &ApiContext, data: AuthRegisterRequest) -> ApiResult<(Self::Res, Self::Extra)> {
let AuthRegisterRequest {email, password} = data;
if UserAccount::exists_by_email(&ctx.env, &email).await? {
return Err(AuthError::EmailAlreadyExists.into())
}
let password = hash_password(&password, None)?;
// create a new user account
let uid = UserId::new(uuid::Uuid::now_v7());
let user_token = uuid::Uuid::now_v7().as_simple().to_string();
UserAccount::insert(&ctx.env, &uid, &password, &email, &user_token).await?;
// sign the user in and return
let auth_token = AuthTokenDO::create(&ctx.env, AuthTokenKind::Signin, uid.clone(), user_token.clone(), AUTH_SIGNIN_TOKEN_EXPIRES).await?;
mailer::send(&ctx, &email, MailerKind::EmailVerification {
oob_token_id: auth_token.id.clone(),
oob_token_key: auth_token.key.clone()
}).await?;
let auth_key = auth_token.key.clone();
Ok((AuthRegisterResponse{
uid,
email_verified: false,
auth_key
}, auth_token))
}
fn response(_ctx: &ApiContext, data: AuthRegisterResponse, auth_token: AuthTokenCreateResponse) -> Response {
let res = Response::new_json(&data);
set_signin_cookie(&res, &auth_token.id);
res
}
}
#[async_trait(?Send)]
impl ApiResExt for AuthCheck {
type Res = <AuthCheck as ApiRes>::Res;
async fn handle(ctx: &ApiContext) -> ApiResult<Self::Res> {
let uid = ctx.uid_unchecked();
Ok(AuthCheckResponse {
uid
})
}
}
#[async_trait(?Send)]
impl ApiBothExt for AuthOpenIdConnect {
type Req = <AuthOpenIdConnect as ApiBoth>::Req;
type Res = <AuthOpenIdConnect as ApiBoth>::Res;
async fn handle(ctx: &ApiContext, data: AuthOpenIdConnectRequest) -> ApiResult<Self::Res> {
let url = OpenIdProcessor::new(data.provider).get_auth_url(&ctx.env).await?;
Ok(AuthOpenIdConnectResponse{url})
}
}
#[async_trait(?Send)]
impl ApiEmptyDynRouteWithExtraExt for AuthOpenIdAccessTokenHook {
// the second param is for whether a user exists
type Extra = ApiResult<OpenIdSession>;
async fn handle(&self, ctx: &ApiContext) -> ApiResult<Self::Extra> {
let url = web_sys::Url::new(&ctx.req.url())?;
let search_params = url.search_params();
let processor = OpenIdProcessor::new(self.provider);
match (search_params.get("code"), search_params.get("state")) {
(Some(code), Some(state)) => {
let (session, _) = processor.validate_token_claims(ctx, code, state).await?;
Ok(Ok(session))
}
_ => {
Ok(Err("missing code or state".into()))
}
}
}
fn response(&self, _ctx: &ApiContext, session: ApiResult<OpenIdSession>) -> Response {
let frontend_route = match session {
Ok(session) => {
FrontendRoute::Landing(FrontendLanding::Auth(FrontendAuthRoute::OpenIdFinalize{
session_id: session.id,
session_key: session.key
}))
},
Err(_) => {
FrontendRoute::NotFound(FrontendNotFoundReason::NoAuth)
}
};
worker::console_log!("redirecting to {:?}", frontend_route.link(FRONTEND_DOMAIN, FRONTEND_ROOT_PATH));
Response::new_temp_redirect(&frontend_route.link(FRONTEND_DOMAIN, FRONTEND_ROOT_PATH))
}
}
#[async_trait(?Send)]
impl ApiBothExt for AuthOpenIdFinalizeQuery {
type Req = <AuthOpenIdFinalizeQuery as ApiBoth>::Req;
type Res = <AuthOpenIdFinalizeQuery as ApiBoth>::Res;
async fn handle(ctx: &ApiContext, data: AuthOpenIdFinalizeRequest) -> ApiResult<AuthOpenIdFinalizeQueryResponse> {
let AuthOpenIdFinalizeRequest{session_id, session_key} = data;
let session = OpenIdSession{id: session_id, key: session_key};
let OpenIdSessionFinalizeInfo{ email, .. } = OpenIdSessionDO::finalize_query(&ctx.env, session.clone()).await?;
let user_exists = UserAccount::load_by_email(&ctx.env, &email).await.is_ok();
Ok(AuthOpenIdFinalizeQueryResponse{
email,
user_exists
})
}
}
#[async_trait(?Send)]
impl ApiBothWithExtraExt for AuthOpenIdFinalizeExec {
type Req = <AuthOpenIdFinalizeExec as ApiBoth>::Req;
type Res = <AuthOpenIdFinalizeExec as ApiBoth>::Res;
type Extra = AuthTokenCreateResponse;
async fn handle(ctx: &ApiContext, data: AuthOpenIdFinalizeRequest) -> ApiResult<(AuthOpenIdFinalizeExecResponse, AuthTokenCreateResponse)> {
let AuthOpenIdFinalizeRequest{session_id, session_key} = data;
let session = OpenIdSession{id: session_id, key: session_key};
let OpenIdSessionFinalizeInfo{ email, email_verified, .. } = OpenIdSessionDO::finalize_exec(&ctx.env, session.clone()).await?;
let mut user = match UserAccount::load_by_email(&ctx.env, &email).await.ok() {
// user already exists, just sign them in
Some(user) => {
worker::console_log!("user already exists, signing in");
user
},
// user doesn't exist, register them
None => {
worker::console_log!("user does not exist, registering");
// theoretically we could use finalize_info.access_token to load profile info etc.
// but, meh, let the user just set it all fresh - makes it easier to integrate
// with various providers too
// create a new user account
let uid = UserId::new(uuid::Uuid::now_v7());
let user_token = uuid::Uuid::now_v7().as_simple().to_string();
// random password
let password = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(&rand::thread_rng().gen::<[u8; OAUTH_REGISTER_PASSWORD_LENGTH]>());
UserAccount::insert(&ctx.env, &uid, &password, &email, &user_token).await?;
UserAccount::load_by_email(&ctx.env, &email).await?
}
};
// update the user's email_verified status if it's changed to true
if !user.email_verified && email_verified {
UserAccount::update_email_verified(&ctx.env, &user.id, email_verified).await?;
user.email_verified = true;
}
// sign the user in and return
let auth_token = AuthTokenDO::create(&ctx.env, AuthTokenKind::Signin, user.id.clone(), user.user_token.clone(), AUTH_SIGNIN_TOKEN_EXPIRES).await?;
let auth_key = auth_token.key.clone();
Ok((AuthOpenIdFinalizeExecResponse{
uid: user.id,
email_verified: user.email_verified || email_verified,
auth_key
}, auth_token))
}
fn response(_ctx: &ApiContext, data: AuthOpenIdFinalizeExecResponse, auth_token: AuthTokenCreateResponse) -> Response {
let res = Response::new_json(&data);
set_signin_cookie(&res, &auth_token.id);
res
}
}
#[async_trait(?Send)]
impl ApiEmptyExt for AuthSignout {
async fn handle(ctx: &ApiContext) -> ApiResult<()> {
let user = ctx.user.as_ref().unwrap();
AuthTokenDO::destroy(&ctx.env, &user.token_id).await?;
Ok(())
}
fn response(_ctx: &ApiContext) -> Response {
let res = Response::new_empty();
delete_signin_cookie(&res);
res
}
}
#[async_trait(?Send)]
impl ApiEmptyExt for AuthSendVerifyEmail {
async fn handle(ctx: &ApiContext) -> ApiResult<()> {
let user = ctx.user.as_ref().unwrap();
// create a new oob token
let auth_token = AuthTokenDO::create(&ctx.env, AuthTokenKind::VerifyEmail, user.account.id.clone(), user.account.user_token.clone(), AUTH_VERIFY_EMAIL_TOKEN_EXPIRES).await?;
mailer::send(ctx, &user.account.email, MailerKind::EmailVerification {
oob_token_id: auth_token.id,
oob_token_key: auth_token.key
}).await?;
Ok(())
}
}
#[async_trait(?Send)]
impl ApiReqExt for AuthConfirmVerifyEmail {
type Req = <AuthConfirmVerifyEmail as ApiReq>::Req;
async fn handle(ctx: &ApiContext, data: AuthConfirmVerifyEmailRequest) -> ApiResult<()> {
let AuthConfirmVerifyEmailRequest {oob_token_id, oob_token_key} = data;
let account = validate_oob_token(&ctx.env, AuthTokenKind::VerifyEmail, oob_token_id, oob_token_key, AuthTokenAfterValidation::Delete).await?;
// now update the DB
UserAccount::update_email_verified(&ctx.env, &account.id, true).await?;
Ok(())
}
}
#[async_trait(?Send)]
impl ApiReqExt for AuthSendResetPasswordAny {
type Req = <AuthSendResetPasswordAny as ApiReq>::Req;
async fn handle(ctx: &ApiContext, data: AuthSendResetPasswordRequestAny) -> ApiResult<()> {
let account = UserAccount::load_by_email(&ctx.env, &data.email).await.map_err(|_| AuthError::NoUserPasswordReset)?;
helper_send_password_reset(ctx, &account).await
}
}
#[async_trait(?Send)]
impl ApiEmptyExt for AuthSendResetPasswordMe {
async fn handle(ctx: &ApiContext) -> ApiResult<()> {
let user = ctx.user.as_ref().unwrap();
helper_send_password_reset(ctx, &user.account).await
}
}
pub async fn helper_send_password_reset(ctx: &ApiContext, account: &UserAccount) -> ApiResult<()> {
// create a new oob token
let auth_token = AuthTokenDO::create(&ctx.env, AuthTokenKind::PasswordReset, account.id.clone(), account.user_token.clone(), AUTH_RESET_PASSWORD_TOKEN_EXPIRES).await?;
mailer::send(&ctx, &account.email, MailerKind::PasswordReset {
oob_token_id: auth_token.id,
oob_token_key: auth_token.key
}).await?;
Ok(())
}
#[async_trait(?Send)]
impl ApiBothWithExtraExt for AuthConfirmResetPassword {
type Req = <AuthConfirmResetPassword as ApiBoth>::Req;
type Res = <AuthConfirmResetPassword as ApiBoth>::Res;
type Extra = AuthTokenCreateResponse;
async fn handle(ctx: &ApiContext, data: AuthConfirmResetPasswordRequest) -> ApiResult<(AuthConfirmResetPasswordResponse, AuthTokenCreateResponse)> {
let AuthConfirmResetPasswordRequest{oob_token_id, oob_token_key, password} = data;
let account = validate_oob_token(&ctx.env, AuthTokenKind::PasswordReset, oob_token_id, oob_token_key, AuthTokenAfterValidation::Delete).await?;
let password = hash_password(&password, None)?;
let user_token = uuid::Uuid::now_v7().as_simple().to_string();
UserAccount::reset_password(&ctx.env, &account.id, &password, &user_token).await?;
// note that this uses the new user_token
let auth_token = AuthTokenDO::create(&ctx.env, AuthTokenKind::Signin, account.id.clone(), user_token.clone(), AUTH_SIGNIN_TOKEN_EXPIRES).await?;
let auth_key = auth_token.key.clone();
Ok((AuthConfirmResetPasswordResponse{
uid: account.id.clone(),
email_verified: account.email_verified,
auth_key
}, auth_token))
}
fn response(_ctx: &ApiContext, data: AuthConfirmResetPasswordResponse, auth_token: AuthTokenCreateResponse) -> Response {
let res = Response::new_json(&data);
set_signin_cookie(&res, &auth_token.id);
res
}
}
#[async_trait(?Send)]
impl ApiBothExt for AuthCheckResetPassword {
type Req = <AuthCheckResetPassword as ApiBoth>::Req;
type Res = <AuthCheckResetPassword as ApiBoth>::Res;
async fn handle(ctx: &ApiContext, data: AuthCheckResetPasswordRequest) -> ApiResult<AuthCheckResetPasswordResponse> {
let AuthCheckResetPasswordRequest{oob_token_id, oob_token_key} = data;
let account = validate_oob_token(&ctx.env, AuthTokenKind::PasswordReset, oob_token_id, oob_token_key, AuthTokenAfterValidation::ExtendExpiresMs(AUTH_RESET_PASSWORD_TOKEN_EXPIRES)).await?;
Ok(AuthCheckResetPasswordResponse{
uid: account.id,
email: account.email
})
}
}