Skip to main content

fastauth_core/
models.rs

1//! Core tables: `user`, `session`, `account`, `verification`.
2
3use time::OffsetDateTime;
4
5use crate::config::SessionTokens;
6use crate::crypto::{Hash, Keys};
7use crate::model::{Col, Model, OnTable};
8use crate::schema::{ColumnDef, ColumnType as T, DefaultValue, OnDelete, SchemaBuilder};
9use crate::value::{ColumnValue, DecodeError, Id, Row, Value};
10
11const fn timestamps() -> [ColumnDef; 2] {
12    [
13        ColumnDef::new("created_at", T::Timestamp).default(DefaultValue::Now),
14        ColumnDef::new("updated_at", T::Timestamp).default(DefaultValue::Now),
15    ]
16}
17
18macro_rules! columns {
19    ($($col:expr),* $(,)?) => {{
20        const STAMPS: [ColumnDef; 2] = timestamps();
21        const COLUMNS: &[ColumnDef] = &[$($col,)* STAMPS[0], STAMPS[1]];
22        COLUMNS
23    }};
24}
25
26pub(crate) fn register_with(schema: &mut SchemaBuilder, tokens: SessionTokens) {
27    schema.model::<User>();
28    match tokens {
29        SessionTokens::Hashed => schema.model::<Session>(),
30        SessionTokens::Raw => schema.table(Session::TABLE, Session::raw_token_columns()),
31    };
32    schema
33        .model::<Account>()
34        .unique(Account::TABLE, &["provider_id", "account_id"])
35        .model::<Verification>();
36}
37
38fn get<T: ColumnValue>(row: &Row, column: &str) -> Result<T, DecodeError> {
39    row.get(column)
40}
41
42/// The core columns of `user`. Plugin and app columns live on the same row; read them from
43/// `AuthUser` (typed) or `UserView::fields` (inside plugins).
44#[derive(Clone, Debug, PartialEq, serde::Serialize)]
45#[serde(rename_all = "camelCase")]
46pub struct User {
47    pub id: Id,
48    pub email: String,
49    pub email_verified: bool,
50    pub name: String,
51    pub image: Option<String>,
52    #[serde(with = "time::serde::rfc3339")]
53    pub created_at: OffsetDateTime,
54    #[serde(with = "time::serde::rfc3339")]
55    pub updated_at: OffsetDateTime,
56}
57
58impl User {
59    pub const ID: Col<User, Id> = Col::new("id");
60    pub const EMAIL: Col<User, String> = Col::new("email");
61    pub const EMAIL_VERIFIED: Col<User, bool> = Col::new("email_verified");
62    pub const NAME: Col<User, String> = Col::new("name");
63    pub const IMAGE: Col<User, Option<String>> = Col::new("image");
64    /// A random value that changes whenever proof of the email claims the user. A sign-in or
65    /// account link that started before a claim can't finish after it. Never sent to clients.
66    pub const SECURITY_STAMP: Col<User, i64> = Col::new("security_stamp");
67    pub const CREATED_AT: Col<User, OffsetDateTime> = Col::new("created_at");
68    pub const UPDATED_AT: Col<User, OffsetDateTime> = Col::new("updated_at");
69}
70
71impl OnTable for User {
72    type Table = User;
73}
74
75impl Model for User {
76    const TABLE: &'static str = "user";
77
78    fn columns() -> &'static [ColumnDef] {
79        columns![
80            ColumnDef::new("id", T::Id).primary_key(),
81            ColumnDef::new("email", T::Text).unique(),
82            ColumnDef::new("email_verified", T::Bool).default(DefaultValue::Bool(false)),
83            ColumnDef::new("name", T::Text).input(),
84            ColumnDef::new("image", T::Text).nullable().input(),
85            ColumnDef::new("security_stamp", T::Int)
86                .default(DefaultValue::Int(0))
87                .hidden(),
88        ]
89    }
90
91    fn decode(row: &Row) -> Result<Self, DecodeError> {
92        Ok(Self {
93            id: get(row, "id")?,
94            email: get(row, "email")?,
95            email_verified: get(row, "email_verified")?,
96            name: get(row, "name")?,
97            image: get(row, "image")?,
98            created_at: get(row, "created_at")?,
99            updated_at: get(row, "updated_at")?,
100        })
101    }
102
103    fn encode(&self) -> Vec<(&'static str, Value)> {
104        vec![
105            ("id", self.id.clone().into_value()),
106            ("email", self.email.clone().into_value()),
107            ("email_verified", self.email_verified.into_value()),
108            ("name", self.name.clone().into_value()),
109            ("image", self.image.clone().into_value()),
110            ("created_at", self.created_at.into_value()),
111            ("updated_at", self.updated_at.into_value()),
112        ]
113    }
114}
115
116/// A row of `session`. By default the token itself is never stored, only its SHA-256;
117/// with [`SessionTokens::Raw`] the table holds the token in `token` instead, and
118/// `token_hash` is computed from it when the row is read.
119#[derive(Clone, Debug, PartialEq)]
120pub struct Session {
121    pub id: Id,
122    pub token_hash: Hash,
123    pub user_id: Id,
124    pub expires_at: OffsetDateTime,
125    pub ip_address: Option<String>,
126    pub user_agent: Option<String>,
127    pub created_at: OffsetDateTime,
128    pub updated_at: OffsetDateTime,
129}
130
131impl Session {
132    pub const ID: Col<Session, Id> = Col::new("id");
133    pub const TOKEN_HASH: Col<Session, Hash> = Col::new("token_hash");
134    /// The token itself, only with [`SessionTokens::Raw`]. Never sent to clients. Filter by
135    /// a token with [`CoreConfig::session_token_eq`](crate::config::CoreConfig::session_token_eq),
136    /// which works under either setting.
137    pub const TOKEN: Col<Session, String> = Col::new("token");
138    pub const USER_ID: Col<Session, Id> = Col::new("user_id");
139    pub const EXPIRES_AT: Col<Session, OffsetDateTime> = Col::new("expires_at");
140    pub const CREATED_AT: Col<Session, OffsetDateTime> = Col::new("created_at");
141    pub const UPDATED_AT: Col<Session, OffsetDateTime> = Col::new("updated_at");
142}
143
144impl Session {
145    /// The columns with [`SessionTokens::Raw`]: `token` (text, unique) instead of
146    /// `token_hash`.
147    fn raw_token_columns() -> &'static [ColumnDef] {
148        columns![
149            ColumnDef::new("id", T::Id).primary_key(),
150            ColumnDef::new("token", T::Text).unique().hidden(),
151            ColumnDef::new("user_id", T::Id)
152                .references("user", "id", OnDelete::Cascade)
153                .index(),
154            ColumnDef::new("expires_at", T::Timestamp),
155            ColumnDef::new("ip_address", T::Text).nullable(),
156            ColumnDef::new("user_agent", T::Text).nullable(),
157        ]
158    }
159}
160
161impl OnTable for Session {
162    type Table = Session;
163}
164
165impl Model for Session {
166    const TABLE: &'static str = "session";
167
168    fn columns() -> &'static [ColumnDef] {
169        columns![
170            ColumnDef::new("id", T::Id).primary_key(),
171            ColumnDef::new("token_hash", T::Bytes).unique().hidden(),
172            ColumnDef::new("user_id", T::Id)
173                .references("user", "id", OnDelete::Cascade)
174                .index(),
175            ColumnDef::new("expires_at", T::Timestamp),
176            ColumnDef::new("ip_address", T::Text).nullable(),
177            ColumnDef::new("user_agent", T::Text).nullable(),
178        ]
179    }
180
181    fn decode(row: &Row) -> Result<Self, DecodeError> {
182        let token_hash = match row.table().position("token_hash") {
183            Some(_) => get(row, "token_hash")?,
184            None => Hash::sha256(get::<String>(row, "token")?),
185        };
186        Ok(Self {
187            id: get(row, "id")?,
188            token_hash,
189            user_id: get(row, "user_id")?,
190            expires_at: get(row, "expires_at")?,
191            ip_address: get(row, "ip_address")?,
192            user_agent: get(row, "user_agent")?,
193            created_at: get(row, "created_at")?,
194            updated_at: get(row, "updated_at")?,
195        })
196    }
197
198    fn encode(&self) -> Vec<(&'static str, Value)> {
199        vec![
200            ("id", self.id.clone().into_value()),
201            ("token_hash", self.token_hash.into_value()),
202            ("user_id", self.user_id.clone().into_value()),
203            ("expires_at", self.expires_at.into_value()),
204            ("ip_address", self.ip_address.clone().into_value()),
205            ("user_agent", self.user_agent.clone().into_value()),
206            ("created_at", self.created_at.into_value()),
207            ("updated_at", self.updated_at.into_value()),
208        ]
209    }
210}
211
212/// A way to sign in: `provider_id = "credential"` holds the password hash; OAuth providers
213/// hold their tokens, encrypted unless
214/// [`store_oauth_tokens_in_plaintext`](crate::Builder::store_oauth_tokens_in_plaintext) is on.
215/// Read them with [`Account::read_access_token`] and [`Account::read_refresh_token`].
216#[derive(Clone, Debug, PartialEq)]
217pub struct Account {
218    pub id: Id,
219    pub user_id: Id,
220    pub provider_id: String,
221    pub account_id: String,
222    pub password_hash: Option<String>,
223    /// As stored: `Keys::encrypt`ed, or the token's bytes (see [`Account::read_access_token`]).
224    pub access_token: Option<Vec<u8>>,
225    /// As stored, like `access_token`.
226    pub refresh_token: Option<Vec<u8>>,
227    pub id_token: Option<String>,
228    pub access_token_expires_at: Option<OffsetDateTime>,
229    pub refresh_token_expires_at: Option<OffsetDateTime>,
230    pub scope: Option<String>,
231    pub created_at: OffsetDateTime,
232    pub updated_at: OffsetDateTime,
233}
234
235impl Account {
236    pub const CREDENTIAL: &'static str = "credential";
237
238    /// The provider's access token, however the row stores it: encrypted by fastauth (as
239    /// bytes, or as hex in a text column), or as plain text, written by fastauth with
240    /// [`store_oauth_tokens_in_plaintext`](crate::Builder::store_oauth_tokens_in_plaintext) or
241    /// by a Better Auth app on the same database. `None` when the row has none, or holds
242    /// bytes that are neither.
243    ///
244    /// A value counts as fastauth's only when one of `keys`' secrets decrypts it, so keep a
245    /// retired secret in `.secrets(..)` while rows encrypted under it remain: without it, such
246    /// a row in a text column reads as its hex.
247    pub fn read_access_token(&self, keys: &Keys) -> Option<String> {
248        read_token(keys, self.access_token.as_deref()?)
249    }
250
251    /// The provider's refresh token, read like [`Account::read_access_token`].
252    pub fn read_refresh_token(&self, keys: &Keys) -> Option<String> {
253        read_token(keys, self.refresh_token.as_deref()?)
254    }
255
256    pub const ID: Col<Account, Id> = Col::new("id");
257    pub const USER_ID: Col<Account, Id> = Col::new("user_id");
258    pub const PROVIDER_ID: Col<Account, String> = Col::new("provider_id");
259    pub const ACCOUNT_ID: Col<Account, String> = Col::new("account_id");
260    pub const PASSWORD_HASH: Col<Account, Option<String>> = Col::new("password_hash");
261    pub const ACCESS_TOKEN: Col<Account, Option<Vec<u8>>> = Col::new("access_token");
262    pub const REFRESH_TOKEN: Col<Account, Option<Vec<u8>>> = Col::new("refresh_token");
263    pub const ID_TOKEN: Col<Account, Option<String>> = Col::new("id_token");
264    pub const ACCESS_TOKEN_EXPIRES_AT: Col<Account, Option<OffsetDateTime>> =
265        Col::new("access_token_expires_at");
266    pub const REFRESH_TOKEN_EXPIRES_AT: Col<Account, Option<OffsetDateTime>> =
267        Col::new("refresh_token_expires_at");
268    pub const SCOPE: Col<Account, Option<String>> = Col::new("scope");
269}
270
271impl OnTable for Account {
272    type Table = Account;
273}
274
275/// A stored OAuth token: fastauth's ciphertext as bytes, the same as hex text (what a UTF-8
276/// text column returns for a row written before plain-text storage), or the token itself.
277fn read_token(keys: &Keys, stored: &[u8]) -> Option<String> {
278    let unhex = |text: &str| -> Option<Vec<u8>> {
279        if !text.len().is_multiple_of(2) {
280            return None;
281        }
282        (0..text.len())
283            .step_by(2)
284            .map(|i| u8::from_str_radix(text.get(i..i + 2)?, 16).ok())
285            .collect()
286    };
287    let plain = keys
288        .decrypt(stored)
289        .or_else(|| keys.decrypt(&unhex(std::str::from_utf8(stored).ok()?)?))
290        .unwrap_or_else(|| stored.to_vec());
291    String::from_utf8(plain).ok()
292}
293
294impl Model for Account {
295    const TABLE: &'static str = "account";
296
297    fn columns() -> &'static [ColumnDef] {
298        columns![
299            ColumnDef::new("id", T::Id).primary_key(),
300            ColumnDef::new("user_id", T::Id)
301                .references("user", "id", OnDelete::Cascade)
302                .index(),
303            ColumnDef::new("provider_id", T::Text),
304            ColumnDef::new("account_id", T::Text).index(),
305            ColumnDef::new("password_hash", T::Text).nullable().hidden(),
306            ColumnDef::new("access_token", T::Bytes).nullable().hidden(),
307            ColumnDef::new("refresh_token", T::Bytes)
308                .nullable()
309                .hidden(),
310            ColumnDef::new("id_token", T::Text).nullable().hidden(),
311            ColumnDef::new("access_token_expires_at", T::Timestamp).nullable(),
312            ColumnDef::new("refresh_token_expires_at", T::Timestamp).nullable(),
313            ColumnDef::new("scope", T::Text).nullable(),
314        ]
315    }
316
317    fn decode(row: &Row) -> Result<Self, DecodeError> {
318        Ok(Self {
319            id: get(row, "id")?,
320            user_id: get(row, "user_id")?,
321            provider_id: get(row, "provider_id")?,
322            account_id: get(row, "account_id")?,
323            password_hash: get(row, "password_hash")?,
324            access_token: get(row, "access_token")?,
325            refresh_token: get(row, "refresh_token")?,
326            id_token: get(row, "id_token")?,
327            access_token_expires_at: get(row, "access_token_expires_at")?,
328            refresh_token_expires_at: get(row, "refresh_token_expires_at")?,
329            scope: get(row, "scope")?,
330            created_at: get(row, "created_at")?,
331            updated_at: get(row, "updated_at")?,
332        })
333    }
334
335    fn encode(&self) -> Vec<(&'static str, Value)> {
336        vec![
337            ("id", self.id.clone().into_value()),
338            ("user_id", self.user_id.clone().into_value()),
339            ("provider_id", self.provider_id.clone().into_value()),
340            ("account_id", self.account_id.clone().into_value()),
341            ("password_hash", self.password_hash.clone().into_value()),
342            ("access_token", self.access_token.clone().into_value()),
343            ("refresh_token", self.refresh_token.clone().into_value()),
344            ("id_token", self.id_token.clone().into_value()),
345            (
346                "access_token_expires_at",
347                self.access_token_expires_at.into_value(),
348            ),
349            (
350                "refresh_token_expires_at",
351                self.refresh_token_expires_at.into_value(),
352            ),
353            ("scope", self.scope.clone().into_value()),
354            ("created_at", self.created_at.into_value()),
355            ("updated_at", self.updated_at.into_value()),
356        ]
357    }
358}
359
360/// Single-use values: email verification, password reset, OAuth state, OTPs.
361/// `identifier` says what the value is for; only the hash of the value is stored.
362#[derive(Clone, Debug, PartialEq)]
363pub struct Verification {
364    pub id: Id,
365    pub identifier: String,
366    pub value_hash: Hash,
367    /// Extra data, e.g. an OAuth PKCE verifier or a callback URL.
368    pub data: Option<String>,
369    pub expires_at: OffsetDateTime,
370    pub created_at: OffsetDateTime,
371    pub updated_at: OffsetDateTime,
372}
373
374impl Verification {
375    pub const ID: Col<Verification, Id> = Col::new("id");
376    pub const IDENTIFIER: Col<Verification, String> = Col::new("identifier");
377    pub const VALUE_HASH: Col<Verification, Hash> = Col::new("value_hash");
378    pub const EXPIRES_AT: Col<Verification, OffsetDateTime> = Col::new("expires_at");
379}
380
381impl OnTable for Verification {
382    type Table = Verification;
383}
384
385impl Model for Verification {
386    const TABLE: &'static str = "verification";
387
388    fn columns() -> &'static [ColumnDef] {
389        columns![
390            ColumnDef::new("id", T::Id).primary_key(),
391            ColumnDef::new("identifier", T::Text).index(),
392            ColumnDef::new("value_hash", T::Bytes).unique().hidden(),
393            ColumnDef::new("data", T::Text).nullable().hidden(),
394            ColumnDef::new("expires_at", T::Timestamp),
395        ]
396    }
397
398    fn decode(row: &Row) -> Result<Self, DecodeError> {
399        Ok(Self {
400            id: get(row, "id")?,
401            identifier: get(row, "identifier")?,
402            value_hash: get(row, "value_hash")?,
403            data: get(row, "data")?,
404            expires_at: get(row, "expires_at")?,
405            created_at: get(row, "created_at")?,
406            updated_at: get(row, "updated_at")?,
407        })
408    }
409
410    fn encode(&self) -> Vec<(&'static str, Value)> {
411        vec![
412            ("id", self.id.clone().into_value()),
413            ("identifier", self.identifier.clone().into_value()),
414            ("value_hash", self.value_hash.into_value()),
415            ("data", self.data.clone().into_value()),
416            ("expires_at", self.expires_at.into_value()),
417            ("created_at", self.created_at.into_value()),
418            ("updated_at", self.updated_at.into_value()),
419        ]
420    }
421}