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