Skip to main content

fastauth_core/
routes.rs

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