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