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.
250/// The layout of Renox's signed-in pages (the account page, the password
251/// confirmation, the notifications): the app's `layouts/app.html` when it
252/// has one, so they keep the app's shell and menus, else Renox's sign-in
253/// layout (#88). The sign-in pages themselves always use the latter.
254pub(crate) fn signed_in_layout(state: &AppState) -> &'static str {
255    if state.views.exists("layouts/app.html") {
256        "layouts/app.html"
257    } else {
258        "renox/auth/layout.html"
259    }
260}
261
262pub(crate) fn current_user_id() -> Option<i64> {
263    crate::context::get::<CurrentGrants>().map(|current| current.user_id)
264}
265
266fn current_grants(user_id: i64) -> Option<Arc<Grants>> {
267    crate::context::get::<CurrentGrants>()
268        .filter(|current| current.user_id == user_id)
269        .map(|current| current.grants)
270}
271
272pub(crate) type AsyncGate = Arc<
273    dyn Fn(
274            User,
275            AppState,
276        ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<bool>> + Send>>
277        + Send
278        + Sync,
279>;
280
281/// The logged-in user of the current request, if any; set by Renox's auth
282/// middleware for every request.
283#[derive(Clone)]
284pub(crate) struct CurrentUser {
285    pub user: Option<Arc<User>>,
286    pub gates: Gates,
287    /// The API token of `Authorization: Bearer`, when that authenticated
288    /// the request (so CSRF doesn't apply).
289    pub token_id: Option<i64>,
290    /// That token's abilities; `None` for every ability (sessions, and
291    /// tokens made without a list).
292    pub abilities: Option<Arc<Vec<String>>>,
293    /// The device a device token authenticated (no user then).
294    pub device: Option<Arc<Device>>,
295    pub grants: Arc<Grants>,
296}
297
298/// The logged-in user. Requests without one are sent to the `login` route
299/// (HTMX requests via `HX-Redirect`) or get 401 when they want JSON. Use
300/// `Option<AuthUser>` where logging in is optional.
301#[derive(Clone)]
302pub struct AuthUser {
303    user: Arc<User>,
304    gates: Gates,
305    state: Option<AppState>,
306    token_id: Option<i64>,
307    abilities: Option<Arc<Vec<String>>>,
308    grants: Arc<Grants>,
309    /// `role_names`, worked out the first time it's asked.
310    role_names: std::sync::OnceLock<Vec<String>>,
311}
312
313impl Deref for AuthUser {
314    type Target = User;
315
316    fn deref(&self) -> &User {
317        &self.user
318    }
319}
320
321impl AuthUser {
322    /// The id of the API token this request logged in with
323    /// (`Authorization: Bearer`), or `None` for a session login. Revoke just
324    /// that token on "log out" from an app: `user.revoke_token(&db, id)`.
325    pub fn token_id(&self) -> Option<i64> {
326        self.token_id
327    }
328
329    /// Whether the API token this request logged in with may do `ability`
330    /// (`create_token_with(.., &["orders:read"], ..)`). Sessions, and tokens
331    /// made without a list, may do everything.
332    pub fn token_can(&self, ability: &str) -> bool {
333        self.abilities
334            .as_ref()
335            .is_none_or(|list| list.iter().any(|a| a == ability || a == "*"))
336    }
337
338    /// Whether the user has `role` (the `Permissions` module): a global
339    /// role, or one given in the request's scope (`permissions::set_scope`),
340    /// within its dates.
341    pub fn has_role(&self, role: &str) -> bool {
342        self.grants.has_role(role)
343    }
344
345    /// Whether one of the user's roles grants `permission` (the
346    /// `Permissions` module; the same roles as `has_role`).
347    /// `allows(permission)` also asks `App::gate_before`.
348    pub fn has_permission(&self, permission: &str) -> bool {
349        self.grants.has_permission(permission)
350    }
351
352    /// Whether a role of the user grants `permission` now, globally or in
353    /// at least one scope, whatever the request's scope. For showing
354    /// things such as menu links to someone who holds the permission only
355    /// through a scoped role; the page itself then filters by scope
356    /// (`scopes_with`, `has_permission_in`). `false` without the
357    /// `Permissions` module.
358    pub fn has_permission_anywhere(&self, permission: &str) -> bool {
359        self.grants.has_permission_anywhere(permission)
360    }
361
362    /// Whether the user has `role` globally or in `scope` (the record's,
363    /// not the request's), within its dates.
364    pub fn has_role_in(&self, role: &str, scope: &permissions::Scope) -> bool {
365        self.grants.has_role_in(role, Some(scope))
366    }
367
368    /// Whether a global role of the user, or one given in `scope` (the
369    /// record's, not the request's), grants `permission` now; for
370    /// policies and handlers that work on one record.
371    pub fn has_permission_in(&self, permission: &str, scope: &permissions::Scope) -> bool {
372        self.grants.has_permission_in(permission, Some(scope))
373    }
374
375    /// The records of model `M` in which the user holds `permission`:
376    /// `Scopes::All` when a global role grants it, else their keys. See
377    /// [`User::scopes_with`].
378    pub fn scopes_with<M: crate::db::Model>(
379        &self,
380        permission: &str,
381    ) -> permissions::Scopes<M::Key> {
382        self.grants.scopes_with::<M>(permission)
383    }
384
385    /// The user's roles (the `Permissions` module) in effect: the global
386    /// ones plus those in the request's scope, sorted, as they were the
387    /// first time this was asked.
388    pub fn role_names(&self) -> &[String] {
389        self.role_names.get_or_init(|| self.grants.roles())
390    }
391
392    /// Whether the policy of `target` allows `ability` (after
393    /// `App::gate_before`).
394    pub fn can(&self, ability: &str, target: &impl Policy) -> bool {
395        self.before(ability)
396            .unwrap_or_else(|| target.allows(&self.user, ability))
397    }
398
399    fn before(&self, ability: &str) -> Option<bool> {
400        self.gates
401            .before
402            .as_ref()
403            .and_then(|before| before(&self.user, ability))
404    }
405
406    /// Like `can`, but a refusal becomes a 403 response.
407    pub fn authorize(&self, ability: &str, target: &impl Policy) -> Result {
408        if self.can(ability, target) {
409            Ok(())
410        } else {
411            Err(Error::Forbidden)
412        }
413    }
414
415    /// Whether the gate named `gate` lets this user through: `gate_before`,
416    /// then the gate, then the user's permissions of that name. Unknown
417    /// names deny.
418    pub fn allows(&self, gate: &str) -> bool {
419        self.gates.check(&self.user, &self.grants, gate)
420    }
421
422    /// Like `allows`, but a refusal becomes a 403 response.
423    pub fn gate(&self, gate: &str) -> Result {
424        if self.allows(gate) {
425            Ok(())
426        } else {
427            Err(Error::Forbidden)
428        }
429    }
430
431    /// Whether the gate named `gate` lets this user through, for gates made
432    /// with `App::gate_async` (which may query the database) as well as
433    /// plain ones. Unknown gates deny.
434    pub async fn allows_async(&self, gate: &str) -> Result<bool> {
435        if let Some(allowed) = self.before(gate) {
436            return Ok(allowed);
437        }
438        if self.gates.gates.contains_key(gate) || self.grants.has_permission(gate) {
439            return Ok(self.allows(gate));
440        }
441        let Some(state) = &self.state else {
442            return Ok(false);
443        };
444        match state.async_gates.get(gate) {
445            Some(check) => check(self.user.as_ref().clone(), state.clone()).await,
446            None => Ok(false),
447        }
448    }
449
450    /// Like `allows_async`, but a refusal becomes a 403 response.
451    pub async fn gate_async(&self, gate: &str) -> Result {
452        if self.allows_async(gate).await? {
453            Ok(())
454        } else {
455            Err(Error::Forbidden)
456        }
457    }
458
459    /// The logged-in user.
460    pub fn user(&self) -> &User {
461        &self.user
462    }
463}
464
465impl<S: Send + Sync> FromRequestParts<S> for AuthUser {
466    type Rejection = Response;
467
468    async fn from_request_parts(parts: &mut Parts, _: &S) -> std::result::Result<Self, Response> {
469        match current(&parts.extensions) {
470            Some(user) => Ok(user),
471            None => Err(unauthenticated(parts)),
472        }
473    }
474}
475
476impl<S: Send + Sync> OptionalFromRequestParts<S> for AuthUser {
477    type Rejection = Infallible;
478
479    async fn from_request_parts(
480        parts: &mut Parts,
481        _: &S,
482    ) -> std::result::Result<Option<Self>, Infallible> {
483        Ok(current(&parts.extensions))
484    }
485}
486
487/// The request's user as an [`AuthUser`], for code outside a handler (the
488/// navigation menus a page draws).
489pub(crate) fn auth_user_of(current: &CurrentUser, state: &AppState) -> Option<AuthUser> {
490    Some(AuthUser {
491        user: current.user.clone()?,
492        gates: current.gates.clone(),
493        state: Some(state.clone()),
494        token_id: current.token_id,
495        abilities: current.abilities.clone(),
496        grants: current.grants.clone(),
497        role_names: std::sync::OnceLock::new(),
498    })
499}
500
501fn current(extensions: &axum::http::Extensions) -> Option<AuthUser> {
502    let current = extensions.get::<CurrentUser>()?;
503    Some(AuthUser {
504        user: current.user.clone()?,
505        gates: current.gates.clone(),
506        state: extensions.get::<AppState>().cloned(),
507        token_id: current.token_id,
508        abilities: current.abilities.clone(),
509        grants: current.grants.clone(),
510        role_names: std::sync::OnceLock::new(),
511    })
512}
513
514/// Logs `user` in for this session. With `remember` (usually
515/// `Some(state.config.remember_lifetime)`, "remember me"), the session lasts
516/// that long instead of `SESSION_LIFETIME`.
517pub fn login(session: &Session, user: &User, remember: Option<std::time::Duration>) -> Result {
518    session.regenerate_token();
519    session.put(AUTH_ID, user.id)?;
520    session.put(AUTH_HASH, fingerprint(&user.password))?;
521    session.put(AUTH_AT, unix_millis())?;
522    session.put(AUTH_SID, crate::crypto::random_token())?;
523    if let Some(lifetime) = remember {
524        session.set_lifetime(lifetime);
525    }
526    Ok(())
527}
528
529/// Logs this device out: ends the session (user, data and CSRF token), and
530/// remembers its id so a copy of the cookie stops working too. The user's
531/// other devices stay logged in; see [`logout_other_devices`] and
532/// [`User::revoke_sessions`].
533pub async fn logout(db: &Db, session: &Session) -> Result {
534    match (session.get::<i64>(AUTH_ID), session.get::<String>(AUTH_SID)) {
535        (Some(_), Some(sid)) => revoke_session(db, session, &sid).await?,
536        // Logged in before sessions had ids: end them all to be safe.
537        (Some(id), None) => {
538            user::revoke_sessions(db, id).await?;
539        }
540        _ => {}
541    }
542    session.flush();
543    Ok(())
544}
545
546/// Logs the user out everywhere except this device (e.g. "log out other
547/// devices", or after a password change).
548pub async fn logout_other_devices(db: &Db, session: &Session, user: &User) -> Result {
549    let cut_off = user::revoke_sessions(db, user.id).await?;
550    // Logged in again after the cut-off (even within the same millisecond),
551    // so this session survives it.
552    let lifetime = session
553        .lifetime()
554        .map(|minutes| std::time::Duration::from_secs(minutes * 60));
555    login(session, user, lifetime)?;
556    session.put(AUTH_AT, cut_off + 1)?;
557    Ok(())
558}
559
560/// Changes the user's password and keeps this session logged in; every
561/// other session ends.
562pub async fn change_password(
563    db: &Db,
564    session: &Session,
565    user: &mut User,
566    password: &str,
567) -> Result {
568    user.set_password(db, password).await?;
569    logout_other_devices(db, session, user).await
570}
571
572/// Denylists one session id until a copy of its cookie would have expired.
573async fn revoke_session(db: &Db, session: &Session, sid: &str) -> Result {
574    let minutes = session.lifetime().unwrap_or(60 * 24 * 30);
575    let expires = crate::db::now() + chrono::Duration::minutes(minutes as i64);
576    crate::db::sql("DELETE FROM revoked_sessions WHERE expires_at < ?")
577        .bind(crate::db::now())
578        .execute(db)
579        .await?;
580    crate::db::sql(
581        "INSERT INTO revoked_sessions (id, expires_at) SELECT ?, ? \
582         WHERE NOT EXISTS (SELECT 1 FROM revoked_sessions WHERE id = ?)",
583    )
584    .bind(sid)
585    .bind(expires)
586    .bind(sid)
587    .execute(db)
588    .await?;
589    Ok(())
590}
591
592pub(crate) fn unix_millis() -> i64 {
593    crate::clock::unix_millis()
594}
595
596/// Ties a session to the password it was logged in with, so changing the
597/// password logs out every other session.
598fn fingerprint(password_hash: &str) -> String {
599    use sha2::{Digest, Sha256};
600    let digest = Sha256::digest(password_hash.as_bytes());
601    digest.iter().take(16).map(|b| format!("{b:02x}")).collect()
602}
603
604/// Loads the session's user once per request for extractors, guards and templates.
605pub(crate) async fn middleware(
606    axum::extract::State(state): axum::extract::State<AppState>,
607    mut req: Request,
608    next: Next,
609) -> Response {
610    let bearer = req
611        .headers()
612        .get(AUTHORIZATION)
613        .and_then(|v| v.to_str().ok())
614        .and_then(|v| v.strip_prefix("Bearer "))
615        .map(str::to_owned);
616    let session = req.extensions().get::<Session>().cloned();
617    let mut device = None;
618    let (user, token) = match (&bearer, &session) {
619        (Some(bearer), _) if bearer.trim().starts_with('d') => {
620            match device::authenticate(&state.db, bearer.trim()).await {
621                Ok(found) => device = found.map(Arc::new),
622                Err(err) => tracing::error!(error = ?err, "could not check the device token"),
623            }
624            (None, None)
625        }
626        // Only a token that authenticates turns CSRF off: a wrong or unknown
627        // one leaves the request a guest's, with CSRF checked as usual.
628        (Some(bearer), _) => match tokens::authenticate(&state.db, bearer.trim()).await {
629            Ok(Some((user, token))) => (Some(user), Some(token)),
630            Ok(None) => (None, None),
631            Err(err) => {
632                tracing::error!(error = ?err, "could not check the API token");
633                (None, None)
634            }
635        },
636        (None, Some(session)) => (resolve(&state, session).await, None),
637        (None, None) => (None, None),
638    };
639    let grants = match &user {
640        Some(user) if state.gates.permissions => {
641            match permissions::grants(&state.db, user.id).await {
642                Ok(grants) => grants,
643                Err(err) => {
644                    tracing::error!(error = ?err, "could not load the user's roles");
645                    Grants::default()
646                }
647            }
648        }
649        _ => Grants::default(),
650    };
651    let grants = Arc::new(grants);
652    if let Some(user) = &user {
653        // For `User::has_role` in policies and `gate_before`, which get a
654        // plain `User`.
655        crate::context::set(CurrentGrants {
656            user_id: user.id,
657            grants: grants.clone(),
658        });
659    }
660    req.extensions_mut().insert(CurrentUser {
661        user: user.map(Arc::new),
662        gates: state.gates.clone(),
663        token_id: token.as_ref().map(|t| t.0),
664        abilities: token.and_then(|t| t.1).map(Arc::new),
665        device,
666        grants,
667    });
668    req.extensions_mut().insert(state);
669    next.run(req).await
670}
671
672async fn resolve(state: &AppState, session: &Session) -> Option<User> {
673    let id: i64 = session.get(AUTH_ID)?;
674    let hash: String = session.get(AUTH_HASH).unwrap_or_default();
675    let logged_in_at: i64 = session.get(AUTH_AT).unwrap_or(0);
676    let sid: String = session.get(AUTH_SID).unwrap_or_default();
677    match User::find_with_revocation(&state.db, id, &sid).await {
678        Ok(Some((user, revoked_at, session_revoked)))
679            if constant_time_eq(&fingerprint(&user.password), &hash)
680                && (revoked_at == 0 || logged_in_at > revoked_at)
681                && !session_revoked =>
682        {
683            Some(user)
684        }
685        Ok(_) => {
686            // Deleted user, changed password or logged out elsewhere: this
687            // session is no longer theirs.
688            session.remove(AUTH_ID);
689            session.remove(AUTH_HASH);
690            session.remove(AUTH_AT);
691            session.remove(AUTH_SID);
692            None
693        }
694        Err(err) => {
695            tracing::error!(error = ?err, "could not load the logged-in user");
696            None
697        }
698    }
699}
700
701fn wants_json(headers: &axum::http::HeaderMap) -> bool {
702    headers
703        .get(ACCEPT)
704        .and_then(|v| v.to_str().ok())
705        .is_some_and(|v| v.contains("application/json"))
706}
707
708fn path_or(state: Option<&AppState>, route: &str, fallback: &str) -> String {
709    state
710        .and_then(|s| s.url(route, &[]).ok())
711        .unwrap_or_else(|| fallback.to_owned())
712}
713
714/// Sends a guest to the login page, remembering where they were going.
715fn unauthenticated(parts: &Parts) -> Response {
716    if wants_json(&parts.headers) || parts.headers.contains_key(AUTHORIZATION) {
717        let body = serde_json::json!({ "message": "Unauthenticated." });
718        return (StatusCode::UNAUTHORIZED, axum::Json(body)).into_response();
719    }
720    let login = path_or(parts.extensions.get::<AppState>(), "login", "/login");
721    if let (Some(session), &Method::GET) = (parts.extensions.get::<Session>(), &parts.method) {
722        let intended = parts
723            .uri
724            .path_and_query()
725            .map(|p| p.as_str().to_owned())
726            .unwrap_or_else(|| "/".into());
727        let _ = session.put(INTENDED, intended);
728    }
729    if Htmx::from_headers(&parts.headers).request {
730        return HxRedirect(login).into_response();
731    }
732    Redirect::to(&login).into_response()
733}
734
735/// Route guard: only logged-in users. See `Routes::require_auth`.
736pub(crate) async fn require_auth(req: Request, next: Next) -> Response {
737    if current(req.extensions()).is_some() {
738        return next.run(req).await;
739    }
740    let (parts, _) = req.into_parts();
741    unauthenticated(&parts)
742}
743
744/// What a route guard asks of the logged-in user (`Routes::require_gate`,
745/// `require_role`, `require_permission`, `require_ability`).
746#[derive(Clone)]
747pub(crate) enum Requirement {
748    Gate(String),
749    Role(String),
750    Permission(String),
751    Ability(String),
752}
753
754/// Route guard: a guest is sent to log in; a user who doesn't meet
755/// `requirement` gets 403.
756pub(crate) async fn require(requirement: Arc<Requirement>, req: Request, next: Next) -> Response {
757    let Some(user) = current(req.extensions()) else {
758        let (parts, _) = req.into_parts();
759        return unauthenticated(&parts);
760    };
761    let allowed = match requirement.as_ref() {
762        Requirement::Gate(gate) => match user.allows_async(gate).await {
763            Ok(allowed) => allowed,
764            Err(err) => return err.into_response(),
765        },
766        Requirement::Role(role) => user.has_role(role),
767        Requirement::Permission(permission) => user.allows(permission),
768        Requirement::Ability(ability) => user.token_can(ability),
769    };
770    if allowed {
771        next.run(req).await
772    } else {
773        Error::Forbidden.into_response()
774    }
775}
776
777/// Route guard: only users who verified their email. See `Routes::require_verified`.
778pub(crate) async fn require_verified(req: Request, next: Next) -> Response {
779    let Some(user) = current(req.extensions()) else {
780        let (parts, _) = req.into_parts();
781        return unauthenticated(&parts);
782    };
783    if user.email_verified_at.is_some() {
784        return next.run(req).await;
785    }
786    if wants_json(req.headers()) || user_via_token(req.extensions()) {
787        let body = serde_json::json!({ "message": "Your email address is not verified." });
788        return (StatusCode::FORBIDDEN, axum::Json(body)).into_response();
789    }
790    let notice = path_or(
791        req.extensions().get::<AppState>(),
792        "verification.notice",
793        "/verify-email",
794    );
795    if Htmx::from_headers(req.headers()).request {
796        return HxRedirect(notice).into_response();
797    }
798    Redirect::to(&notice).into_response()
799}
800
801pub(crate) fn user_via_token(extensions: &axum::http::Extensions) -> bool {
802    extensions
803        .get::<CurrentUser>()
804        .is_some_and(|c| c.token_id.is_some() || c.device.is_some())
805}
806
807/// Route guard: only guests; logged-in users go to the `home` route.
808pub(crate) async fn guest_only(req: Request, next: Next) -> Response {
809    if current(req.extensions()).is_none() {
810        return next.run(req).await;
811    }
812    Redirect::to(&path_or(req.extensions().get::<AppState>(), "home", "/")).into_response()
813}
814
815/// Where to go after logging in: the page that asked for a login, else `fallback`.
816pub(crate) fn intended(session: &Session, fallback: String) -> String {
817    session
818        .pull::<String>(INTENDED)
819        .filter(|path| crate::htmx::is_local_path(path))
820        .unwrap_or(fallback)
821}
822
823#[cfg(test)]
824mod tests {
825    use super::*;
826
827    #[test]
828    fn fingerprints_are_short_and_stable() {
829        let a = fingerprint("$argon2id$v=19$abc");
830        assert_eq!(a.len(), 32);
831        assert_eq!(a, fingerprint("$argon2id$v=19$abc"));
832        assert_ne!(a, fingerprint("$argon2id$v=19$abd"));
833    }
834}