Skip to main content

fastauth_core/
internal.rs

1//! Core operations shared by core endpoints and plugins: users, accounts, sessions,
2//! sign-in with gates, verification values, email.
3
4use std::any::Any;
5use std::borrow::Cow;
6use std::marker::PhantomData;
7
8use http::StatusCode;
9use time::{Duration, OffsetDateTime};
10
11use crate::adapter::{Adapter, DbError, Transaction, Update};
12use crate::crypto::{Hash, random_bytes, random_token};
13use crate::endpoint::{Ctx, Gate, SignInAttempt};
14use crate::error::{AuthError, codes};
15use crate::events::{
16    AccountLinked, EmailVerified, SessionCreated, SessionRevoked, UserClaimed, UserCreated,
17};
18use crate::mail::{AuthEmail, VerifyEmail};
19use crate::model::{Col, Model, OnTable};
20use crate::models::{Account, Session, User, Verification};
21use crate::query::Db;
22use crate::schema::Schema;
23use crate::session::{
24    SESSION_DATA, SessionView, UserView, clear_session_cookies, set_session_cookies,
25};
26use crate::value::{ColumnValue, Id, Value};
27
28/// A user to create.
29#[derive(Clone, Debug, Default)]
30pub struct NewUser {
31    pub email: String,
32    pub name: String,
33    pub image: Option<String>,
34    pub email_verified: bool,
35    /// App and plugin columns, already validated.
36    pub extra: Vec<(&'static str, Value)>,
37}
38
39/// An account to create with a user or link to one.
40#[derive(Clone, Debug, Default)]
41pub struct NewAccount {
42    pub provider_id: String,
43    /// Defaults to the user id (what the credential account uses).
44    pub account_id: Option<String>,
45    pub password_hash: Option<String>,
46    /// Plaintext; encrypted before it is stored.
47    pub access_token: Option<String>,
48    /// Plaintext; encrypted before it is stored.
49    pub refresh_token: Option<String>,
50    pub id_token: Option<String>,
51    pub access_token_expires_at: Option<OffsetDateTime>,
52    pub refresh_token_expires_at: Option<OffsetDateTime>,
53    pub scope: Option<String>,
54}
55
56/// What [`Internal::create_session_with`] stores beyond a default session: a different expiry
57/// and plugin columns, written in the same insert.
58#[derive(Clone, Debug, Default)]
59pub struct NewSession {
60    expires_at: Option<OffsetDateTime>,
61    values: Vec<(&'static str, Value)>,
62}
63
64impl NewSession {
65    pub fn new() -> Self {
66        Self::default()
67    }
68
69    /// Replaces the expiry `remember_me` and the session config give.
70    pub fn expires_at(mut self, expires_at: OffsetDateTime) -> Self {
71        self.expires_at = Some(expires_at);
72        self
73    }
74
75    /// Sets a plugin's or the app's session column.
76    pub fn set<O: OnTable<Table = Session>, T: ColumnValue>(
77        mut self,
78        column: Col<O, T>,
79        value: impl Into<T>,
80    ) -> Self {
81        self.values.push((column.name(), value.into().into_value()));
82        self
83    }
84}
85
86/// How long a `rememberMe: false` session lives at most, as in Better Auth.
87const DONT_REMEMBER_LIFETIME: Duration = Duration::days(1);
88
89impl NewAccount {
90    pub fn credential(password_hash: String) -> Self {
91        Self {
92            provider_id: Account::CREDENTIAL.into(),
93            password_hash: Some(password_hash),
94            ..Self::default()
95        }
96    }
97
98    pub fn oauth(provider_id: impl Into<String>, account_id: impl Into<String>) -> Self {
99        Self {
100            provider_id: provider_id.into(),
101            account_id: Some(account_id.into()),
102            ..Self::default()
103        }
104    }
105}
106
107/// Which user write [`Internal::user_fields`] reads client input for.
108#[derive(Clone, Copy, Debug, PartialEq, Eq)]
109pub enum UserInput {
110    /// A client creating their own user: `/sign-up/email`, or an email code that signs up.
111    SignUp,
112    /// The server creating a user (`auth.api().create_user(..)`).
113    Create,
114    /// `/update-user`, for the signed-in user.
115    Update,
116}
117
118#[derive(Clone, Debug)]
119pub enum SignInResult {
120    SignedIn(Box<SessionView>),
121    /// A gate wants more (e.g. a TOTP code). Respond with this JSON; no session exists.
122    Challenge(serde_json::Value),
123}
124
125fn user_exists(err: DbError) -> AuthError {
126    match err {
127        DbError::UniqueViolation { ref table, .. } if table == User::TABLE => AuthError::new(
128            StatusCode::UNPROCESSABLE_ENTITY,
129            codes::USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL,
130            "user already exists, use another email",
131        ),
132        other => other.into(),
133    }
134}
135
136fn account_linked(err: DbError) -> AuthError {
137    match err {
138        DbError::UniqueViolation {
139            ref table,
140            column: None,
141        } if table == Account::TABLE => AuthError::new(
142            StatusCode::CONFLICT,
143            codes::SOCIAL_ACCOUNT_ALREADY_LINKED,
144            "social account already linked",
145        ),
146        other => other.into(),
147    }
148}
149
150/// The cookie that marks the browser which set or proved an unverified user's password.
151const PENDING_VERIFICATION: &str = "pending_verification";
152
153/// A fresh random security stamp.
154fn new_security_stamp() -> i64 {
155    i64::from_le_bytes(random_bytes::<8>())
156}
157
158pub(crate) fn url_encode(value: &str) -> String {
159    url::form_urlencoded::byte_serialize(value.as_bytes()).collect()
160}
161
162/// A sign-in or link that started before proof of the email claimed the user.
163fn claimed_meanwhile() -> AuthError {
164    AuthError::new(
165        StatusCode::UNAUTHORIZED,
166        codes::UNAUTHORIZED,
167        "the account changed while signing in; sign in again",
168    )
169}
170
171/// What a claim cleanup registered with
172/// [`PluginBuilder::on_claim`](crate::plugin::PluginBuilder::on_claim) gets: the claimed
173/// user and the claim's transaction. Every query on [`db`](Self::db) commits or rolls back
174/// with the claim.
175pub struct Claim<'a, D> {
176    user_id: &'a Id,
177    tx: &'a (dyn Any + Send + Sync),
178    schema: &'a Schema,
179    _adapter: PhantomData<fn() -> D>,
180}
181
182impl<'a, D: Adapter> Claim<'a, D> {
183    /// The user that was claimed. Its email is verified now.
184    pub fn user_id(&self) -> &'a Id {
185        self.user_id
186    }
187
188    /// Typed queries inside the claim's transaction.
189    pub fn db(&self) -> Db<'a, D::Tx> {
190        let tx = self
191            .tx
192            .downcast_ref::<D::Tx>()
193            .expect("a claim runs in its adapter's transaction");
194        Db::new(tx, self.schema)
195    }
196}
197
198impl<D> std::fmt::Debug for Claim<'_, D> {
199    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
200        f.debug_struct("Claim")
201            .field("user_id", self.user_id)
202            .finish_non_exhaustive()
203    }
204}
205
206/// The verification identifiers core keeps per user, which a claim retires.
207fn user_verification_identifiers(user_id: &Id) -> [String; 2] {
208    [
209        format!("email-verification:{user_id}"),
210        format!("reset-password:{user_id}"),
211    ]
212}
213
214/// What a token bound to a user carries: the user's security stamp and email when it was
215/// minted, so a claim or a change of email retires it.
216fn user_binding(user: &UserView) -> String {
217    format!("{}:{}", user.security_stamp(), user.email)
218}
219
220pub struct Internal<'a, D, A> {
221    ctx: &'a Ctx<D, A>,
222}
223
224impl<'a, D: Adapter, A> Internal<'a, D, A> {
225    pub(crate) fn new(ctx: &'a Ctx<D, A>) -> Self {
226        Self { ctx }
227    }
228
229    pub async fn find_user_by_email(&self, email: &str) -> Result<Option<UserView>, AuthError> {
230        let row = self
231            .ctx
232            .db()
233            .find::<User>(User::EMAIL.eq(email.trim().to_lowercase()))
234            .one_row()
235            .await?;
236        row.map(UserView::from_row)
237            .transpose()
238            .map_err(AuthError::internal)
239    }
240
241    pub async fn find_user_by_id(&self, id: &Id) -> Result<Option<UserView>, AuthError> {
242        let row = self
243            .ctx
244            .db()
245            .find::<User>(User::ID.eq(id))
246            .one_row()
247            .await?;
248        row.map(UserView::from_row)
249            .transpose()
250            .map_err(AuthError::internal)
251    }
252
253    fn account_values(
254        &self,
255        user_id: &Id,
256        account: NewAccount,
257    ) -> Result<Vec<(&'static str, Value)>, AuthError> {
258        let keys = self.ctx.keys();
259        let seal = |t: Option<String>| t.map(|t| keys.encrypt(t.as_bytes()));
260        Ok(vec![
261            ("id", self.ctx.new_id()?.into_value()),
262            ("user_id", user_id.clone().into_value()),
263            ("provider_id", account.provider_id.into_value()),
264            (
265                "account_id",
266                account
267                    .account_id
268                    .unwrap_or_else(|| user_id.to_string())
269                    .into_value(),
270            ),
271            ("password_hash", account.password_hash.into_value()),
272            ("access_token", seal(account.access_token).into_value()),
273            ("refresh_token", seal(account.refresh_token).into_value()),
274            ("id_token", account.id_token.into_value()),
275            (
276                "access_token_expires_at",
277                account.access_token_expires_at.into_value(),
278            ),
279            (
280                "refresh_token_expires_at",
281                account.refresh_token_expires_at.into_value(),
282            ),
283            ("scope", account.scope.into_value()),
284        ])
285    }
286
287    /// Creates a user (and optionally its first account) in one transaction.
288    /// Answers `USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL` (422) when the email is taken.
289    pub async fn create_user(
290        &self,
291        user: NewUser,
292        account: Option<NewAccount>,
293    ) -> Result<UserView, AuthError> {
294        let id = self.ctx.new_id()?;
295        let mut values = vec![
296            ("id", id.clone().into_value()),
297            ("email", user.email.trim().to_lowercase().into_value()),
298            ("email_verified", user.email_verified.into_value()),
299            ("name", user.name.into_value()),
300            ("image", user.image.into_value()),
301        ];
302        values.extend(user.extra);
303        let account = account
304            .map(|account| self.account_values(&id, account))
305            .transpose()?;
306        let tx = self.ctx.adapter().begin().await?;
307        let db = self.ctx.db_on(&tx);
308        let row = db.insert_row::<User>(values).await.map_err(user_exists)?;
309        if let Some(account) = account {
310            db.insert_row::<Account>(account)
311                .await
312                .map_err(account_linked)?;
313        }
314        tx.commit().await?;
315        let view = UserView::from_row(row).map_err(AuthError::internal)?;
316        self.ctx.emit(UserCreated {
317            user_id: view.id.clone(),
318            email: view.email.clone(),
319        });
320        Ok(view)
321    }
322
323    pub async fn link_account(
324        &self,
325        user_id: &Id,
326        account: NewAccount,
327    ) -> Result<Account, AuthError> {
328        let provider_id = account.provider_id.clone();
329        let row = self
330            .ctx
331            .db()
332            .insert_row::<Account>(self.account_values(user_id, account)?)
333            .await
334            .map_err(account_linked)?;
335        self.ctx.emit(AccountLinked {
336            user_id: user_id.clone(),
337            provider_id,
338        });
339        Account::decode(&row).map_err(AuthError::internal)
340    }
341
342    /// Links an account like [`link_account`](Self::link_account), unless proof of the email
343    /// claimed the user after `user` was read: then the account is removed again and the call
344    /// answers 401. For links that a session or an earlier request started, such as linking
345    /// a social account, so a link the previous holder started can't land on a claimed user.
346    pub async fn link_account_unless_claimed(
347        &self,
348        user: &UserView,
349        account: NewAccount,
350    ) -> Result<Account, AuthError> {
351        let provider_id = account.provider_id.clone();
352        let row = self
353            .ctx
354            .db()
355            .insert_row::<Account>(self.account_values(&user.id, account)?)
356            .await
357            .map_err(account_linked)?;
358        let linked = Account::decode(&row).map_err(AuthError::internal)?;
359        if !self.stamp_holds(&user.id, user.security_stamp()).await? {
360            self.ctx
361                .db()
362                .delete::<Account>(Account::ID.eq(&linked.id))
363                .await?;
364            return Err(claimed_meanwhile());
365        }
366        self.ctx.emit(AccountLinked {
367            user_id: user.id.clone(),
368            provider_id,
369        });
370        Ok(linked)
371    }
372
373    /// Whether `user_id`'s security stamp still is `stamp`. A locking no-op write, so it waits
374    /// for a claim in progress and then sees its stamp: anything inserted before this check
375    /// and after a claim began is either deleted by the claim or refused here.
376    async fn stamp_holds(&self, user_id: &Id, stamp: i64) -> Result<bool, AuthError> {
377        let table = self.ctx.schema().expect(User::TABLE);
378        let filter = User::ID
379            .eq(user_id)
380            .and(User::SECURITY_STAMP.eq(stamp))
381            .resolve(table)?;
382        let column = table
383            .position(User::SECURITY_STAMP.name())
384            .ok_or_else(|| AuthError::internal("user.security_stamp missing"))?;
385        let matched = self
386            .ctx
387            .adapter()
388            .update(Update {
389                table,
390                filter,
391                set: vec![(column, Value::Int(stamp))],
392            })
393            .await?;
394        Ok(matched == 1)
395    }
396
397    pub async fn find_account(
398        &self,
399        provider_id: &str,
400        account_id: &str,
401    ) -> Result<Option<Account>, AuthError> {
402        let filter = Account::PROVIDER_ID
403            .eq(provider_id)
404            .and(Account::ACCOUNT_ID.eq(account_id));
405        Ok(self.ctx.db().find::<Account>(filter).one().await?)
406    }
407
408    pub async fn credential_account(&self, user_id: &Id) -> Result<Option<Account>, AuthError> {
409        let filter = Account::USER_ID
410            .eq(user_id)
411            .and(Account::PROVIDER_ID.eq(Account::CREDENTIAL));
412        Ok(self.ctx.db().find::<Account>(filter).one().await?)
413    }
414
415    /// The app and plugin columns in `extra` (a body's extra camelCase keys), after every
416    /// [`prepare_user_input`](crate::plugin::PluginBuilder::prepare_user_input) hook, parsed
417    /// like [`user_input_fields`](crate::routes::user_input_fields). Creating a user needs every
418    /// required column; an update doesn't.
419    pub async fn user_fields(
420        &self,
421        extra: &serde_json::Map<String, serde_json::Value>,
422        input: UserInput,
423    ) -> Result<Vec<(&'static str, Value)>, AuthError> {
424        let mut extra = extra.clone();
425        for hook in &self.ctx.shared.user_input_hooks {
426            extra = hook(self.ctx.retype(), extra, input).await?;
427        }
428        crate::routes::user_input_fields(self.ctx, &extra, input != UserInput::Update)
429    }
430
431    /// Checks a new password against the configured length limits and policy.
432    pub fn validate_new_password(&self, password: &str) -> Result<(), AuthError> {
433        let Some(config) = &self.ctx.config().email_password else {
434            return Ok(());
435        };
436        let length = password.chars().count();
437        if length < config.min_password_length {
438            return Err(AuthError::bad_request(
439                codes::PASSWORD_TOO_SHORT,
440                "password is too short",
441            ));
442        }
443        if length > config.max_password_length {
444            return Err(AuthError::bad_request(
445                codes::PASSWORD_TOO_LONG,
446                "password is too long",
447            ));
448        }
449        if config
450            .password_policy
451            .as_ref()
452            .is_some_and(|policy| !policy(password))
453        {
454            return Err(AuthError::bad_request(
455                codes::PASSWORD_TOO_WEAK,
456                "password is too weak",
457            ));
458        }
459        Ok(())
460    }
461
462    /// Validates, hashes and stores a password, creating the credential account if needed.
463    pub async fn set_password(&self, user_id: &Id, password: &str) -> Result<(), AuthError> {
464        self.validate_new_password(password)?;
465        let hash = self
466            .ctx
467            .passwords()
468            .hash(password)
469            .await
470            .map_err(AuthError::internal)?;
471        let update = || {
472            self.ctx
473                .db()
474                .update::<Account>(
475                    Account::USER_ID
476                        .eq(user_id)
477                        .and(Account::PROVIDER_ID.eq(Account::CREDENTIAL)),
478                )
479                .set(Account::PASSWORD_HASH, Some(hash.clone()))
480                .exec()
481        };
482        if update().await? > 0 {
483            return Ok(());
484        }
485        match self
486            .link_account(user_id, NewAccount::credential(hash.clone()))
487            .await
488        {
489            Err(err) if err.code() == codes::SOCIAL_ACCOUNT_ALREADY_LINKED => {
490                update().await?;
491                Ok(())
492            }
493            other => other.map(|_| ()),
494        }
495    }
496
497    /// Creates a session and sets its cookies, running no sign-in gate at all. This is the
498    /// low-level primitive: sign a user in with [`sign_in`](Self::sign_in), and finish a
499    /// challenged sign-in with [`complete_sign_in`](Self::complete_sign_in). Finishing one
500    /// with this would skip every other plugin's gates, so a banned user would get a session.
501    ///
502    /// A `remember_me: false` session lives one day at most and is never extended. The session
503    /// hooks run before the response gets the session: when one fails, the session is deleted
504    /// and the response sets none of its cookies.
505    pub async fn create_session(
506        &self,
507        user_id: &Id,
508        remember_me: bool,
509    ) -> Result<SessionView, AuthError> {
510        self.create_session_with(user_id, remember_me, NewSession::default())
511            .await
512    }
513
514    /// [`create_session`](Self::create_session) with an expiry or plugin columns of its own,
515    /// stored in the one insert, so the session hooks and every later request see them.
516    pub async fn create_session_with(
517        &self,
518        user_id: &Id,
519        remember_me: bool,
520        options: NewSession,
521    ) -> Result<SessionView, AuthError> {
522        self.insert_session(user_id, None, remember_me, options)
523            .await
524    }
525
526    /// [`create_session_with`](Self::create_session_with), refused with 401 when proof of the
527    /// email claimed the user since `stamp` was read: the session is deleted again before
528    /// anyone sees its token.
529    async fn insert_session(
530        &self,
531        user_id: &Id,
532        stamp: Option<i64>,
533        remember_me: bool,
534        options: NewSession,
535    ) -> Result<SessionView, AuthError> {
536        let now = self.ctx.now();
537        let token = random_token();
538        let lifetime = match remember_me {
539            true => self.ctx.config().session.expires_in,
540            false => self
541                .ctx
542                .config()
543                .session
544                .expires_in
545                .min(DONT_REMEMBER_LIFETIME),
546        };
547        let session = Session {
548            id: self.ctx.new_id()?,
549            token_hash: Hash::sha256(&token),
550            user_id: user_id.clone(),
551            expires_at: options.expires_at.unwrap_or(now + lifetime),
552            ip_address: self.ctx.ip().map(str::to_owned),
553            user_agent: self
554                .ctx
555                .user_agent()
556                .map(|ua| ua.chars().take(512).collect()),
557            created_at: now,
558            updated_at: now,
559        };
560        let mut values = session.encode();
561        values.extend(options.values);
562        let row = self.ctx.db().insert_row::<Session>(values).await?;
563        let session = Session::decode(&row).map_err(AuthError::internal)?;
564        if let Some(stamp) = stamp
565            && !self.stamp_holds(user_id, stamp).await?
566        {
567            self.ctx
568                .db()
569                .delete::<Session>(Session::ID.eq(&session.id))
570                .await?;
571            return Err(claimed_meanwhile());
572        }
573        let user = self
574            .find_user_by_id(user_id)
575            .await?
576            .ok_or_else(|| AuthError::internal("session for a missing user"))?;
577        let view = SessionView {
578            session,
579            row,
580            user,
581            token: Some(token.clone()),
582            ephemeral: false,
583            from_cache: false,
584        };
585        let config = self.ctx.config();
586        let before = self.ctx.effects.lock().unwrap().cookies.clone();
587        set_session_cookies(
588            config,
589            self.ctx.keys(),
590            &self.ctx.effects,
591            &token,
592            remember_me,
593        );
594        for hook in &self.ctx.shared.session_hooks {
595            if let Err(err) = hook(self.ctx.retype(), view.clone()).await {
596                self.ctx.effects.lock().unwrap().cookies = before;
597                self.ctx
598                    .db()
599                    .delete::<Session>(Session::ID.eq(&view.session.id))
600                    .await?;
601                return Err(err);
602            }
603        }
604        self.ctx.set_cookie(crate::cookies::SetCookie::delete(
605            config.cookie_name(SESSION_DATA),
606        ));
607        self.ctx.emit(SessionCreated {
608            session_id: view.session.id.clone(),
609            user_id: user_id.clone(),
610        });
611        Ok(view)
612    }
613
614    /// The unexpired session `token` belongs to, with its user, without refreshing it.
615    /// For plugins that hold session tokens of their own, such as one per signed-in account.
616    pub async fn find_session_by_token(
617        &self,
618        token: &str,
619    ) -> Result<Option<SessionView>, AuthError> {
620        crate::session::by_token(&self.ctx.shared, self.ctx.adapter(), token).await
621    }
622
623    /// The request-only session a resolver's [`Resolved::User`](crate::endpoint::Resolved)
624    /// gets for this user, after the session gates. `None` when the user doesn't exist; the
625    /// gate's error when one refuses the user (a banned user, with the admin plugin). For
626    /// plugins that act for a user without a session, such as an API key's owner.
627    pub async fn ephemeral_session(&self, user_id: &Id) -> Result<Option<SessionView>, AuthError> {
628        crate::session::for_user(
629            &self.ctx.shared,
630            self.ctx.within.as_ref(),
631            &self.ctx.request,
632            &self.ctx.effects,
633            user_id,
634        )
635        .await
636    }
637
638    /// Makes `token` the request's session: sets the session cookie (for the configured
639    /// lifetime, or for the browser session when `remember_me` is false) and drops the
640    /// cookie cache, which belonged to the previous session.
641    pub fn set_session_cookies(&self, token: &str, remember_me: bool) {
642        let config = self.ctx.config();
643        set_session_cookies(
644            config,
645            self.ctx.keys(),
646            &self.ctx.effects,
647            token,
648            remember_me,
649        );
650        self.ctx.set_cookie(crate::cookies::SetCookie::delete(
651            config.cookie_name(SESSION_DATA),
652        ));
653    }
654
655    /// Runs every sign-in gate in registration order, then creates the session. The first
656    /// gate that denies or challenges ends the sign-in without a session.
657    ///
658    /// Read `user` before checking the credential it signs in with: when proof of the email
659    /// claims the user after `user` was read, the sign-in answers 401 instead of a session
660    /// (the security stamp changed), so a password check in flight during a claim can't keep
661    /// the previous holder signed in.
662    pub async fn sign_in(
663        &self,
664        user: UserView,
665        method: impl Into<Cow<'static, str>>,
666        remember_me: bool,
667    ) -> Result<SignInResult, AuthError> {
668        self.run_gates(user, method.into(), remember_me, None).await
669    }
670
671    /// Finishes a sign-in that a gate of plugin `challenger` answered with
672    /// [`Gate::Challenge`], once the user has met the challenge (e.g. a correct TOTP code).
673    /// Pass the plugin's own id (`TwoFactor::ID`, or `"app"` for a gate the app registered)
674    /// and the method the sign-in started with.
675    ///
676    /// Runs every gate except `challenger`'s, in registration order, whether they come before
677    /// or after it, then creates the session. A remaining gate can still deny, which returns
678    /// its error with no session. It can also challenge, which returns
679    /// [`SignInResult::Challenge`] with no session; answer with its body. That gate's plugin
680    /// finishes the sign-in with its own `complete_sign_in`, which runs `challenger`'s gates
681    /// again, so two gates that both challenge the same user keep challenging each other.
682    ///
683    /// A 500 when no gate belongs to `challenger`: a wrong id would run the challenger's
684    /// own gate again and challenge forever.
685    pub async fn complete_sign_in(
686        &self,
687        challenger: &str,
688        user: UserView,
689        method: impl Into<Cow<'static, str>>,
690        remember_me: bool,
691    ) -> Result<SignInResult, AuthError> {
692        if !self
693            .ctx
694            .shared
695            .gates
696            .iter()
697            .any(|gate| gate.owner == challenger)
698        {
699            return Err(AuthError::internal(format!(
700                "complete_sign_in: no sign-in gate belongs to `{challenger}`"
701            )));
702        }
703        self.run_gates(user, method.into(), remember_me, Some(challenger))
704            .await
705    }
706
707    async fn run_gates(
708        &self,
709        user: UserView,
710        method: Cow<'static, str>,
711        remember_me: bool,
712        skip: Option<&str>,
713    ) -> Result<SignInResult, AuthError> {
714        let attempt = SignInAttempt {
715            user: user.clone(),
716            method,
717            remember_me,
718        };
719        for owned in &self.ctx.shared.gates {
720            if skip == Some(owned.owner) {
721                continue;
722            }
723            match (owned.gate)(self.ctx.retype(), attempt.clone()).await? {
724                Gate::Allow => {}
725                Gate::Deny(err) => return Err(err),
726                Gate::Challenge(body) => return Ok(SignInResult::Challenge(body)),
727            }
728        }
729        Ok(SignInResult::SignedIn(Box::new(
730            self.insert_session(
731                &user.id,
732                Some(user.security_stamp()),
733                remember_me,
734                NewSession::default(),
735            )
736            .await?,
737        )))
738    }
739
740    /// Makes whoever just proved control of `user`'s email its only owner. Every path that
741    /// proves an email calls this: a magic link, an email code, a password-reset link, a
742    /// verified social profile, and a verification link that came without the password (see
743    /// [`prove_email`](Self::prove_email)).
744    ///
745    /// For a user whose email isn't verified, one transaction changes the security stamp,
746    /// marks the email verified, deletes every account (password and OAuth links), session and
747    /// core token (verification and reset links) the user collected before the proof, runs
748    /// every plugin's [`on_claim`](crate::plugin::PluginBuilder::on_claim) cleanup (passkeys,
749    /// API keys, two-factor), and links `link`, the account the proof came with, if any.
750    /// A failing cleanup rolls the whole claim back and fails the call. Sign-ins and links
751    /// that started before the claim can't finish after it, because the stamp changed.
752    /// [`UserClaimed`] and [`EmailVerified`] are emitted after the commit, for
753    /// notifications only.
754    ///
755    /// A verified user comes back unchanged, with `link` linked: whoever proved the email
756    /// before already owns it.
757    pub async fn claim_user(
758        &self,
759        user: UserView,
760        link: Option<NewAccount>,
761    ) -> Result<UserView, AuthError> {
762        let linked_provider = link.as_ref().map(|account| account.provider_id.clone());
763        let link = link
764            .map(|account| self.account_values(&user.id, account))
765            .transpose()?;
766        if !user.email_verified {
767            let tx = self.ctx.adapter().begin().await?;
768            match self.claim_in(&tx, &user.id, link.clone()).await {
769                Ok(Some(revoked)) => {
770                    tx.commit().await?;
771                    if revoked > 0 {
772                        self.ctx.emit(SessionRevoked {
773                            user_id: user.id.clone(),
774                            session_id: None,
775                        });
776                    }
777                    self.ctx.emit(EmailVerified {
778                        user_id: user.id.clone(),
779                    });
780                    self.ctx.emit(UserClaimed {
781                        user_id: user.id.clone(),
782                    });
783                    if let Some(provider_id) = linked_provider {
784                        self.ctx.emit(AccountLinked {
785                            user_id: user.id.clone(),
786                            provider_id,
787                        });
788                    }
789                    return self
790                        .find_user_by_id(&user.id)
791                        .await?
792                        .ok_or_else(|| AuthError::internal("user deleted while claiming it"));
793                }
794                // Verified meanwhile, by a proof that claimed it first.
795                Ok(None) => tx.rollback().await?,
796                Err(err) => {
797                    let _ = tx.rollback().await;
798                    return Err(err);
799                }
800            }
801        }
802        if let Some(values) = link {
803            self.ctx
804                .db()
805                .insert_row::<Account>(values)
806                .await
807                .map_err(account_linked)?;
808            if let Some(provider_id) = linked_provider {
809                self.ctx.emit(AccountLinked {
810                    user_id: user.id.clone(),
811                    provider_id,
812                });
813            }
814        }
815        self.find_user_by_id(&user.id)
816            .await?
817            .ok_or_else(|| AuthError::internal("user deleted while claiming it"))
818    }
819
820    /// [`claim_user`](Self::claim_user) without an account to link, the 0.5 name.
821    #[deprecated(since = "0.6.0", note = "use `claim_user(user, None)`")]
822    pub async fn claim_unverified_user(&self, user: UserView) -> Result<UserView, AuthError> {
823        self.claim_user(user, None).await
824    }
825
826    /// The claim's statements, in `tx`. The user row is written first, so a concurrent
827    /// [`stamp_holds`](Self::stamp_holds) waits for the claim. `None` when the user was
828    /// verified meanwhile; otherwise how many sessions were revoked.
829    async fn claim_in(
830        &self,
831        tx: &D::Tx,
832        user_id: &Id,
833        link: Option<Vec<(&'static str, Value)>>,
834    ) -> Result<Option<u64>, AuthError> {
835        let db = self.ctx.db_on(tx);
836        let claimed = db
837            .update::<User>(User::ID.eq(user_id).and(User::EMAIL_VERIFIED.eq(false)))
838            .set(User::SECURITY_STAMP, new_security_stamp())
839            .set(User::EMAIL_VERIFIED, true)
840            .exec()
841            .await?;
842        if claimed == 0 {
843            return Ok(None);
844        }
845        db.delete::<Account>(Account::USER_ID.eq(user_id)).await?;
846        let revoked = db.delete::<Session>(Session::USER_ID.eq(user_id)).await?;
847        db.delete::<Verification>(
848            Verification::IDENTIFIER.in_(user_verification_identifiers(user_id)),
849        )
850        .await?;
851        for cleanup in &self.ctx.shared.claim_hooks {
852            cleanup(Claim {
853                user_id,
854                tx,
855                schema: self.ctx.schema(),
856                _adapter: PhantomData,
857            })
858            .await?;
859        }
860        if let Some(values) = link {
861            db.insert_row::<Account>(values)
862                .await
863                .map_err(account_linked)?;
864        }
865        Ok(Some(revoked))
866    }
867
868    /// The request proved control of `user`'s email with a verification link or code. When
869    /// it also proves it holds the user's password (it carries the user's session, or the
870    /// signed cookie that sign-up or a refused unverified sign-in left in the browser that
871    /// knew the password), the email is marked verified and nothing else changes. Otherwise
872    /// whoever set the password may not own the mailbox, so the user is claimed
873    /// ([`claim_user`](Self::claim_user)): the password and everything else from before the
874    /// proof is gone, and the owner signs in by link or sets a password with a reset.
875    pub async fn prove_email(&self, user: UserView) -> Result<UserView, AuthError> {
876        if user.email_verified {
877            return Ok(user);
878        }
879        if !self.holds_credentials_of(&user).await? {
880            return self.claim_user(user, None).await;
881        }
882        self.ctx
883            .db()
884            .update::<User>(User::ID.eq(&user.id))
885            .set(User::EMAIL_VERIFIED, true)
886            .exec()
887            .await?;
888        self.ctx.emit(EmailVerified {
889            user_id: user.id.clone(),
890        });
891        self.find_user_by_id(&user.id)
892            .await?
893            .ok_or_else(|| AuthError::internal("user deleted while verifying it"))
894    }
895
896    /// Whether this request comes from the browser that holds `user`'s credentials: it
897    /// carries a live session of the user, or the signed [`PENDING_VERIFICATION`] cookie
898    /// for the user's current security stamp.
899    async fn holds_credentials_of(&self, user: &UserView) -> Result<bool, AuthError> {
900        let binding = self.ctx.signed_cookie(PENDING_VERIFICATION);
901        if binding.is_some() {
902            self.ctx.delete_cookie(PENDING_VERIFICATION);
903        }
904        if binding.as_deref() == Some(user_binding(user).as_str()) {
905            return Ok(true);
906        }
907        let Some(token) = self.ctx.signed_token_cookie(crate::session::SESSION_TOKEN) else {
908            return Ok(false);
909        };
910        Ok(self
911            .find_session_by_token(&token)
912            .await?
913            .is_some_and(|session| !session.ephemeral && session.user.id == user.id))
914    }
915
916    /// Leaves the signed cookie [`prove_email`](Self::prove_email) accepts as proof that this
917    /// browser knows `user`'s password, for as long as a verification link lives. Sign-up and
918    /// a sign-in refused for an unverified email call this.
919    pub fn remember_password_holder(&self, user: &UserView) {
920        self.ctx.set_signed_cookie(
921            PENDING_VERIFICATION,
922            &user_binding(user),
923            Some(self.ctx.config().email_verification.ttl),
924        );
925    }
926
927    /// Stores a single-use token for `user` under `{purpose}:{user_id}`, bound to the user's
928    /// security stamp and email: [`consume_user_verification`](Self::consume_user_verification)
929    /// refuses it once a claim or a change of email happened since. For links mailed to the
930    /// user, such as email verification and password reset.
931    pub async fn create_user_verification(
932        &self,
933        purpose: &str,
934        user: &UserView,
935        ttl: Duration,
936    ) -> Result<String, AuthError> {
937        self.create_verification(
938            &format!("{purpose}:{}", user.id),
939            ttl,
940            Some(user_binding(user)),
941        )
942        .await
943    }
944
945    /// Consumes a token from [`create_user_verification`](Self::create_user_verification) for
946    /// `purpose` and answers its user. `None` when the token is unknown, expired, for another
947    /// purpose, or minted before the user was claimed or changed email.
948    pub async fn consume_user_verification(
949        &self,
950        purpose: &str,
951        token: &str,
952    ) -> Result<Option<UserView>, AuthError> {
953        let Some(verification) = self.consume_verification(token).await? else {
954            return Ok(None);
955        };
956        let Some(user_id) = verification
957            .identifier
958            .strip_prefix(purpose)
959            .and_then(|rest| rest.strip_prefix(':'))
960        else {
961            return Ok(None);
962        };
963        let Some(user) = self.find_user_by_id(&Id::from(user_id)).await? else {
964            return Ok(None);
965        };
966        let bound = verification.data.as_deref() == Some(user_binding(&user).as_str());
967        Ok(bound.then_some(user))
968    }
969
970    pub async fn revoke_session(&self, user_id: &Id, session_id: &Id) -> Result<bool, AuthError> {
971        let deleted = self
972            .ctx
973            .db()
974            .delete::<Session>(Session::ID.eq(session_id).and(Session::USER_ID.eq(user_id)))
975            .await?;
976        if deleted > 0 {
977            self.ctx.emit(SessionRevoked {
978                user_id: user_id.clone(),
979                session_id: Some(session_id.clone()),
980            });
981        }
982        Ok(deleted > 0)
983    }
984
985    /// Deletes every session of a user, except `keep` when given.
986    pub async fn revoke_user_sessions(
987        &self,
988        user_id: &Id,
989        keep: Option<&Id>,
990    ) -> Result<u64, AuthError> {
991        let mut filter = Session::USER_ID.eq(user_id);
992        if let Some(keep) = keep {
993            filter = filter.and(Session::ID.ne(keep));
994        }
995        let deleted = self.ctx.db().delete::<Session>(filter).await?;
996        if deleted > 0 {
997            self.ctx.emit(SessionRevoked {
998                user_id: user_id.clone(),
999                session_id: None,
1000            });
1001        }
1002        Ok(deleted)
1003    }
1004
1005    pub fn clear_session_cookies(&self) {
1006        clear_session_cookies(self.ctx.config(), &self.ctx.effects);
1007    }
1008
1009    /// Deletes every expired verification, as Better Auth does on lookup. Runs before each
1010    /// new one is stored, so rows anyone can mint (OAuth states, passkey challenges, magic
1011    /// links) don't pile up.
1012    async fn purge_expired_verifications(&self) -> Result<(), AuthError> {
1013        self.ctx
1014            .db()
1015            .delete::<Verification>(Verification::EXPIRES_AT.lt(self.ctx.now()))
1016            .await?;
1017        Ok(())
1018    }
1019
1020    /// Stores a single-use value and returns it. Only its hash is kept.
1021    pub async fn create_verification(
1022        &self,
1023        identifier: &str,
1024        ttl: Duration,
1025        data: Option<String>,
1026    ) -> Result<String, AuthError> {
1027        self.purge_expired_verifications().await?;
1028        let token = random_token();
1029        let now = self.ctx.now();
1030        let verification = Verification {
1031            id: self.ctx.new_id()?,
1032            identifier: identifier.to_owned(),
1033            value_hash: Hash::sha256(&token),
1034            data,
1035            expires_at: now + ttl,
1036            created_at: now,
1037            updated_at: now,
1038        };
1039        self.ctx.db().insert(&verification).await?;
1040        Ok(token)
1041    }
1042
1043    /// Stores a caller-chosen value (e.g. a 6-digit OTP) under `identifier`, replacing older ones.
1044    pub async fn store_verification_value(
1045        &self,
1046        identifier: &str,
1047        value: &str,
1048        ttl: Duration,
1049        data: Option<String>,
1050    ) -> Result<(), AuthError> {
1051        self.purge_expired_verifications().await?;
1052        self.ctx
1053            .db()
1054            .delete::<Verification>(Verification::IDENTIFIER.eq(identifier))
1055            .await?;
1056        let now = self.ctx.now();
1057        let verification = Verification {
1058            id: self.ctx.new_id()?,
1059            identifier: identifier.to_owned(),
1060            value_hash: Hash::sha256(format!("{identifier}:{value}")),
1061            data,
1062            expires_at: now + ttl,
1063            created_at: now,
1064            updated_at: now,
1065        };
1066        self.ctx.db().insert(&verification).await?;
1067        Ok(())
1068    }
1069
1070    /// Consumes a value stored with `store_verification_value`.
1071    pub async fn consume_verification_value(
1072        &self,
1073        identifier: &str,
1074        value: &str,
1075    ) -> Result<Option<Verification>, AuthError> {
1076        self.consume_hash(Hash::sha256(format!("{identifier}:{value}")))
1077            .await
1078    }
1079
1080    /// The unexpired verification for `token`, without consuming it.
1081    pub async fn find_verification(&self, token: &str) -> Result<Option<Verification>, AuthError> {
1082        let found = self
1083            .ctx
1084            .db()
1085            .find::<Verification>(Verification::VALUE_HASH.eq(Hash::sha256(token)))
1086            .one()
1087            .await?;
1088        Ok(found.filter(|v| v.expires_at > self.ctx.now()))
1089    }
1090
1091    /// Finds and deletes the verification for `token`. `None` if unknown or expired.
1092    pub async fn consume_verification(
1093        &self,
1094        token: &str,
1095    ) -> Result<Option<Verification>, AuthError> {
1096        self.consume_hash(Hash::sha256(token)).await
1097    }
1098
1099    async fn consume_hash(&self, hash: Hash) -> Result<Option<Verification>, AuthError> {
1100        let Some(found) = self
1101            .ctx
1102            .db()
1103            .find::<Verification>(Verification::VALUE_HASH.eq(hash))
1104            .one()
1105            .await?
1106        else {
1107            return Ok(None);
1108        };
1109        let deleted = self
1110            .ctx
1111            .db()
1112            .delete::<Verification>(Verification::ID.eq(&found.id))
1113            .await?;
1114        Ok((deleted == 1 && found.expires_at > self.ctx.now()).then_some(found))
1115    }
1116
1117    /// Whether a mailer is configured, so `send_email` can succeed.
1118    pub fn can_send_email(&self) -> bool {
1119        self.ctx.mailer().is_some()
1120    }
1121
1122    pub async fn send_email(&self, email: AuthEmail) -> Result<(), AuthError> {
1123        let Some(mailer) = self.ctx.mailer() else {
1124            return Err(AuthError::internal(
1125                "an email needs sending but no mailer is configured",
1126            ));
1127        };
1128        mailer.send(email).await.map_err(AuthError::internal)
1129    }
1130
1131    /// Sends `email` without waiting for the mailer, so the route answers in the same time
1132    /// whether or not it sent anything. Use it where sending depends on whether an account
1133    /// exists. A failed send is logged (`tracing::error!`), not returned.
1134    pub async fn send_email_in_background(&self, email: AuthEmail) -> Result<(), AuthError> {
1135        let Some(mailer) = self.ctx.mailer() else {
1136            return Err(AuthError::internal(
1137                "an email needs sending but no mailer is configured",
1138            ));
1139        };
1140        crate::mail::send_in_background(mailer.clone(), email).await;
1141        Ok(())
1142    }
1143
1144    /// The database work of creating and looking up a verification token, for the branch
1145    /// of a route that sends nothing, so both branches take about as long.
1146    pub async fn simulate_verification(&self) -> Result<(), AuthError> {
1147        let token = random_token();
1148        self.find_verification(&token).await?;
1149        Ok(())
1150    }
1151
1152    /// Creates a verification token and emails the link in the background (see
1153    /// `send_email_in_background`).
1154    pub async fn send_verification_email(
1155        &self,
1156        user: &UserView,
1157        callback_url: Option<&str>,
1158    ) -> Result<(), AuthError> {
1159        let ttl = self.ctx.config().email_verification.ttl;
1160        let token = self
1161            .create_user_verification("email-verification", user, ttl)
1162            .await?;
1163        let mut url = format!(
1164            "{}/verify-email?token={token}",
1165            self.ctx.config().auth_url()
1166        );
1167        if let Some(callback) = callback_url {
1168            url.push_str(&format!("&callbackURL={}", url_encode(callback)));
1169        }
1170        self.send_email_in_background(AuthEmail::VerifyEmail(VerifyEmail {
1171            to: user.email.clone(),
1172            name: user.name.clone(),
1173            url,
1174            token,
1175        }))
1176        .await
1177    }
1178}