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::{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.id, &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>(Session::TOKEN_HASH.eq(crate::crypto::Hash::sha256(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_id = ctx.session().user.id.clone();
670        let mut update = ctx.db().update::<User>(User::ID.eq(&user_id));
671        if let Some(name) = input.name {
672            update = update.set(User::NAME, name);
673        }
674        if let Some(image) = input.image {
675            update = update.set(User::IMAGE, image);
676        }
677        for (column, value) in ctx
678            .internal()
679            .user_fields(&input.extra, UserInput::Update)
680            .await?
681        {
682            update = update.set_raw(column, value);
683        }
684        update.exec().await?;
685        ctx.emit(UserUpdated { user_id });
686        Ok(OK)
687    }
688}
689
690pub struct ChangePassword;
691
692#[derive(Debug, Deserialize)]
693#[serde(rename_all = "camelCase")]
694pub struct ChangePasswordInput {
695    pub new_password: String,
696    pub current_password: String,
697    #[serde(default)]
698    pub revoke_other_sessions: bool,
699}
700
701#[derive(Debug, Serialize)]
702pub struct ChangePasswordOutput {
703    pub token: Option<String>,
704    pub user: Map<String, Json>,
705}
706
707impl<D: Adapter> Endpoint<D> for ChangePassword {
708    const METHOD: Method = Method::POST;
709    const PATH: &'static str = "/change-password";
710    type Access = Authenticated;
711    type Input = ChangePasswordInput;
712    type Output = ChangePasswordOutput;
713
714    async fn call(
715        &self,
716        ctx: Ctx<D, Authenticated>,
717        input: ChangePasswordInput,
718    ) -> Result<ChangePasswordOutput, AuthError> {
719        let session = &ctx.sensitive_session().await?;
720        let internal = ctx.internal();
721        let Some(hash) = internal
722            .credential_account(&session.user.id)
723            .await?
724            .and_then(|a| a.password_hash)
725        else {
726            return Err(AuthError::bad_request(
727                codes::CREDENTIAL_ACCOUNT_NOT_FOUND,
728                "this user has no password",
729            ));
730        };
731        if !ctx
732            .passwords()
733            .verify(&input.current_password, &hash)
734            .await
735            .map_err(AuthError::internal)?
736        {
737            return Err(AuthError::bad_request(
738                codes::INVALID_PASSWORD,
739                "invalid password",
740            ));
741        }
742        internal
743            .set_password(&session.user.id, &input.new_password)
744            .await?;
745        if input.revoke_other_sessions && !session.ephemeral {
746            internal
747                .revoke_user_sessions(&session.user.id, Some(&session.session.id))
748                .await?;
749        }
750        ctx.emit(PasswordChanged {
751            user_id: session.user.id.clone(),
752        });
753        Ok(ChangePasswordOutput {
754            token: session.token.clone(),
755            user: session.user.to_json(),
756        })
757    }
758}
759
760// ---------------------------------------------------------------------------- email verification
761
762pub struct SendVerificationEmail;
763
764#[derive(Debug, Deserialize)]
765pub struct SendVerificationEmailInput {
766    pub email: String,
767    #[serde(default, rename = "callbackURL")]
768    pub callback_url: Option<String>,
769}
770
771impl<D: Adapter> Endpoint<D> for SendVerificationEmail {
772    const METHOD: Method = Method::POST;
773    const PATH: &'static str = "/send-verification-email";
774    type Access = Public;
775    type Input = SendVerificationEmailInput;
776    type Output = Status;
777
778    async fn call(
779        &self,
780        ctx: Ctx<D, Public>,
781        input: SendVerificationEmailInput,
782    ) -> Result<Status, AuthError> {
783        check_callback(&ctx, input.callback_url.as_deref())?;
784        let internal = ctx.internal();
785        if let Some(user) = internal
786            .find_user_by_email(&normalize_email(&input.email)?)
787            .await?
788            && !user.email_verified
789        {
790            internal
791                .send_verification_email(&user, input.callback_url.as_deref())
792                .await?;
793        } else {
794            internal.simulate_verification().await?;
795        }
796        Ok(OK)
797    }
798}
799
800pub struct VerifyEmail;
801
802#[derive(Debug, Deserialize)]
803pub struct VerifyEmailInput {
804    pub token: String,
805    #[serde(default, rename = "callbackURL")]
806    pub callback_url: Option<String>,
807}
808
809#[derive(Debug, Serialize)]
810pub struct VerifyEmailOutput {
811    pub status: bool,
812    pub user: Option<Map<String, Json>>,
813}
814
815impl<D: Adapter> Endpoint<D> for VerifyEmail {
816    const METHOD: Method = Method::GET;
817    const PATH: &'static str = "/verify-email";
818    type Access = Public;
819    type Input = VerifyEmailInput;
820    type Output = VerifyEmailOutput;
821
822    async fn call(
823        &self,
824        ctx: Ctx<D, Public>,
825        input: VerifyEmailInput,
826    ) -> Result<VerifyEmailOutput, AuthError> {
827        check_callback(&ctx, input.callback_url.as_deref())?;
828        let internal = ctx.internal();
829        let invalid = || AuthError::bad_request(codes::INVALID_TOKEN, "invalid or expired token");
830        let user = internal
831            .consume_user_verification("email-verification", &input.token)
832            .await?;
833        let Some(user) = user else {
834            if let Some(callback) = &input.callback_url {
835                ctx.redirect(with_query(callback, "error", codes::INVALID_TOKEN));
836                return Ok(VerifyEmailOutput {
837                    status: false,
838                    user: None,
839                });
840            }
841            return Err(invalid());
842        };
843        let user = internal.prove_email(user).await?;
844        if ctx
845            .config()
846            .email_verification
847            .auto_sign_in_after_verification
848        {
849            internal
850                .sign_in(user.clone(), "email-verification", true)
851                .await?;
852        }
853        if let Some(callback) = input.callback_url {
854            ctx.redirect(callback);
855        }
856        let user = internal
857            .find_user_by_id(&user.id)
858            .await?
859            .map(|u: UserView| u.to_json());
860        Ok(VerifyEmailOutput { status: true, user })
861    }
862}
863
864// ---------------------------------------------------------------------------- password reset
865
866pub struct RequestPasswordReset;
867
868#[derive(Debug, Deserialize)]
869#[serde(rename_all = "camelCase")]
870pub struct RequestPasswordResetInput {
871    pub email: String,
872    #[serde(default)]
873    pub redirect_to: Option<String>,
874}
875
876#[derive(Debug, Serialize)]
877pub struct RequestPasswordResetOutput {
878    pub status: bool,
879    pub message: &'static str,
880}
881
882async fn request_reset<D: Adapter>(
883    ctx: &Ctx<D, Public>,
884    input: RequestPasswordResetInput,
885) -> Result<RequestPasswordResetOutput, AuthError> {
886    check_callback(ctx, input.redirect_to.as_deref())?;
887    let internal = ctx.internal();
888    let ttl = email_password(ctx).reset_password_ttl;
889    if let Some(user) = internal
890        .find_user_by_email(&normalize_email(&input.email)?)
891        .await?
892    {
893        let token = internal
894            .create_user_verification("reset-password", &user, ttl)
895            .await?;
896        let mut url = format!("{}/reset-password/{token}", ctx.config().auth_url());
897        if let Some(redirect) = &input.redirect_to {
898            url = with_query(&url, "callbackURL", redirect);
899        }
900        internal
901            .send_email_in_background(AuthEmail::ResetPassword(ResetPasswordEmail {
902                to: user.email.clone(),
903                name: user.name.clone(),
904                url,
905                token,
906            }))
907            .await?;
908    } else {
909        internal.simulate_verification().await?;
910    }
911    Ok(RequestPasswordResetOutput {
912        status: true,
913        message: "If this email exists in our system, check your email for the reset link",
914    })
915}
916
917impl<D: Adapter> Endpoint<D> for RequestPasswordReset {
918    const METHOD: Method = Method::POST;
919    const PATH: &'static str = "/request-password-reset";
920    type Access = Public;
921    type Input = RequestPasswordResetInput;
922    type Output = RequestPasswordResetOutput;
923
924    async fn call(
925        &self,
926        ctx: Ctx<D, Public>,
927        input: RequestPasswordResetInput,
928    ) -> Result<Self::Output, AuthError> {
929        request_reset(&ctx, input).await
930    }
931}
932
933/// The older Better Auth name for `/request-password-reset`.
934pub struct ForgetPassword;
935
936impl<D: Adapter> Endpoint<D> for ForgetPassword {
937    const METHOD: Method = Method::POST;
938    const PATH: &'static str = "/forget-password";
939    type Access = Public;
940    type Input = RequestPasswordResetInput;
941    type Output = RequestPasswordResetOutput;
942
943    async fn call(
944        &self,
945        ctx: Ctx<D, Public>,
946        input: RequestPasswordResetInput,
947    ) -> Result<Self::Output, AuthError> {
948        request_reset(&ctx, input).await
949    }
950}
951
952/// The link in the reset email. Redirects to the app's reset page with the token.
953pub struct ResetPasswordCallback;
954
955#[derive(Debug, Deserialize)]
956pub struct ResetPasswordCallbackInput {
957    #[serde(default, rename = "callbackURL")]
958    pub callback_url: Option<String>,
959}
960
961impl<D: Adapter> Endpoint<D> for ResetPasswordCallback {
962    const METHOD: Method = Method::GET;
963    const PATH: &'static str = "/reset-password/{token}";
964    type Access = Public;
965    type Input = ResetPasswordCallbackInput;
966    type Output = Status;
967
968    async fn call(
969        &self,
970        ctx: Ctx<D, Public>,
971        input: ResetPasswordCallbackInput,
972    ) -> Result<Status, AuthError> {
973        let Some(callback) = input.callback_url else {
974            return Err(AuthError::bad_request(
975                codes::INVALID_CALLBACK_URL,
976                "callbackURL is required",
977            ));
978        };
979        check_callback(&ctx, Some(&callback))?;
980        let token = ctx.param("token").unwrap_or_default().to_owned();
981        let valid = ctx
982            .internal()
983            .find_verification(&token)
984            .await?
985            .is_some_and(|v| v.identifier.starts_with("reset-password:"));
986        ctx.redirect(if valid {
987            with_query(&callback, "token", &token)
988        } else {
989            with_query(&callback, "error", codes::INVALID_TOKEN)
990        });
991        Ok(Status { status: valid })
992    }
993}
994
995pub struct ResetPassword;
996
997#[derive(Debug, Deserialize)]
998#[serde(rename_all = "camelCase")]
999pub struct ResetPasswordInput {
1000    pub new_password: String,
1001    pub token: String,
1002}
1003
1004impl<D: Adapter> Endpoint<D> for ResetPassword {
1005    const METHOD: Method = Method::POST;
1006    const PATH: &'static str = "/reset-password";
1007    type Access = Public;
1008    type Input = ResetPasswordInput;
1009    type Output = Status;
1010
1011    async fn call(
1012        &self,
1013        ctx: Ctx<D, Public>,
1014        input: ResetPasswordInput,
1015    ) -> Result<Status, AuthError> {
1016        let internal = ctx.internal();
1017        internal.validate_new_password(&input.new_password)?;
1018        let user = internal
1019            .consume_user_verification("reset-password", &input.token)
1020            .await?
1021            .ok_or_else(|| {
1022                AuthError::bad_request(codes::INVALID_TOKEN, "invalid or expired token")
1023            })?;
1024        // The link was mailed to the address, so it proves the mailbox like a magic link.
1025        let user_id = internal.claim_user(user, None).await?.id.clone();
1026        internal.set_password(&user_id, &input.new_password).await?;
1027        if email_password(&ctx).revoke_sessions_on_password_reset {
1028            internal.revoke_user_sessions(&user_id, None).await?;
1029        }
1030        ctx.emit(PasswordChanged { user_id });
1031        Ok(OK)
1032    }
1033}