1use http::{Method, StatusCode};
4use serde::{Deserialize, Serialize};
5use serde_json::{Map, Value as Json};
6
7use crate::adapter::Adapter;
8use crate::endpoint::{Authenticated, Ctx, Empty, Endpoint, MaybeAuthenticated, Public};
9use crate::error::{AuthError, codes};
10use crate::events::{EmailVerified, PasswordChanged, UserUpdated};
11use crate::internal::{NewAccount, NewUser, SignInResult, url_encode};
12use crate::mail::{AuthEmail, ResetPassword as ResetPasswordEmail};
13use crate::model::Model;
14use crate::models::{Session, User};
15use crate::plugin::PluginBuilder;
16use crate::session::UserView;
17use crate::value::{Id, Value, camel_case};
18
19pub(crate) fn register<D: Adapter>(app: &mut PluginBuilder<'_, D>, email_password: bool) {
20 app.endpoint(GetSession)
21 .endpoint(SignOut)
22 .endpoint(ListSessions)
23 .endpoint(RevokeSession)
24 .endpoint(RevokeSessions)
25 .endpoint(RevokeOtherSessions)
26 .endpoint(UpdateUser)
27 .endpoint(SendVerificationEmail)
28 .endpoint(VerifyEmail);
29 if email_password {
30 app.endpoint(SignUpEmail)
31 .endpoint(SignInEmail)
32 .endpoint(ChangePassword)
33 .endpoint(RequestPasswordReset)
34 .endpoint(ForgetPassword)
35 .endpoint(ResetPasswordCallback)
36 .endpoint(ResetPassword);
37 }
38}
39
40#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
41pub struct Status {
42 pub status: bool,
43}
44
45const OK: Status = Status { status: true };
46
47fn check_callback<D: Adapter, A>(ctx: &Ctx<D, A>, url: Option<&str>) -> Result<(), AuthError> {
48 match url {
49 Some(url) if !ctx.config().is_safe_redirect(url) => Err(AuthError::new(
50 StatusCode::FORBIDDEN,
51 codes::INVALID_CALLBACK_URL,
52 "callback URL is not on a trusted origin",
53 )),
54 _ => Ok(()),
55 }
56}
57
58fn with_query(url: &str, key: &str, value: &str) -> String {
59 let sep = if url.contains('?') { '&' } else { '?' };
60 format!("{url}{sep}{key}={}", url_encode(value))
61}
62
63fn normalize_email(email: &str) -> Result<String, AuthError> {
64 let email = email.trim().to_lowercase();
65 let valid = email.len() <= 254
66 && email.split_once('@').is_some_and(|(local, domain)| {
67 !local.is_empty() && domain.contains('.') && !domain.starts_with('.')
68 });
69 if !valid {
70 return Err(AuthError::bad_request(
71 codes::INVALID_EMAIL,
72 "invalid email",
73 ));
74 }
75 Ok(email)
76}
77
78fn user_input_fields<D: Adapter, A>(
80 ctx: &Ctx<D, A>,
81 extra: &Map<String, Json>,
82 require_all: bool,
83) -> Result<Vec<(&'static str, Value)>, AuthError> {
84 let table = ctx.schema().expect(User::TABLE);
85 let mut out = Vec::new();
86 for (key, json) in extra {
87 let column = table
88 .columns
89 .iter()
90 .find(|c| c.input && c.owner != "core" && camel_case(c.name) == *key)
91 .ok_or_else(|| {
92 AuthError::bad_request(codes::INVALID_FIELD, format!("field `{key}` can't be set"))
93 })?;
94 let value = Value::from_json(column.ty, json)
95 .filter(|v| !v.is_null() || column.nullable)
96 .ok_or_else(|| {
97 AuthError::bad_request(
98 codes::INVALID_FIELD,
99 format!("field `{key}` has the wrong type"),
100 )
101 })?;
102 out.push((column.name, value));
103 }
104 if require_all {
105 for column in table
106 .columns
107 .iter()
108 .filter(|c| c.input && c.owner != "core" && !c.nullable && c.default.is_none())
109 {
110 if !out.iter().any(|(name, _)| *name == column.name) {
111 return Err(AuthError::bad_request(
112 codes::INVALID_FIELD,
113 format!("field `{}` is required", camel_case(column.name)),
114 ));
115 }
116 }
117 }
118 Ok(out)
119}
120
121fn email_password<D: Adapter, A>(ctx: &Ctx<D, A>) -> &crate::config::EmailPassword {
122 ctx.config()
123 .email_password
124 .as_ref()
125 .expect("route only registered with email_password")
126}
127
128pub struct SignUpEmail;
131
132#[derive(Debug, Deserialize)]
133#[serde(rename_all = "camelCase")]
134pub struct SignUpEmailInput {
135 pub name: String,
136 pub email: String,
137 pub password: String,
138 #[serde(default)]
139 pub image: Option<String>,
140 #[serde(default, rename = "callbackURL")]
141 pub callback_url: Option<String>,
142 #[serde(default)]
143 pub remember_me: Option<bool>,
144 #[serde(flatten)]
146 pub extra: Map<String, Json>,
147}
148
149#[derive(Debug, Serialize)]
150pub struct SignUpOutput {
151 pub token: Option<String>,
152 pub user: Map<String, Json>,
153}
154
155impl<D: Adapter> Endpoint<D> for SignUpEmail {
156 const METHOD: Method = Method::POST;
157 const PATH: &'static str = "/sign-up/email";
158 type Access = Public;
159 type Input = SignUpEmailInput;
160 type Output = SignUpOutput;
161
162 async fn call(
163 &self,
164 ctx: Ctx<D, Public>,
165 input: SignUpEmailInput,
166 ) -> Result<SignUpOutput, AuthError> {
167 let config = email_password(&ctx);
168 let email = normalize_email(&input.email)?;
169 check_callback(&ctx, input.callback_url.as_deref())?;
170 let internal = ctx.internal();
171 internal.validate_new_password(&input.password)?;
172 let extra = user_input_fields(&ctx, &input.extra, true)?;
173
174 if config.require_email_verification && internal.find_user_by_email(&email).await?.is_some()
175 {
176 ctx.passwords().verify_dummy(&input.password).await;
178 let now = time::OffsetDateTime::now_utc();
179 let ghost = User {
180 id: Id::new_v7(),
181 email,
182 email_verified: false,
183 name: input.name,
184 image: input.image,
185 created_at: now,
186 updated_at: now,
187 };
188 let user = serde_json::to_value(ghost)
189 .ok()
190 .and_then(|v| v.as_object().cloned())
191 .unwrap_or_default();
192 return Ok(SignUpOutput { token: None, user });
193 }
194
195 let hash = ctx
196 .passwords()
197 .hash(&input.password)
198 .await
199 .map_err(AuthError::internal)?;
200 let new_user = NewUser {
201 email,
202 name: input.name,
203 image: input.image,
204 email_verified: false,
205 extra,
206 };
207 let user = internal
208 .create_user(new_user, Some(NewAccount::credential(hash)))
209 .await?;
210
211 if config.require_email_verification
212 || ctx.config().email_verification.send_on_sign_up && ctx.mailer().is_some()
213 {
214 internal
215 .send_verification_email(&user, input.callback_url.as_deref())
216 .await?;
217 }
218 if config.require_email_verification || !config.auto_sign_in {
219 return Ok(SignUpOutput {
220 token: None,
221 user: user.to_json(),
222 });
223 }
224 match internal
225 .sign_in(user.clone(), "email", input.remember_me.unwrap_or(true))
226 .await?
227 {
228 SignInResult::SignedIn(session) => Ok(SignUpOutput {
229 token: session.token,
230 user: user.to_json(),
231 }),
232 SignInResult::Challenge(_) => Ok(SignUpOutput {
233 token: None,
234 user: user.to_json(),
235 }),
236 }
237 }
238}
239
240pub struct CreateUser;
244
245#[derive(Debug, Default, Deserialize)]
246#[serde(rename_all = "camelCase")]
247pub struct CreateUserInput {
248 pub email: String,
249 pub name: String,
250 #[serde(default)]
252 pub password: Option<String>,
253 #[serde(default)]
255 pub fields: Map<String, Json>,
256}
257
258impl<D: Adapter> Endpoint<D> for CreateUser {
259 const METHOD: Method = Method::POST;
260 const PATH: &'static str = "/create-user";
261 type Access = Public;
262 type Input = CreateUserInput;
263 type Output = UserView;
264
265 async fn call(
266 &self,
267 ctx: Ctx<D, Public>,
268 input: CreateUserInput,
269 ) -> Result<UserView, AuthError> {
270 let email = normalize_email(&input.email)?;
271 let internal = ctx.internal();
272 let extra = user_input_fields(&ctx, &input.fields, true)?;
273 let account = match &input.password {
274 Some(password) => {
275 internal.validate_new_password(password)?;
276 let hash = ctx
277 .passwords()
278 .hash(password)
279 .await
280 .map_err(AuthError::internal)?;
281 Some(NewAccount::credential(hash))
282 }
283 None => None,
284 };
285 let new_user = NewUser {
286 email,
287 name: input.name,
288 extra,
289 ..NewUser::default()
290 };
291 internal.create_user(new_user, account).await
292 }
293}
294
295pub struct SignInEmail;
298
299#[derive(Debug, Deserialize)]
300#[serde(rename_all = "camelCase")]
301pub struct SignInEmailInput {
302 pub email: String,
303 pub password: String,
304 #[serde(default, rename = "callbackURL")]
305 pub callback_url: Option<String>,
306 #[serde(default)]
307 pub remember_me: Option<bool>,
308}
309
310#[derive(Debug, Serialize)]
311#[serde(untagged)]
312pub enum SignInOutput {
313 SignedIn {
314 redirect: bool,
315 token: String,
316 url: Option<String>,
317 user: Map<String, Json>,
318 },
319 Challenge(Json),
321}
322
323impl SignInOutput {
324 pub fn from_result<D: Adapter, A>(
325 ctx: &Ctx<D, A>,
326 result: SignInResult,
327 callback_url: Option<String>,
328 ) -> Self {
329 match result {
330 SignInResult::SignedIn(session) => {
331 if let Some(url) = &callback_url {
332 ctx.redirect(url.clone());
333 }
334 SignInOutput::SignedIn {
335 redirect: callback_url.is_some(),
336 token: session.token.clone().unwrap_or_default(),
337 url: callback_url,
338 user: session.user.to_json(),
339 }
340 }
341 SignInResult::Challenge(body) => SignInOutput::Challenge(body),
342 }
343 }
344}
345
346fn invalid_credentials() -> AuthError {
347 AuthError::new(
348 StatusCode::UNAUTHORIZED,
349 codes::INVALID_EMAIL_OR_PASSWORD,
350 "invalid email or password",
351 )
352}
353
354impl<D: Adapter> Endpoint<D> for SignInEmail {
355 const METHOD: Method = Method::POST;
356 const PATH: &'static str = "/sign-in/email";
357 type Access = Public;
358 type Input = SignInEmailInput;
359 type Output = SignInOutput;
360
361 async fn call(
362 &self,
363 ctx: Ctx<D, Public>,
364 input: SignInEmailInput,
365 ) -> Result<SignInOutput, AuthError> {
366 let config = email_password(&ctx);
367 let email = normalize_email(&input.email)?;
368 check_callback(&ctx, input.callback_url.as_deref())?;
369 let internal = ctx.internal();
370 let passwords = ctx.passwords();
371
372 let Some(user) = internal.find_user_by_email(&email).await? else {
373 passwords.verify_dummy(&input.password).await;
374 return Err(invalid_credentials());
375 };
376 let Some(hash) = internal
377 .credential_account(&user.id)
378 .await?
379 .and_then(|a| a.password_hash)
380 else {
381 passwords.verify_dummy(&input.password).await;
382 return Err(invalid_credentials());
383 };
384 if !passwords
385 .verify(&input.password, &hash)
386 .await
387 .map_err(AuthError::internal)?
388 {
389 return Err(invalid_credentials());
390 }
391 if passwords.needs_rehash(&hash) {
392 internal.set_password(&user.id, &input.password).await?;
393 }
394 if config.require_email_verification && !user.email_verified {
395 if ctx.mailer().is_some() {
396 internal
397 .send_verification_email(&user, input.callback_url.as_deref())
398 .await?;
399 }
400 return Err(AuthError::new(
401 StatusCode::FORBIDDEN,
402 codes::EMAIL_NOT_VERIFIED,
403 "email is not verified",
404 ));
405 }
406 let result = internal
407 .sign_in(user, "email", input.remember_me.unwrap_or(true))
408 .await?;
409 Ok(SignInOutput::from_result(&ctx, result, input.callback_url))
410 }
411}
412
413pub struct SignOut;
416
417#[derive(Debug, Serialize)]
418pub struct SignOutOutput {
419 pub success: bool,
420}
421
422impl<D: Adapter> Endpoint<D> for SignOut {
423 const METHOD: Method = Method::POST;
424 const PATH: &'static str = "/sign-out";
425 type Access = MaybeAuthenticated;
426 type Input = Empty;
427 type Output = SignOutOutput;
428
429 async fn call(
430 &self,
431 ctx: Ctx<D, MaybeAuthenticated>,
432 _: Empty,
433 ) -> Result<SignOutOutput, AuthError> {
434 if let Some(session) = ctx.session().filter(|s| !s.ephemeral) {
435 ctx.internal()
436 .revoke_session(&session.user.id, &session.session.id)
437 .await?;
438 }
439 ctx.internal().clear_session_cookies();
440 Ok(SignOutOutput { success: true })
441 }
442}
443
444pub struct GetSession;
445
446impl<D: Adapter> Endpoint<D> for GetSession {
447 const METHOD: Method = Method::GET;
448 const PATH: &'static str = "/get-session";
449 type Access = MaybeAuthenticated;
450 type Input = Map<String, Json>;
451 type Output = Option<Json>;
452
453 async fn call(
454 &self,
455 ctx: Ctx<D, MaybeAuthenticated>,
456 _: Map<String, Json>,
457 ) -> Result<Option<Json>, AuthError> {
458 Ok(ctx.session().map(|s| s.to_response_json()))
459 }
460}
461
462pub struct ListSessions;
463
464impl<D: Adapter> Endpoint<D> for ListSessions {
465 const METHOD: Method = Method::GET;
466 const PATH: &'static str = "/list-sessions";
467 type Access = Authenticated;
468 type Input = Map<String, Json>;
469 type Output = Vec<Map<String, Json>>;
470
471 async fn call(
472 &self,
473 ctx: Ctx<D, Authenticated>,
474 _: Map<String, Json>,
475 ) -> Result<Self::Output, AuthError> {
476 let rows = ctx
477 .db()
478 .find::<Session>(
479 Session::USER_ID
480 .eq(&ctx.session().user.id)
481 .and(Session::EXPIRES_AT.gt(ctx.now())),
482 )
483 .order_by(Session::CREATED_AT.desc())
484 .all_rows()
485 .await?;
486 Ok(rows.iter().map(|r| r.to_client_json()).collect())
487 }
488}
489
490pub struct RevokeSession;
491
492#[derive(Debug, Deserialize)]
493pub struct RevokeSessionInput {
494 #[serde(default)]
496 pub token: Option<String>,
497 #[serde(default)]
498 pub id: Option<Id>,
499}
500
501impl<D: Adapter> Endpoint<D> for RevokeSession {
502 const METHOD: Method = Method::POST;
503 const PATH: &'static str = "/revoke-session";
504 type Access = Authenticated;
505 type Input = RevokeSessionInput;
506 type Output = Status;
507
508 async fn call(
509 &self,
510 ctx: Ctx<D, Authenticated>,
511 input: RevokeSessionInput,
512 ) -> Result<Status, AuthError> {
513 let user_id = &ctx.session().user.id;
514 let target = match (input.id, input.token) {
515 (Some(id), _) => Some(id),
516 (None, Some(token)) => ctx
517 .db()
518 .find::<Session>(Session::TOKEN_HASH.eq(crate::crypto::Hash::sha256(token)))
519 .one()
520 .await?
521 .map(|s| s.id),
522 (None, None) => {
523 return Err(AuthError::bad_request(
524 codes::INVALID_BODY,
525 "send `id` or `token`",
526 ));
527 }
528 };
529 let Some(target) = target else {
530 return Err(AuthError::new(
531 StatusCode::NOT_FOUND,
532 codes::SESSION_NOT_FOUND,
533 "session not found",
534 ));
535 };
536 if !ctx.internal().revoke_session(user_id, &target).await? {
537 return Err(AuthError::new(
538 StatusCode::NOT_FOUND,
539 codes::SESSION_NOT_FOUND,
540 "session not found",
541 ));
542 }
543 if target == ctx.session().session.id {
544 ctx.internal().clear_session_cookies();
545 }
546 Ok(OK)
547 }
548}
549
550pub struct RevokeSessions;
551
552impl<D: Adapter> Endpoint<D> for RevokeSessions {
553 const METHOD: Method = Method::POST;
554 const PATH: &'static str = "/revoke-sessions";
555 type Access = Authenticated;
556 type Input = Empty;
557 type Output = Status;
558
559 async fn call(&self, ctx: Ctx<D, Authenticated>, _: Empty) -> Result<Status, AuthError> {
560 ctx.internal()
561 .revoke_user_sessions(&ctx.session().user.id, None)
562 .await?;
563 ctx.internal().clear_session_cookies();
564 Ok(OK)
565 }
566}
567
568pub struct RevokeOtherSessions;
569
570impl<D: Adapter> Endpoint<D> for RevokeOtherSessions {
571 const METHOD: Method = Method::POST;
572 const PATH: &'static str = "/revoke-other-sessions";
573 type Access = Authenticated;
574 type Input = Empty;
575 type Output = Status;
576
577 async fn call(&self, ctx: Ctx<D, Authenticated>, _: Empty) -> Result<Status, AuthError> {
578 let session = ctx.session();
579 ctx.internal()
580 .revoke_user_sessions(&session.user.id, Some(&session.session.id))
581 .await?;
582 Ok(OK)
583 }
584}
585
586pub struct UpdateUser;
589
590#[derive(Debug, Deserialize)]
591pub struct UpdateUserInput {
592 #[serde(default)]
593 pub name: Option<String>,
594 #[serde(default, with = "double_option")]
595 pub image: Option<Option<String>>,
596 #[serde(flatten)]
597 pub extra: Map<String, Json>,
598}
599
600mod double_option {
601 use serde::{Deserialize, Deserializer};
602
603 pub fn deserialize<'de, D: Deserializer<'de>>(
604 d: D,
605 ) -> Result<Option<Option<String>>, D::Error> {
606 Option::<String>::deserialize(d).map(Some)
607 }
608}
609
610impl<D: Adapter> Endpoint<D> for UpdateUser {
611 const METHOD: Method = Method::POST;
612 const PATH: &'static str = "/update-user";
613 type Access = Authenticated;
614 type Input = UpdateUserInput;
615 type Output = Status;
616
617 async fn call(
618 &self,
619 ctx: Ctx<D, Authenticated>,
620 input: UpdateUserInput,
621 ) -> Result<Status, AuthError> {
622 if input.extra.contains_key("email") {
623 return Err(AuthError::bad_request(
624 codes::INVALID_FIELD,
625 "email can't be changed here",
626 ));
627 }
628 let user_id = ctx.session().user.id.clone();
629 let mut update = ctx.db().update::<User>(User::ID.eq(&user_id));
630 if let Some(name) = input.name {
631 update = update.set(User::NAME, name);
632 }
633 if let Some(image) = input.image {
634 update = update.set(User::IMAGE, image);
635 }
636 for (column, value) in user_input_fields(&ctx, &input.extra, false)? {
637 update = update.set_raw(column, value);
638 }
639 update.exec().await?;
640 ctx.emit(UserUpdated { user_id });
641 Ok(OK)
642 }
643}
644
645pub struct ChangePassword;
646
647#[derive(Debug, Deserialize)]
648#[serde(rename_all = "camelCase")]
649pub struct ChangePasswordInput {
650 pub new_password: String,
651 pub current_password: String,
652 #[serde(default)]
653 pub revoke_other_sessions: bool,
654}
655
656#[derive(Debug, Serialize)]
657pub struct ChangePasswordOutput {
658 pub token: Option<String>,
659 pub user: Map<String, Json>,
660}
661
662impl<D: Adapter> Endpoint<D> for ChangePassword {
663 const METHOD: Method = Method::POST;
664 const PATH: &'static str = "/change-password";
665 type Access = Authenticated;
666 type Input = ChangePasswordInput;
667 type Output = ChangePasswordOutput;
668
669 async fn call(
670 &self,
671 ctx: Ctx<D, Authenticated>,
672 input: ChangePasswordInput,
673 ) -> Result<ChangePasswordOutput, AuthError> {
674 let session = ctx.session();
675 let internal = ctx.internal();
676 let Some(hash) = internal
677 .credential_account(&session.user.id)
678 .await?
679 .and_then(|a| a.password_hash)
680 else {
681 return Err(AuthError::bad_request(
682 codes::CREDENTIAL_ACCOUNT_NOT_FOUND,
683 "this user has no password",
684 ));
685 };
686 if !ctx
687 .passwords()
688 .verify(&input.current_password, &hash)
689 .await
690 .map_err(AuthError::internal)?
691 {
692 return Err(AuthError::bad_request(
693 codes::INVALID_PASSWORD,
694 "invalid password",
695 ));
696 }
697 internal
698 .set_password(&session.user.id, &input.new_password)
699 .await?;
700 if input.revoke_other_sessions && !session.ephemeral {
701 internal
702 .revoke_user_sessions(&session.user.id, Some(&session.session.id))
703 .await?;
704 }
705 ctx.emit(PasswordChanged {
706 user_id: session.user.id.clone(),
707 });
708 Ok(ChangePasswordOutput {
709 token: session.token.clone(),
710 user: session.user.to_json(),
711 })
712 }
713}
714
715pub struct SendVerificationEmail;
718
719#[derive(Debug, Deserialize)]
720pub struct SendVerificationEmailInput {
721 pub email: String,
722 #[serde(default, rename = "callbackURL")]
723 pub callback_url: Option<String>,
724}
725
726impl<D: Adapter> Endpoint<D> for SendVerificationEmail {
727 const METHOD: Method = Method::POST;
728 const PATH: &'static str = "/send-verification-email";
729 type Access = Public;
730 type Input = SendVerificationEmailInput;
731 type Output = Status;
732
733 async fn call(
734 &self,
735 ctx: Ctx<D, Public>,
736 input: SendVerificationEmailInput,
737 ) -> Result<Status, AuthError> {
738 check_callback(&ctx, input.callback_url.as_deref())?;
739 let internal = ctx.internal();
740 if let Some(user) = internal
741 .find_user_by_email(&normalize_email(&input.email)?)
742 .await?
743 && !user.email_verified
744 {
745 internal
746 .send_verification_email(&user, input.callback_url.as_deref())
747 .await?;
748 }
749 Ok(OK)
750 }
751}
752
753pub struct VerifyEmail;
754
755#[derive(Debug, Deserialize)]
756pub struct VerifyEmailInput {
757 pub token: String,
758 #[serde(default, rename = "callbackURL")]
759 pub callback_url: Option<String>,
760}
761
762#[derive(Debug, Serialize)]
763pub struct VerifyEmailOutput {
764 pub status: bool,
765 pub user: Option<Map<String, Json>>,
766}
767
768impl<D: Adapter> Endpoint<D> for VerifyEmail {
769 const METHOD: Method = Method::GET;
770 const PATH: &'static str = "/verify-email";
771 type Access = Public;
772 type Input = VerifyEmailInput;
773 type Output = VerifyEmailOutput;
774
775 async fn call(
776 &self,
777 ctx: Ctx<D, Public>,
778 input: VerifyEmailInput,
779 ) -> Result<VerifyEmailOutput, AuthError> {
780 check_callback(&ctx, input.callback_url.as_deref())?;
781 let internal = ctx.internal();
782 let invalid = || AuthError::bad_request(codes::INVALID_TOKEN, "invalid or expired token");
783 let verification = internal.consume_verification(&input.token).await?;
784 let user_id = verification
785 .as_ref()
786 .and_then(|v| v.identifier.strip_prefix("email-verification:"))
787 .map(Id::from);
788 let user = match user_id {
789 Some(id) => internal.find_user_by_id(&id).await?,
790 None => None,
791 };
792 let Some(user) = user else {
793 if let Some(callback) = &input.callback_url {
794 ctx.redirect(with_query(callback, "error", codes::INVALID_TOKEN));
795 return Ok(VerifyEmailOutput {
796 status: false,
797 user: None,
798 });
799 }
800 return Err(invalid());
801 };
802 ctx.db()
803 .update::<User>(User::ID.eq(&user.id))
804 .set(User::EMAIL_VERIFIED, true)
805 .exec()
806 .await?;
807 ctx.emit(EmailVerified {
808 user_id: user.id.clone(),
809 });
810 if ctx
811 .config()
812 .email_verification
813 .auto_sign_in_after_verification
814 {
815 internal
816 .sign_in(user.clone(), "email-verification", true)
817 .await?;
818 }
819 if let Some(callback) = input.callback_url {
820 ctx.redirect(callback);
821 }
822 let user = internal
823 .find_user_by_id(&user.id)
824 .await?
825 .map(|u: UserView| u.to_json());
826 Ok(VerifyEmailOutput { status: true, user })
827 }
828}
829
830pub struct RequestPasswordReset;
833
834#[derive(Debug, Deserialize)]
835#[serde(rename_all = "camelCase")]
836pub struct RequestPasswordResetInput {
837 pub email: String,
838 #[serde(default)]
839 pub redirect_to: Option<String>,
840}
841
842#[derive(Debug, Serialize)]
843pub struct RequestPasswordResetOutput {
844 pub status: bool,
845 pub message: &'static str,
846}
847
848async fn request_reset<D: Adapter>(
849 ctx: &Ctx<D, Public>,
850 input: RequestPasswordResetInput,
851) -> Result<RequestPasswordResetOutput, AuthError> {
852 check_callback(ctx, input.redirect_to.as_deref())?;
853 let internal = ctx.internal();
854 let ttl = email_password(ctx).reset_password_ttl;
855 if let Some(user) = internal
856 .find_user_by_email(&normalize_email(&input.email)?)
857 .await?
858 {
859 let token = internal
860 .create_verification(&format!("reset-password:{}", user.id), ttl, None)
861 .await?;
862 let mut url = format!("{}/reset-password/{token}", ctx.config().auth_url());
863 if let Some(redirect) = &input.redirect_to {
864 url = with_query(&url, "callbackURL", redirect);
865 }
866 internal
867 .send_email(AuthEmail::ResetPassword(ResetPasswordEmail {
868 to: user.email.clone(),
869 name: user.name.clone(),
870 url,
871 token,
872 }))
873 .await?;
874 }
875 Ok(RequestPasswordResetOutput {
876 status: true,
877 message: "If this email exists in our system, check your email for the reset link",
878 })
879}
880
881impl<D: Adapter> Endpoint<D> for RequestPasswordReset {
882 const METHOD: Method = Method::POST;
883 const PATH: &'static str = "/request-password-reset";
884 type Access = Public;
885 type Input = RequestPasswordResetInput;
886 type Output = RequestPasswordResetOutput;
887
888 async fn call(
889 &self,
890 ctx: Ctx<D, Public>,
891 input: RequestPasswordResetInput,
892 ) -> Result<Self::Output, AuthError> {
893 request_reset(&ctx, input).await
894 }
895}
896
897pub struct ForgetPassword;
899
900impl<D: Adapter> Endpoint<D> for ForgetPassword {
901 const METHOD: Method = Method::POST;
902 const PATH: &'static str = "/forget-password";
903 type Access = Public;
904 type Input = RequestPasswordResetInput;
905 type Output = RequestPasswordResetOutput;
906
907 async fn call(
908 &self,
909 ctx: Ctx<D, Public>,
910 input: RequestPasswordResetInput,
911 ) -> Result<Self::Output, AuthError> {
912 request_reset(&ctx, input).await
913 }
914}
915
916pub struct ResetPasswordCallback;
918
919#[derive(Debug, Deserialize)]
920pub struct ResetPasswordCallbackInput {
921 #[serde(default, rename = "callbackURL")]
922 pub callback_url: Option<String>,
923}
924
925impl<D: Adapter> Endpoint<D> for ResetPasswordCallback {
926 const METHOD: Method = Method::GET;
927 const PATH: &'static str = "/reset-password/{token}";
928 type Access = Public;
929 type Input = ResetPasswordCallbackInput;
930 type Output = Status;
931
932 async fn call(
933 &self,
934 ctx: Ctx<D, Public>,
935 input: ResetPasswordCallbackInput,
936 ) -> Result<Status, AuthError> {
937 let Some(callback) = input.callback_url else {
938 return Err(AuthError::bad_request(
939 codes::INVALID_CALLBACK_URL,
940 "callbackURL is required",
941 ));
942 };
943 check_callback(&ctx, Some(&callback))?;
944 let token = ctx.param("token").unwrap_or_default().to_owned();
945 let valid = ctx
946 .internal()
947 .find_verification(&token)
948 .await?
949 .is_some_and(|v| v.identifier.starts_with("reset-password:"));
950 ctx.redirect(if valid {
951 with_query(&callback, "token", &token)
952 } else {
953 with_query(&callback, "error", codes::INVALID_TOKEN)
954 });
955 Ok(Status { status: valid })
956 }
957}
958
959pub struct ResetPassword;
960
961#[derive(Debug, Deserialize)]
962#[serde(rename_all = "camelCase")]
963pub struct ResetPasswordInput {
964 pub new_password: String,
965 pub token: String,
966}
967
968impl<D: Adapter> Endpoint<D> for ResetPassword {
969 const METHOD: Method = Method::POST;
970 const PATH: &'static str = "/reset-password";
971 type Access = Public;
972 type Input = ResetPasswordInput;
973 type Output = Status;
974
975 async fn call(
976 &self,
977 ctx: Ctx<D, Public>,
978 input: ResetPasswordInput,
979 ) -> Result<Status, AuthError> {
980 let internal = ctx.internal();
981 internal.validate_new_password(&input.new_password)?;
982 let user_id = internal
983 .consume_verification(&input.token)
984 .await?
985 .and_then(|v| v.identifier.strip_prefix("reset-password:").map(Id::from))
986 .ok_or_else(|| {
987 AuthError::bad_request(codes::INVALID_TOKEN, "invalid or expired token")
988 })?;
989 internal.set_password(&user_id, &input.new_password).await?;
990 if email_password(&ctx).revoke_sessions_on_password_reset {
991 internal.revoke_user_sessions(&user_id, None).await?;
992 }
993 ctx.emit(PasswordChanged { user_id });
994 Ok(OK)
995 }
996}