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
64/// Trims and lowercases an email, answering 400 `INVALID_EMAIL` when it isn't one. Every
65/// email route normalizes this way, so plugins that take an email should too.
66pub 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
81/// Turns extra JSON body keys into user columns, as sign-up does. Only app and plugin `input`
82/// columns are accepted; with `require_all`, every required one without a default must be
83/// there. Answers 400 `INVALID_FIELD` otherwise.
84pub 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
133// ---------------------------------------------------------------------------- sign-up
134
135pub 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    /// App and plugin `input` columns, by camelCase name.
150    #[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            // Answer as if it worked, so sign-up can't be used to discover accounts.
182            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
245// ---------------------------------------------------------------------------- create-user
246
247/// Server-only: `auth.api().create_user(..)`. Never registered as a route, but hooks
248/// can target it.
249pub 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    /// Creates a credential account with this password. `None` creates the user alone.
257    #[serde(default)]
258    pub password: Option<String>,
259    /// App and plugin `input` columns, by camelCase name, as on sign-up.
260    #[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
301// ---------------------------------------------------------------------------- sign-in
302
303pub 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    /// A sign-in gate's answer, e.g. `{"twoFactorRedirect": true}`.
326    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
419// ---------------------------------------------------------------------------- sessions
420
421pub 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    /// Better Auth clients send the token; it is hashed to find the session.
501    #[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
592// ---------------------------------------------------------------------------- user
593
594pub 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
721// ---------------------------------------------------------------------------- email verification
722
723pub 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        }
755        Ok(OK)
756    }
757}
758
759pub struct VerifyEmail;
760
761#[derive(Debug, Deserialize)]
762pub struct VerifyEmailInput {
763    pub token: String,
764    #[serde(default, rename = "callbackURL")]
765    pub callback_url: Option<String>,
766}
767
768#[derive(Debug, Serialize)]
769pub struct VerifyEmailOutput {
770    pub status: bool,
771    pub user: Option<Map<String, Json>>,
772}
773
774impl<D: Adapter> Endpoint<D> for VerifyEmail {
775    const METHOD: Method = Method::GET;
776    const PATH: &'static str = "/verify-email";
777    type Access = Public;
778    type Input = VerifyEmailInput;
779    type Output = VerifyEmailOutput;
780
781    async fn call(
782        &self,
783        ctx: Ctx<D, Public>,
784        input: VerifyEmailInput,
785    ) -> Result<VerifyEmailOutput, AuthError> {
786        check_callback(&ctx, input.callback_url.as_deref())?;
787        let internal = ctx.internal();
788        let invalid = || AuthError::bad_request(codes::INVALID_TOKEN, "invalid or expired token");
789        let verification = internal.consume_verification(&input.token).await?;
790        let user_id = verification
791            .as_ref()
792            .and_then(|v| v.identifier.strip_prefix("email-verification:"))
793            .map(Id::from);
794        let user = match user_id {
795            Some(id) => internal.find_user_by_id(&id).await?,
796            None => None,
797        };
798        let Some(user) = user else {
799            if let Some(callback) = &input.callback_url {
800                ctx.redirect(with_query(callback, "error", codes::INVALID_TOKEN));
801                return Ok(VerifyEmailOutput {
802                    status: false,
803                    user: None,
804                });
805            }
806            return Err(invalid());
807        };
808        ctx.db()
809            .update::<User>(User::ID.eq(&user.id))
810            .set(User::EMAIL_VERIFIED, true)
811            .exec()
812            .await?;
813        ctx.emit(EmailVerified {
814            user_id: user.id.clone(),
815        });
816        if ctx
817            .config()
818            .email_verification
819            .auto_sign_in_after_verification
820        {
821            internal
822                .sign_in(user.clone(), "email-verification", true)
823                .await?;
824        }
825        if let Some(callback) = input.callback_url {
826            ctx.redirect(callback);
827        }
828        let user = internal
829            .find_user_by_id(&user.id)
830            .await?
831            .map(|u: UserView| u.to_json());
832        Ok(VerifyEmailOutput { status: true, user })
833    }
834}
835
836// ---------------------------------------------------------------------------- password reset
837
838pub struct RequestPasswordReset;
839
840#[derive(Debug, Deserialize)]
841#[serde(rename_all = "camelCase")]
842pub struct RequestPasswordResetInput {
843    pub email: String,
844    #[serde(default)]
845    pub redirect_to: Option<String>,
846}
847
848#[derive(Debug, Serialize)]
849pub struct RequestPasswordResetOutput {
850    pub status: bool,
851    pub message: &'static str,
852}
853
854async fn request_reset<D: Adapter>(
855    ctx: &Ctx<D, Public>,
856    input: RequestPasswordResetInput,
857) -> Result<RequestPasswordResetOutput, AuthError> {
858    check_callback(ctx, input.redirect_to.as_deref())?;
859    let internal = ctx.internal();
860    let ttl = email_password(ctx).reset_password_ttl;
861    if let Some(user) = internal
862        .find_user_by_email(&normalize_email(&input.email)?)
863        .await?
864    {
865        let token = internal
866            .create_verification(&format!("reset-password:{}", user.id), ttl, None)
867            .await?;
868        let mut url = format!("{}/reset-password/{token}", ctx.config().auth_url());
869        if let Some(redirect) = &input.redirect_to {
870            url = with_query(&url, "callbackURL", redirect);
871        }
872        internal
873            .send_email(AuthEmail::ResetPassword(ResetPasswordEmail {
874                to: user.email.clone(),
875                name: user.name.clone(),
876                url,
877                token,
878            }))
879            .await?;
880    }
881    Ok(RequestPasswordResetOutput {
882        status: true,
883        message: "If this email exists in our system, check your email for the reset link",
884    })
885}
886
887impl<D: Adapter> Endpoint<D> for RequestPasswordReset {
888    const METHOD: Method = Method::POST;
889    const PATH: &'static str = "/request-password-reset";
890    type Access = Public;
891    type Input = RequestPasswordResetInput;
892    type Output = RequestPasswordResetOutput;
893
894    async fn call(
895        &self,
896        ctx: Ctx<D, Public>,
897        input: RequestPasswordResetInput,
898    ) -> Result<Self::Output, AuthError> {
899        request_reset(&ctx, input).await
900    }
901}
902
903/// The older Better Auth name for `/request-password-reset`.
904pub struct ForgetPassword;
905
906impl<D: Adapter> Endpoint<D> for ForgetPassword {
907    const METHOD: Method = Method::POST;
908    const PATH: &'static str = "/forget-password";
909    type Access = Public;
910    type Input = RequestPasswordResetInput;
911    type Output = RequestPasswordResetOutput;
912
913    async fn call(
914        &self,
915        ctx: Ctx<D, Public>,
916        input: RequestPasswordResetInput,
917    ) -> Result<Self::Output, AuthError> {
918        request_reset(&ctx, input).await
919    }
920}
921
922/// The link in the reset email. Redirects to the app's reset page with the token.
923pub struct ResetPasswordCallback;
924
925#[derive(Debug, Deserialize)]
926pub struct ResetPasswordCallbackInput {
927    #[serde(default, rename = "callbackURL")]
928    pub callback_url: Option<String>,
929}
930
931impl<D: Adapter> Endpoint<D> for ResetPasswordCallback {
932    const METHOD: Method = Method::GET;
933    const PATH: &'static str = "/reset-password/{token}";
934    type Access = Public;
935    type Input = ResetPasswordCallbackInput;
936    type Output = Status;
937
938    async fn call(
939        &self,
940        ctx: Ctx<D, Public>,
941        input: ResetPasswordCallbackInput,
942    ) -> Result<Status, AuthError> {
943        let Some(callback) = input.callback_url else {
944            return Err(AuthError::bad_request(
945                codes::INVALID_CALLBACK_URL,
946                "callbackURL is required",
947            ));
948        };
949        check_callback(&ctx, Some(&callback))?;
950        let token = ctx.param("token").unwrap_or_default().to_owned();
951        let valid = ctx
952            .internal()
953            .find_verification(&token)
954            .await?
955            .is_some_and(|v| v.identifier.starts_with("reset-password:"));
956        ctx.redirect(if valid {
957            with_query(&callback, "token", &token)
958        } else {
959            with_query(&callback, "error", codes::INVALID_TOKEN)
960        });
961        Ok(Status { status: valid })
962    }
963}
964
965pub struct ResetPassword;
966
967#[derive(Debug, Deserialize)]
968#[serde(rename_all = "camelCase")]
969pub struct ResetPasswordInput {
970    pub new_password: String,
971    pub token: String,
972}
973
974impl<D: Adapter> Endpoint<D> for ResetPassword {
975    const METHOD: Method = Method::POST;
976    const PATH: &'static str = "/reset-password";
977    type Access = Public;
978    type Input = ResetPasswordInput;
979    type Output = Status;
980
981    async fn call(
982        &self,
983        ctx: Ctx<D, Public>,
984        input: ResetPasswordInput,
985    ) -> Result<Status, AuthError> {
986        let internal = ctx.internal();
987        internal.validate_new_password(&input.new_password)?;
988        let user_id = internal
989            .consume_verification(&input.token)
990            .await?
991            .and_then(|v| v.identifier.strip_prefix("reset-password:").map(Id::from))
992            .ok_or_else(|| {
993                AuthError::bad_request(codes::INVALID_TOKEN, "invalid or expired token")
994            })?;
995        internal.set_password(&user_id, &input.new_password).await?;
996        if email_password(&ctx).revoke_sessions_on_password_reset {
997            internal.revoke_user_sessions(&user_id, None).await?;
998        }
999        ctx.emit(PasswordChanged { user_id });
1000        Ok(OK)
1001    }
1002}