Skip to main content

fastauth_core/
models.rs

1//! Core tables: `user`, `session`, `account`, `verification`.
2
3use time::OffsetDateTime;
4
5use crate::crypto::Hash;
6use crate::model::{Col, Model, OnTable};
7use crate::schema::{ColumnDef, ColumnType as T, DefaultValue, OnDelete, SchemaBuilder};
8use crate::value::{ColumnValue, DecodeError, Id, Row, Value};
9
10const fn timestamps() -> [ColumnDef; 2] {
11    [
12        ColumnDef::new("created_at", T::Timestamp).default(DefaultValue::Now),
13        ColumnDef::new("updated_at", T::Timestamp).default(DefaultValue::Now),
14    ]
15}
16
17macro_rules! columns {
18    ($($col:expr),* $(,)?) => {{
19        const STAMPS: [ColumnDef; 2] = timestamps();
20        const COLUMNS: &[ColumnDef] = &[$($col,)* STAMPS[0], STAMPS[1]];
21        COLUMNS
22    }};
23}
24
25pub(crate) fn register(schema: &mut SchemaBuilder) {
26    schema
27        .model::<User>()
28        .model::<Session>()
29        .model::<Account>()
30        .unique(Account::TABLE, &["provider_id", "account_id"])
31        .model::<Verification>();
32}
33
34fn get<T: ColumnValue>(row: &Row, column: &str) -> Result<T, DecodeError> {
35    row.get(column)
36}
37
38/// The core columns of `user`. Plugin and app columns live on the same row; read them from
39/// `AuthUser` (typed) or `UserView::fields` (inside plugins).
40#[derive(Clone, Debug, PartialEq, serde::Serialize)]
41#[serde(rename_all = "camelCase")]
42pub struct User {
43    pub id: Id,
44    pub email: String,
45    pub email_verified: bool,
46    pub name: String,
47    pub image: Option<String>,
48    #[serde(with = "time::serde::rfc3339")]
49    pub created_at: OffsetDateTime,
50    #[serde(with = "time::serde::rfc3339")]
51    pub updated_at: OffsetDateTime,
52}
53
54impl User {
55    pub const ID: Col<User, Id> = Col::new("id");
56    pub const EMAIL: Col<User, String> = Col::new("email");
57    pub const EMAIL_VERIFIED: Col<User, bool> = Col::new("email_verified");
58    pub const NAME: Col<User, String> = Col::new("name");
59    pub const IMAGE: Col<User, Option<String>> = Col::new("image");
60    /// A random value that changes whenever proof of the email claims the user. A sign-in or
61    /// account link that started before a claim can't finish after it. Never sent to clients.
62    pub const SECURITY_STAMP: Col<User, i64> = Col::new("security_stamp");
63    pub const CREATED_AT: Col<User, OffsetDateTime> = Col::new("created_at");
64    pub const UPDATED_AT: Col<User, OffsetDateTime> = Col::new("updated_at");
65}
66
67impl OnTable for User {
68    type Table = User;
69}
70
71impl Model for User {
72    const TABLE: &'static str = "user";
73
74    fn columns() -> &'static [ColumnDef] {
75        columns![
76            ColumnDef::new("id", T::Id).primary_key(),
77            ColumnDef::new("email", T::Text).unique(),
78            ColumnDef::new("email_verified", T::Bool).default(DefaultValue::Bool(false)),
79            ColumnDef::new("name", T::Text).input(),
80            ColumnDef::new("image", T::Text).nullable().input(),
81            ColumnDef::new("security_stamp", T::Int)
82                .default(DefaultValue::Int(0))
83                .hidden(),
84        ]
85    }
86
87    fn decode(row: &Row) -> Result<Self, DecodeError> {
88        Ok(Self {
89            id: get(row, "id")?,
90            email: get(row, "email")?,
91            email_verified: get(row, "email_verified")?,
92            name: get(row, "name")?,
93            image: get(row, "image")?,
94            created_at: get(row, "created_at")?,
95            updated_at: get(row, "updated_at")?,
96        })
97    }
98
99    fn encode(&self) -> Vec<(&'static str, Value)> {
100        vec![
101            ("id", self.id.clone().into_value()),
102            ("email", self.email.clone().into_value()),
103            ("email_verified", self.email_verified.into_value()),
104            ("name", self.name.clone().into_value()),
105            ("image", self.image.clone().into_value()),
106            ("created_at", self.created_at.into_value()),
107            ("updated_at", self.updated_at.into_value()),
108        ]
109    }
110}
111
112/// A row of `session`. The token itself is never stored, only its SHA-256.
113#[derive(Clone, Debug, PartialEq)]
114pub struct Session {
115    pub id: Id,
116    pub token_hash: Hash,
117    pub user_id: Id,
118    pub expires_at: OffsetDateTime,
119    pub ip_address: Option<String>,
120    pub user_agent: Option<String>,
121    pub created_at: OffsetDateTime,
122    pub updated_at: OffsetDateTime,
123}
124
125impl Session {
126    pub const ID: Col<Session, Id> = Col::new("id");
127    pub const TOKEN_HASH: Col<Session, Hash> = Col::new("token_hash");
128    pub const USER_ID: Col<Session, Id> = Col::new("user_id");
129    pub const EXPIRES_AT: Col<Session, OffsetDateTime> = Col::new("expires_at");
130    pub const CREATED_AT: Col<Session, OffsetDateTime> = Col::new("created_at");
131    pub const UPDATED_AT: Col<Session, OffsetDateTime> = Col::new("updated_at");
132}
133
134impl OnTable for Session {
135    type Table = Session;
136}
137
138impl Model for Session {
139    const TABLE: &'static str = "session";
140
141    fn columns() -> &'static [ColumnDef] {
142        columns![
143            ColumnDef::new("id", T::Id).primary_key(),
144            ColumnDef::new("token_hash", T::Bytes).unique().hidden(),
145            ColumnDef::new("user_id", T::Id)
146                .references("user", "id", OnDelete::Cascade)
147                .index(),
148            ColumnDef::new("expires_at", T::Timestamp),
149            ColumnDef::new("ip_address", T::Text).nullable(),
150            ColumnDef::new("user_agent", T::Text).nullable(),
151        ]
152    }
153
154    fn decode(row: &Row) -> Result<Self, DecodeError> {
155        Ok(Self {
156            id: get(row, "id")?,
157            token_hash: get(row, "token_hash")?,
158            user_id: get(row, "user_id")?,
159            expires_at: get(row, "expires_at")?,
160            ip_address: get(row, "ip_address")?,
161            user_agent: get(row, "user_agent")?,
162            created_at: get(row, "created_at")?,
163            updated_at: get(row, "updated_at")?,
164        })
165    }
166
167    fn encode(&self) -> Vec<(&'static str, Value)> {
168        vec![
169            ("id", self.id.clone().into_value()),
170            ("token_hash", self.token_hash.into_value()),
171            ("user_id", self.user_id.clone().into_value()),
172            ("expires_at", self.expires_at.into_value()),
173            ("ip_address", self.ip_address.clone().into_value()),
174            ("user_agent", self.user_agent.clone().into_value()),
175            ("created_at", self.created_at.into_value()),
176            ("updated_at", self.updated_at.into_value()),
177        ]
178    }
179}
180
181/// A way to sign in: `provider_id = "credential"` holds the password hash; OAuth providers
182/// hold encrypted tokens.
183#[derive(Clone, Debug, PartialEq)]
184pub struct Account {
185    pub id: Id,
186    pub user_id: Id,
187    pub provider_id: String,
188    pub account_id: String,
189    pub password_hash: Option<String>,
190    /// `Keys::encrypt`ed.
191    pub access_token: Option<Vec<u8>>,
192    /// `Keys::encrypt`ed.
193    pub refresh_token: Option<Vec<u8>>,
194    pub id_token: Option<String>,
195    pub access_token_expires_at: Option<OffsetDateTime>,
196    pub refresh_token_expires_at: Option<OffsetDateTime>,
197    pub scope: Option<String>,
198    pub created_at: OffsetDateTime,
199    pub updated_at: OffsetDateTime,
200}
201
202impl Account {
203    pub const CREDENTIAL: &'static str = "credential";
204
205    pub const ID: Col<Account, Id> = Col::new("id");
206    pub const USER_ID: Col<Account, Id> = Col::new("user_id");
207    pub const PROVIDER_ID: Col<Account, String> = Col::new("provider_id");
208    pub const ACCOUNT_ID: Col<Account, String> = Col::new("account_id");
209    pub const PASSWORD_HASH: Col<Account, Option<String>> = Col::new("password_hash");
210    pub const ACCESS_TOKEN: Col<Account, Option<Vec<u8>>> = Col::new("access_token");
211    pub const REFRESH_TOKEN: Col<Account, Option<Vec<u8>>> = Col::new("refresh_token");
212    pub const ID_TOKEN: Col<Account, Option<String>> = Col::new("id_token");
213    pub const ACCESS_TOKEN_EXPIRES_AT: Col<Account, Option<OffsetDateTime>> =
214        Col::new("access_token_expires_at");
215    pub const REFRESH_TOKEN_EXPIRES_AT: Col<Account, Option<OffsetDateTime>> =
216        Col::new("refresh_token_expires_at");
217    pub const SCOPE: Col<Account, Option<String>> = Col::new("scope");
218}
219
220impl OnTable for Account {
221    type Table = Account;
222}
223
224impl Model for Account {
225    const TABLE: &'static str = "account";
226
227    fn columns() -> &'static [ColumnDef] {
228        columns![
229            ColumnDef::new("id", T::Id).primary_key(),
230            ColumnDef::new("user_id", T::Id)
231                .references("user", "id", OnDelete::Cascade)
232                .index(),
233            ColumnDef::new("provider_id", T::Text),
234            ColumnDef::new("account_id", T::Text).index(),
235            ColumnDef::new("password_hash", T::Text).nullable().hidden(),
236            ColumnDef::new("access_token", T::Bytes).nullable().hidden(),
237            ColumnDef::new("refresh_token", T::Bytes)
238                .nullable()
239                .hidden(),
240            ColumnDef::new("id_token", T::Text).nullable().hidden(),
241            ColumnDef::new("access_token_expires_at", T::Timestamp).nullable(),
242            ColumnDef::new("refresh_token_expires_at", T::Timestamp).nullable(),
243            ColumnDef::new("scope", T::Text).nullable(),
244        ]
245    }
246
247    fn decode(row: &Row) -> Result<Self, DecodeError> {
248        Ok(Self {
249            id: get(row, "id")?,
250            user_id: get(row, "user_id")?,
251            provider_id: get(row, "provider_id")?,
252            account_id: get(row, "account_id")?,
253            password_hash: get(row, "password_hash")?,
254            access_token: get(row, "access_token")?,
255            refresh_token: get(row, "refresh_token")?,
256            id_token: get(row, "id_token")?,
257            access_token_expires_at: get(row, "access_token_expires_at")?,
258            refresh_token_expires_at: get(row, "refresh_token_expires_at")?,
259            scope: get(row, "scope")?,
260            created_at: get(row, "created_at")?,
261            updated_at: get(row, "updated_at")?,
262        })
263    }
264
265    fn encode(&self) -> Vec<(&'static str, Value)> {
266        vec![
267            ("id", self.id.clone().into_value()),
268            ("user_id", self.user_id.clone().into_value()),
269            ("provider_id", self.provider_id.clone().into_value()),
270            ("account_id", self.account_id.clone().into_value()),
271            ("password_hash", self.password_hash.clone().into_value()),
272            ("access_token", self.access_token.clone().into_value()),
273            ("refresh_token", self.refresh_token.clone().into_value()),
274            ("id_token", self.id_token.clone().into_value()),
275            (
276                "access_token_expires_at",
277                self.access_token_expires_at.into_value(),
278            ),
279            (
280                "refresh_token_expires_at",
281                self.refresh_token_expires_at.into_value(),
282            ),
283            ("scope", self.scope.clone().into_value()),
284            ("created_at", self.created_at.into_value()),
285            ("updated_at", self.updated_at.into_value()),
286        ]
287    }
288}
289
290/// Single-use values: email verification, password reset, OAuth state, OTPs.
291/// `identifier` says what the value is for; only the hash of the value is stored.
292#[derive(Clone, Debug, PartialEq)]
293pub struct Verification {
294    pub id: Id,
295    pub identifier: String,
296    pub value_hash: Hash,
297    /// Extra data, e.g. an OAuth PKCE verifier or a callback URL.
298    pub data: Option<String>,
299    pub expires_at: OffsetDateTime,
300    pub created_at: OffsetDateTime,
301    pub updated_at: OffsetDateTime,
302}
303
304impl Verification {
305    pub const ID: Col<Verification, Id> = Col::new("id");
306    pub const IDENTIFIER: Col<Verification, String> = Col::new("identifier");
307    pub const VALUE_HASH: Col<Verification, Hash> = Col::new("value_hash");
308    pub const EXPIRES_AT: Col<Verification, OffsetDateTime> = Col::new("expires_at");
309}
310
311impl OnTable for Verification {
312    type Table = Verification;
313}
314
315impl Model for Verification {
316    const TABLE: &'static str = "verification";
317
318    fn columns() -> &'static [ColumnDef] {
319        columns![
320            ColumnDef::new("id", T::Id).primary_key(),
321            ColumnDef::new("identifier", T::Text).index(),
322            ColumnDef::new("value_hash", T::Bytes).unique().hidden(),
323            ColumnDef::new("data", T::Text).nullable().hidden(),
324            ColumnDef::new("expires_at", T::Timestamp),
325        ]
326    }
327
328    fn decode(row: &Row) -> Result<Self, DecodeError> {
329        Ok(Self {
330            id: get(row, "id")?,
331            identifier: get(row, "identifier")?,
332            value_hash: get(row, "value_hash")?,
333            data: get(row, "data")?,
334            expires_at: get(row, "expires_at")?,
335            created_at: get(row, "created_at")?,
336            updated_at: get(row, "updated_at")?,
337        })
338    }
339
340    fn encode(&self) -> Vec<(&'static str, Value)> {
341        vec![
342            ("id", self.id.clone().into_value()),
343            ("identifier", self.identifier.clone().into_value()),
344            ("value_hash", self.value_hash.into_value()),
345            ("data", self.data.clone().into_value()),
346            ("expires_at", self.expires_at.into_value()),
347            ("created_at", self.created_at.into_value()),
348            ("updated_at", self.updated_at.into_value()),
349        ]
350    }
351}