Skip to main content

renox_core/auth/
mod.rs

1//! Authentication and authorization: the `users` table, password hashing,
2//! session login with "remember me", route guards, policies and gates.
3//!
4//! ```
5//! # #[derive(Model, serde::Serialize, Default)]
6//! # #[model(table = "products")]
7//! # struct Product { id: i64, name: String, price: i64, category: Option<String>, user_id: i64 }
8//! # use renox::prelude::*;
9//! # impl Policy for Product { fn allows(&self, user: &User, _: &str) -> bool { self.user_id == user.id } }
10//! # let _ =
11//! App::new()
12//!     .module(Auth::new())                       // /login, /register, /logout
13//!     .gate("admin", |user| user.email.ends_with("@shop.example"))
14//!     .module(Shop)
15//! # ;
16//!
17//! struct Shop;
18//!
19//! impl Module for Shop {
20//! #   fn name(&self) -> &'static str { "shop" }
21//!     fn routes(&self) -> Routes {
22//!         Routes::new()
23//!             .get("/products/{id}/edit", edit)
24//!             .require_auth()                    // everything above needs a login
25//!     }
26//! }
27//!
28//! async fn edit(auth: AuthUser, State(db): State<Db>, Path(id): Path<i64>) -> Result<View> {
29//!     let product = Product::find_or_404(&db, id).await?;
30//!     auth.authorize("update", &product)?;       // 403 unless the policy allows it
31//!     Ok(view("products/edit.html", context! { product }))
32//! }
33//! ```
34
35pub(crate) mod account;
36mod device;
37pub mod events;
38mod external;
39mod inbox;
40pub(crate) mod module;
41pub mod notifications;
42pub mod one_time;
43pub mod passwordless;
44mod passwords;
45pub mod permissions;
46pub mod second_factor;
47mod throttle;
48mod tokens;
49mod user;
50mod verification;
51
52use std::collections::HashMap;
53use std::convert::Infallible;
54use std::ops::Deref;
55use std::sync::Arc;
56
57use axum::extract::{FromRequestParts, OptionalFromRequestParts, Request};
58use axum::http::header::{ACCEPT, AUTHORIZATION};
59use axum::http::request::Parts;
60use axum::http::{Method, StatusCode};
61use axum::middleware::Next;
62use axum::response::{IntoResponse, Redirect, Response};
63
64pub(crate) use account::require_password_confirmed;
65pub(crate) use device::require as device_guard;
66pub use device::{Device, DeviceToken, NewDeviceToken};
67pub use external::{confirm_identity, register_verified, registration_open, sign_in};
68pub use module::{Auth, Registration};
69pub use notifications::{
70    Channel, DatabaseMessage, DatabaseNotification, Notification, Recipient,
71    prune_read_notifications,
72};
73pub use one_time::{CodeCheck, OneTimeCode, prune_expired_codes};
74pub use passwordless::{LoginCodeDelivery, LoginCodes};
75pub(crate) use permissions::Grants;
76pub use permissions::Permissions;
77pub use second_factor::{PendingLogin, complete_login, pending_login};
78pub(crate) use throttle::LoginThrottle;
79pub use tokens::{AccessToken, NewToken, prune_expired_tokens};
80pub use user::{User, hash_password, needs_rehash, normalize_email, verify_password};
81pub use verification::send_verification;
82
83use crate::crypto::constant_time_eq;
84use crate::db::Db;
85use crate::{AppState, Error, Htmx, HxRedirect, Result, Session};
86
87pub(crate) const AUTH_ID: &str = "_auth_user_id";
88const AUTH_HASH: &str = "_auth_password_hash";
89/// Unix milliseconds of the login, compared with `users.sessions_revoked_at`.
90const AUTH_AT: &str = "_auth_at";
91/// A random id per login, so one device can be logged out (`revoked_sessions`).
92const AUTH_SID: &str = "_auth_session_id";
93const INTENDED: &str = "_intended";
94
95/// Decides whether a user may perform an ability on a model.
96///
97/// ```
98/// # #[derive(Model, serde::Serialize, Default)]
99/// # #[model(table = "products")]
100/// # struct Product { id: i64, name: String, price: i64, category: Option<String>, user_id: i64 }
101/// # use renox::prelude::*;
102/// impl Policy for Product {
103///     fn allows(&self, user: &User, ability: &str) -> bool {
104///         match ability {
105///             "update" | "delete" => self.user_id == user.id,
106///             _ => true,
107///         }
108///     }
109/// }
110/// ```
111pub trait Policy {
112    /// Whether `user` may perform `ability` (e.g. `"update"`) on this model.
113    fn allows(&self, user: &User, ability: &str) -> bool;
114}
115
116/// A model together with what the current user may do with it, so templates
117/// can ask the policy: `{% if can('update', product) %}`.
118///
119/// ```
120/// # use renox::prelude::*;
121/// # #[derive(Model, serde::Serialize, Default)] struct Product { id: i64, user_id: i64 }
122/// # impl Policy for Product { fn allows(&self, user: &User, _: &str) -> bool { self.user_id == user.id } }
123/// async fn index(State(db): State<Db>, user: Option<AuthUser>, Page(page): Page) -> Result<View> {
124///     let products = Product::query().paginate(&db, page, 20).await?
125///         .map(|p| Can::new(p, user.as_deref(), &["update", "delete"]));
126///     Ok(view("products/index.html", context! { products }))
127/// }
128/// ```
129///
130/// It serializes as the model's own fields plus `_can` (`{"update": true, …}`);
131/// guests get `false` for every ability.
132#[derive(Debug, Clone, serde::Serialize)]
133#[non_exhaustive]
134pub struct Can<T> {
135    /// The model, serialized as its own fields.
136    #[serde(flatten)]
137    pub item: T,
138    /// Each asked ability and whether it is allowed, serialized as `_can`.
139    #[serde(rename = "_can")]
140    pub abilities: std::collections::BTreeMap<String, bool>,
141}
142
143/// Who asks a policy, for [`Can::new`]: a [`User`], or an [`AuthUser`],
144/// which also applies `App::gate_before` (pass `user.as_ref()` for that).
145/// Sealed: only those two.
146pub trait Viewer: viewer::Sealed {
147    /// The user the policy is asked about.
148    fn as_user(&self) -> &User;
149
150    /// `App::gate_before`'s answer, if any.
151    fn before(&self, _ability: &str) -> Option<bool> {
152        None
153    }
154}
155
156mod viewer {
157    pub trait Sealed {}
158    impl Sealed for super::User {}
159    impl Sealed for super::AuthUser {}
160}
161
162impl Viewer for User {
163    fn as_user(&self) -> &User {
164        self
165    }
166}
167
168impl Viewer for AuthUser {
169    fn as_user(&self) -> &User {
170        &self.user
171    }
172
173    fn before(&self, ability: &str) -> Option<bool> {
174        AuthUser::before(self, ability)
175    }
176}
177
178impl<T: Policy> Can<T> {
179    /// Asks `item`'s policy about each of `abilities`; a guest (`None`) gets `false` for all.
180    pub fn new<V: Viewer + ?Sized>(item: T, user: Option<&V>, abilities: &[&str]) -> Self {
181        let abilities = abilities
182            .iter()
183            .map(|ability| {
184                let allowed = user.is_some_and(|user| {
185                    user.before(ability)
186                        .unwrap_or_else(|| item.allows(user.as_user(), ability))
187                });
188                ((*ability).to_owned(), allowed)
189            })
190            .collect();
191        Self { item, abilities }
192    }
193}
194
195pub(crate) type Gate = Arc<dyn Fn(&User) -> bool + Send + Sync>;
196pub(crate) type GateBefore = Arc<dyn Fn(&User, &str) -> Option<bool> + Send + Sync>;
197pub(crate) type Gates = Arc<Access>;
198
199/// The app's gates (`App::gate`), its `App::gate_before` hook, and whether
200/// the `Permissions` module is on.
201#[derive(Default)]
202pub(crate) struct Access {
203    pub gates: HashMap<String, Gate>,
204    pub before: Option<GateBefore>,
205    pub permissions: bool,
206}
207
208impl Access {
209    /// A gate or permission named `name`: `gate_before` first, then the gate,
210    /// then the user's permissions. Unknown names deny.
211    pub(crate) fn check(&self, user: &User, grants: &Grants, name: &str) -> bool {
212        if let Some(allowed) = self.before.as_ref().and_then(|before| before(user, name)) {
213            return allowed;
214        }
215        match self.gates.get(name) {
216            Some(check) => check(user),
217            None => grants.has_permission(name),
218        }
219    }
220}
221
222/// The logged-in user's grants, in [`crate::context`] for the request.
223#[derive(Clone)]
224pub(crate) struct CurrentGrants {
225    user_id: i64,
226    grants: Arc<Grants>,
227}
228
229impl User {
230    /// Whether this user has `role` (the `Permissions` module), answered
231    /// from the roles loaded for the current request, so it works in
232    /// `Policy::allows` and `App::gate_before` ("admins may do anything").
233    /// It is `false` for any other user, and outside a request (a job, a
234    /// command): use the async `user.roles(&db)` there.
235    ///
236    /// Global roles count, plus those given in the request's scope
237    /// (`permissions::set_scope`), within their dates.
238    pub fn has_role(&self, role: &str) -> bool {
239        current_grants(self.id).is_some_and(|g| g.has_role(role))
240    }
241
242    /// Like [`User::has_role`], for a permission granted by one of the
243    /// user's roles.
244    pub fn has_permission(&self, permission: &str) -> bool {
245        current_grants(self.id).is_some_and(|g| g.has_permission(permission))
246    }
247}
248
249/// The logged-in user's id in the current request, if any.
250pub(crate) fn current_user_id() -> Option<i64> {
251    crate::context::get::<CurrentGrants>().map(|current| current.user_id)
252}
253
254fn current_grants(user_id: i64) -> Option<Arc<Grants>> {
255    crate::context::get::<CurrentGrants>()
256        .filter(|current| current.user_id == user_id)
257        .map(|current| current.grants)
258}
259
260pub(crate) type AsyncGate = Arc<
261    dyn Fn(
262            User,
263            AppState,
264        ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<bool>> + Send>>
265        + Send
266        + Sync,
267>;
268
269/// The logged-in user of the current request, if any; set by Renox's auth
270/// middleware for every request.
271#[derive(Clone)]
272pub(crate) struct CurrentUser {
273    pub user: Option<Arc<User>>,
274    pub gates: Gates,
275    /// The API token of `Authorization: Bearer`, when that authenticated
276    /// the request (so CSRF doesn't apply).
277    pub token_id: Option<i64>,
278    /// That token's abilities; `None` for every ability (sessions, and
279    /// tokens made without a list).
280    pub abilities: Option<Arc<Vec<String>>>,
281    /// The device a device token authenticated (no user then).
282    pub device: Option<Arc<Device>>,
283    pub grants: Arc<Grants>,
284}
285
286/// The logged-in user. Requests without one are sent to the `login` route
287/// (HTMX requests via `HX-Redirect`) or get 401 when they want JSON. Use
288/// `Option<AuthUser>` where logging in is optional.
289#[derive(Clone)]
290pub struct AuthUser {
291    user: Arc<User>,
292    gates: Gates,
293    state: Option<AppState>,
294    token_id: Option<i64>,
295    abilities: Option<Arc<Vec<String>>>,
296    grants: Arc<Grants>,
297    /// `role_names`, worked out the first time it's asked.
298    role_names: std::sync::OnceLock<Vec<String>>,
299}
300
301impl Deref for AuthUser {
302    type Target = User;
303
304    fn deref(&self) -> &User {
305        &self.user
306    }
307}
308
309impl AuthUser {
310    /// The id of the API token this request logged in with
311    /// (`Authorization: Bearer`), or `None` for a session login. Revoke just
312    /// that token on "log out" from an app: `user.revoke_token(&db, id)`.
313    pub fn token_id(&self) -> Option<i64> {
314        self.token_id
315    }
316
317    /// Whether the API token this request logged in with may do `ability`
318    /// (`create_token_with(.., &["orders:read"], ..)`). Sessions, and tokens
319    /// made without a list, may do everything.
320    pub fn token_can(&self, ability: &str) -> bool {
321        self.abilities
322            .as_ref()
323            .is_none_or(|list| list.iter().any(|a| a == ability || a == "*"))
324    }
325
326    /// Whether the user has `role` (the `Permissions` module): a global
327    /// role, or one given in the request's scope (`permissions::set_scope`),
328    /// within its dates.
329    pub fn has_role(&self, role: &str) -> bool {
330        self.grants.has_role(role)
331    }
332
333    /// Whether one of the user's roles grants `permission` (the
334    /// `Permissions` module; the same roles as `has_role`).
335    /// `allows(permission)` also asks `App::gate_before`.
336    pub fn has_permission(&self, permission: &str) -> bool {
337        self.grants.has_permission(permission)
338    }
339
340    /// Whether a role of the user grants `permission` now, globally or in
341    /// at least one scope, whatever the request's scope. For showing
342    /// things such as menu links to someone who holds the permission only
343    /// through a scoped role; the page itself then filters by scope
344    /// (`scopes_with`, `has_permission_in`). `false` without the
345    /// `Permissions` module.
346    pub fn has_permission_anywhere(&self, permission: &str) -> bool {
347        self.grants.has_permission_anywhere(permission)
348    }
349
350    /// Whether the user has `role` globally or in `scope` (the record's,
351    /// not the request's), within its dates.
352    pub fn has_role_in(&self, role: &str, scope: &permissions::Scope) -> bool {
353        self.grants.has_role_in(role, Some(scope))
354    }
355
356    /// Whether a global role of the user, or one given in `scope` (the
357    /// record's, not the request's), grants `permission` now; for
358    /// policies and handlers that work on one record.
359    pub fn has_permission_in(&self, permission: &str, scope: &permissions::Scope) -> bool {
360        self.grants.has_permission_in(permission, Some(scope))
361    }
362
363    /// The records of model `M` in which the user holds `permission`:
364    /// `Scopes::All` when a global role grants it, else their keys. See
365    /// [`User::scopes_with`].
366    pub fn scopes_with<M: crate::db::Model>(
367        &self,
368        permission: &str,
369    ) -> permissions::Scopes<M::Key> {
370        self.grants.scopes_with::<M>(permission)
371    }
372
373    /// The user's roles (the `Permissions` module) in effect: the global
374    /// ones plus those in the request's scope, sorted, as they were the
375    /// first time this was asked.
376    pub fn role_names(&self) -> &[String] {
377        self.role_names.get_or_init(|| self.grants.roles())
378    }
379
380    /// Whether the policy of `target` allows `ability` (after
381    /// `App::gate_before`).
382    pub fn can(&self, ability: &str, target: &impl Policy) -> bool {
383        self.before(ability)
384            .unwrap_or_else(|| target.allows(&self.user, ability))
385    }
386
387    fn before(&self, ability: &str) -> Option<bool> {
388        self.gates
389            .before
390            .as_ref()
391            .and_then(|before| before(&self.user, ability))
392    }
393
394    /// Like `can`, but a refusal becomes a 403 response.
395    pub fn authorize(&self, ability: &str, target: &impl Policy) -> Result {
396        if self.can(ability, target) {
397            Ok(())
398        } else {
399            Err(Error::Forbidden)
400        }
401    }
402
403    /// Whether the gate named `gate` lets this user through: `gate_before`,
404    /// then the gate, then the user's permissions of that name. Unknown
405    /// names deny.
406    pub fn allows(&self, gate: &str) -> bool {
407        self.gates.check(&self.user, &self.grants, gate)
408    }
409
410    /// Like `allows`, but a refusal becomes a 403 response.
411    pub fn gate(&self, gate: &str) -> Result {
412        if self.allows(gate) {
413            Ok(())
414        } else {
415            Err(Error::Forbidden)
416        }
417    }
418
419    /// Whether the gate named `gate` lets this user through, for gates made
420    /// with `App::gate_async` (which may query the database) as well as
421    /// plain ones. Unknown gates deny.
422    pub async fn allows_async(&self, gate: &str) -> Result<bool> {
423        if let Some(allowed) = self.before(gate) {
424            return Ok(allowed);
425        }
426        if self.gates.gates.contains_key(gate) || self.grants.has_permission(gate) {
427            return Ok(self.allows(gate));
428        }
429        let Some(state) = &self.state else {
430            return Ok(false);
431        };
432        match state.async_gates.get(gate) {
433            Some(check) => check(self.user.as_ref().clone(), state.clone()).await,
434            None => Ok(false),
435        }
436    }
437
438    /// Like `allows_async`, but a refusal becomes a 403 response.
439    pub async fn gate_async(&self, gate: &str) -> Result {
440        if self.allows_async(gate).await? {
441            Ok(())
442        } else {
443            Err(Error::Forbidden)
444        }
445    }
446
447    /// The logged-in user.
448    pub fn user(&self) -> &User {
449        &self.user
450    }
451}
452
453impl<S: Send + Sync> FromRequestParts<S> for AuthUser {
454    type Rejection = Response;
455
456    async fn from_request_parts(parts: &mut Parts, _: &S) -> std::result::Result<Self, Response> {
457        match current(&parts.extensions) {
458            Some(user) => Ok(user),
459            None => Err(unauthenticated(parts)),
460        }
461    }
462}
463
464impl<S: Send + Sync> OptionalFromRequestParts<S> for AuthUser {
465    type Rejection = Infallible;
466
467    async fn from_request_parts(
468        parts: &mut Parts,
469        _: &S,
470    ) -> std::result::Result<Option<Self>, Infallible> {
471        Ok(current(&parts.extensions))
472    }
473}
474
475/// The request's user as an [`AuthUser`], for code outside a handler (the
476/// navigation menus a page draws).
477pub(crate) fn auth_user_of(current: &CurrentUser, state: &AppState) -> Option<AuthUser> {
478    Some(AuthUser {
479        user: current.user.clone()?,
480        gates: current.gates.clone(),
481        state: Some(state.clone()),
482        token_id: current.token_id,
483        abilities: current.abilities.clone(),
484        grants: current.grants.clone(),
485        role_names: std::sync::OnceLock::new(),
486    })
487}
488
489fn current(extensions: &axum::http::Extensions) -> Option<AuthUser> {
490    let current = extensions.get::<CurrentUser>()?;
491    Some(AuthUser {
492        user: current.user.clone()?,
493        gates: current.gates.clone(),
494        state: extensions.get::<AppState>().cloned(),
495        token_id: current.token_id,
496        abilities: current.abilities.clone(),
497        grants: current.grants.clone(),
498        role_names: std::sync::OnceLock::new(),
499    })
500}
501
502/// Logs `user` in for this session. With `remember` (usually
503/// `Some(state.config.remember_lifetime)`, "remember me"), the session lasts
504/// that long instead of `SESSION_LIFETIME`.
505pub fn login(session: &Session, user: &User, remember: Option<std::time::Duration>) -> Result {
506    session.regenerate_token();
507    session.put(AUTH_ID, user.id)?;
508    session.put(AUTH_HASH, fingerprint(&user.password))?;
509    session.put(AUTH_AT, unix_millis())?;
510    session.put(AUTH_SID, crate::crypto::random_token())?;
511    if let Some(lifetime) = remember {
512        session.set_lifetime(lifetime);
513    }
514    Ok(())
515}
516
517/// Logs this device out: ends the session (user, data and CSRF token), and
518/// remembers its id so a copy of the cookie stops working too. The user's
519/// other devices stay logged in; see [`logout_other_devices`] and
520/// [`User::revoke_sessions`].
521pub async fn logout(db: &Db, session: &Session) -> Result {
522    match (session.get::<i64>(AUTH_ID), session.get::<String>(AUTH_SID)) {
523        (Some(_), Some(sid)) => revoke_session(db, session, &sid).await?,
524        // Logged in before sessions had ids: end them all to be safe.
525        (Some(id), None) => {
526            user::revoke_sessions(db, id).await?;
527        }
528        _ => {}
529    }
530    session.flush();
531    Ok(())
532}
533
534/// Logs the user out everywhere except this device (e.g. "log out other
535/// devices", or after a password change).
536pub async fn logout_other_devices(db: &Db, session: &Session, user: &User) -> Result {
537    let cut_off = user::revoke_sessions(db, user.id).await?;
538    // Logged in again after the cut-off (even within the same millisecond),
539    // so this session survives it.
540    let lifetime = session
541        .lifetime()
542        .map(|minutes| std::time::Duration::from_secs(minutes * 60));
543    login(session, user, lifetime)?;
544    session.put(AUTH_AT, cut_off + 1)?;
545    Ok(())
546}
547
548/// Changes the user's password and keeps this session logged in; every
549/// other session ends.
550pub async fn change_password(
551    db: &Db,
552    session: &Session,
553    user: &mut User,
554    password: &str,
555) -> Result {
556    user.set_password(db, password).await?;
557    logout_other_devices(db, session, user).await
558}
559
560/// Denylists one session id until a copy of its cookie would have expired.
561async fn revoke_session(db: &Db, session: &Session, sid: &str) -> Result {
562    let minutes = session.lifetime().unwrap_or(60 * 24 * 30);
563    let expires = crate::db::now() + chrono::Duration::minutes(minutes as i64);
564    crate::db::sql("DELETE FROM revoked_sessions WHERE expires_at < ?")
565        .bind(crate::db::now())
566        .execute(db)
567        .await?;
568    crate::db::sql(
569        "INSERT INTO revoked_sessions (id, expires_at) SELECT ?, ? \
570         WHERE NOT EXISTS (SELECT 1 FROM revoked_sessions WHERE id = ?)",
571    )
572    .bind(sid)
573    .bind(expires)
574    .bind(sid)
575    .execute(db)
576    .await?;
577    Ok(())
578}
579
580pub(crate) fn unix_millis() -> i64 {
581    crate::clock::unix_millis()
582}
583
584/// Ties a session to the password it was logged in with, so changing the
585/// password logs out every other session.
586fn fingerprint(password_hash: &str) -> String {
587    use sha2::{Digest, Sha256};
588    let digest = Sha256::digest(password_hash.as_bytes());
589    digest.iter().take(16).map(|b| format!("{b:02x}")).collect()
590}
591
592/// Loads the session's user once per request for extractors, guards and templates.
593pub(crate) async fn middleware(
594    axum::extract::State(state): axum::extract::State<AppState>,
595    mut req: Request,
596    next: Next,
597) -> Response {
598    let bearer = req
599        .headers()
600        .get(AUTHORIZATION)
601        .and_then(|v| v.to_str().ok())
602        .and_then(|v| v.strip_prefix("Bearer "))
603        .map(str::to_owned);
604    let session = req.extensions().get::<Session>().cloned();
605    let mut device = None;
606    let (user, token) = match (&bearer, &session) {
607        (Some(bearer), _) if bearer.trim().starts_with('d') => {
608            match device::authenticate(&state.db, bearer.trim()).await {
609                Ok(found) => device = found.map(Arc::new),
610                Err(err) => tracing::error!(error = ?err, "could not check the device token"),
611            }
612            (None, None)
613        }
614        // Only a token that authenticates turns CSRF off: a wrong or unknown
615        // one leaves the request a guest's, with CSRF checked as usual.
616        (Some(bearer), _) => match tokens::authenticate(&state.db, bearer.trim()).await {
617            Ok(Some((user, token))) => (Some(user), Some(token)),
618            Ok(None) => (None, None),
619            Err(err) => {
620                tracing::error!(error = ?err, "could not check the API token");
621                (None, None)
622            }
623        },
624        (None, Some(session)) => (resolve(&state, session).await, None),
625        (None, None) => (None, None),
626    };
627    let grants = match &user {
628        Some(user) if state.gates.permissions => {
629            match permissions::grants(&state.db, user.id).await {
630                Ok(grants) => grants,
631                Err(err) => {
632                    tracing::error!(error = ?err, "could not load the user's roles");
633                    Grants::default()
634                }
635            }
636        }
637        _ => Grants::default(),
638    };
639    let grants = Arc::new(grants);
640    if let Some(user) = &user {
641        // For `User::has_role` in policies and `gate_before`, which get a
642        // plain `User`.
643        crate::context::set(CurrentGrants {
644            user_id: user.id,
645            grants: grants.clone(),
646        });
647    }
648    req.extensions_mut().insert(CurrentUser {
649        user: user.map(Arc::new),
650        gates: state.gates.clone(),
651        token_id: token.as_ref().map(|t| t.0),
652        abilities: token.and_then(|t| t.1).map(Arc::new),
653        device,
654        grants,
655    });
656    req.extensions_mut().insert(state);
657    next.run(req).await
658}
659
660async fn resolve(state: &AppState, session: &Session) -> Option<User> {
661    let id: i64 = session.get(AUTH_ID)?;
662    let hash: String = session.get(AUTH_HASH).unwrap_or_default();
663    let logged_in_at: i64 = session.get(AUTH_AT).unwrap_or(0);
664    let sid: String = session.get(AUTH_SID).unwrap_or_default();
665    match User::find_with_revocation(&state.db, id, &sid).await {
666        Ok(Some((user, revoked_at, session_revoked)))
667            if constant_time_eq(&fingerprint(&user.password), &hash)
668                && (revoked_at == 0 || logged_in_at > revoked_at)
669                && !session_revoked =>
670        {
671            Some(user)
672        }
673        Ok(_) => {
674            // Deleted user, changed password or logged out elsewhere: this
675            // session is no longer theirs.
676            session.remove(AUTH_ID);
677            session.remove(AUTH_HASH);
678            session.remove(AUTH_AT);
679            session.remove(AUTH_SID);
680            None
681        }
682        Err(err) => {
683            tracing::error!(error = ?err, "could not load the logged-in user");
684            None
685        }
686    }
687}
688
689fn wants_json(headers: &axum::http::HeaderMap) -> bool {
690    headers
691        .get(ACCEPT)
692        .and_then(|v| v.to_str().ok())
693        .is_some_and(|v| v.contains("application/json"))
694}
695
696fn path_or(state: Option<&AppState>, route: &str, fallback: &str) -> String {
697    state
698        .and_then(|s| s.url(route, &[]).ok())
699        .unwrap_or_else(|| fallback.to_owned())
700}
701
702/// Sends a guest to the login page, remembering where they were going.
703fn unauthenticated(parts: &Parts) -> Response {
704    if wants_json(&parts.headers) || parts.headers.contains_key(AUTHORIZATION) {
705        let body = serde_json::json!({ "message": "Unauthenticated." });
706        return (StatusCode::UNAUTHORIZED, axum::Json(body)).into_response();
707    }
708    let login = path_or(parts.extensions.get::<AppState>(), "login", "/login");
709    if let (Some(session), &Method::GET) = (parts.extensions.get::<Session>(), &parts.method) {
710        let intended = parts
711            .uri
712            .path_and_query()
713            .map(|p| p.as_str().to_owned())
714            .unwrap_or_else(|| "/".into());
715        let _ = session.put(INTENDED, intended);
716    }
717    if Htmx::from_headers(&parts.headers).request {
718        return HxRedirect(login).into_response();
719    }
720    Redirect::to(&login).into_response()
721}
722
723/// Route guard: only logged-in users. See `Routes::require_auth`.
724pub(crate) async fn require_auth(req: Request, next: Next) -> Response {
725    if current(req.extensions()).is_some() {
726        return next.run(req).await;
727    }
728    let (parts, _) = req.into_parts();
729    unauthenticated(&parts)
730}
731
732/// What a route guard asks of the logged-in user (`Routes::require_gate`,
733/// `require_role`, `require_permission`, `require_ability`).
734#[derive(Clone)]
735pub(crate) enum Requirement {
736    Gate(String),
737    Role(String),
738    Permission(String),
739    Ability(String),
740}
741
742/// Route guard: a guest is sent to log in; a user who doesn't meet
743/// `requirement` gets 403.
744pub(crate) async fn require(requirement: Arc<Requirement>, req: Request, next: Next) -> Response {
745    let Some(user) = current(req.extensions()) else {
746        let (parts, _) = req.into_parts();
747        return unauthenticated(&parts);
748    };
749    let allowed = match requirement.as_ref() {
750        Requirement::Gate(gate) => match user.allows_async(gate).await {
751            Ok(allowed) => allowed,
752            Err(err) => return err.into_response(),
753        },
754        Requirement::Role(role) => user.has_role(role),
755        Requirement::Permission(permission) => user.allows(permission),
756        Requirement::Ability(ability) => user.token_can(ability),
757    };
758    if allowed {
759        next.run(req).await
760    } else {
761        Error::Forbidden.into_response()
762    }
763}
764
765/// Route guard: only users who verified their email. See `Routes::require_verified`.
766pub(crate) async fn require_verified(req: Request, next: Next) -> Response {
767    let Some(user) = current(req.extensions()) else {
768        let (parts, _) = req.into_parts();
769        return unauthenticated(&parts);
770    };
771    if user.email_verified_at.is_some() {
772        return next.run(req).await;
773    }
774    if wants_json(req.headers()) || user_via_token(req.extensions()) {
775        let body = serde_json::json!({ "message": "Your email address is not verified." });
776        return (StatusCode::FORBIDDEN, axum::Json(body)).into_response();
777    }
778    let notice = path_or(
779        req.extensions().get::<AppState>(),
780        "verification.notice",
781        "/verify-email",
782    );
783    if Htmx::from_headers(req.headers()).request {
784        return HxRedirect(notice).into_response();
785    }
786    Redirect::to(&notice).into_response()
787}
788
789pub(crate) fn user_via_token(extensions: &axum::http::Extensions) -> bool {
790    extensions
791        .get::<CurrentUser>()
792        .is_some_and(|c| c.token_id.is_some() || c.device.is_some())
793}
794
795/// Route guard: only guests; logged-in users go to the `home` route.
796pub(crate) async fn guest_only(req: Request, next: Next) -> Response {
797    if current(req.extensions()).is_none() {
798        return next.run(req).await;
799    }
800    Redirect::to(&path_or(req.extensions().get::<AppState>(), "home", "/")).into_response()
801}
802
803/// Where to go after logging in: the page that asked for a login, else `fallback`.
804pub(crate) fn intended(session: &Session, fallback: String) -> String {
805    session
806        .pull::<String>(INTENDED)
807        .filter(|path| crate::htmx::is_local_path(path))
808        .unwrap_or(fallback)
809}
810
811#[cfg(test)]
812mod tests {
813    use super::*;
814
815    #[test]
816    fn fingerprints_are_short_and_stable() {
817        let a = fingerprint("$argon2id$v=19$abc");
818        assert_eq!(a.len(), 32);
819        assert_eq!(a, fingerprint("$argon2id$v=19$abc"));
820        assert_ne!(a, fingerprint("$argon2id$v=19$abd"));
821    }
822}