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