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