Skip to main content

tablo_core/auth/session/
lifetime.rs

1//! [`Sessions`]: how long a panel's sessions last, from sign-in and between requests.
2
3use std::time::Duration;
4
5use jiff::Timestamp;
6
7use super::{AuthSession, SESSION_LIFETIME};
8use crate::{Auth, PanelUser};
9
10/// How long a panel's sessions last, set by [`Auth::sessions`]: seven days from sign-in by
11/// default, however long the user stays away meanwhile.
12///
13/// ```rust
14/// # use std::time::Duration;
15/// # use tablo_core::{Auth, Sessions};
16/// // A back office: sign in again each working day, and after half an hour away.
17/// let auth = Auth::password().sessions(
18///     Sessions::new()
19///         .lifetime(Duration::from_secs(10 * 60 * 60))
20///         .idle_timeout(Duration::from_secs(30 * 60)),
21/// );
22/// # let _ = auth;
23/// ```
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub struct Sessions {
26    lifetime: Duration,
27    idle: Option<Duration>,
28}
29
30/// The shortest [`Sessions::lifetime`] and [`Sessions::idle_timeout`]: under it a user could not
31/// finish signing in.
32const SHORTEST: Duration = Duration::from_mins(1);
33
34impl Sessions {
35    /// Sessions that last [`SESSION_LIFETIME`] from sign-in, with no idle timeout.
36    #[must_use]
37    pub fn new() -> Self {
38        Self {
39            lifetime: SESSION_LIFETIME,
40            idle: None,
41        }
42    }
43
44    /// How long a session lasts from the sign-in that started it, whatever the user does
45    /// meanwhile; never under a minute.
46    ///
47    /// It holds for the sessions already open: one older than a shortened lifetime ends on its
48    /// next request. A credential change starts the lifetime again, with the session it issues.
49    #[must_use]
50    pub fn lifetime(mut self, lifetime: Duration) -> Self {
51        self.lifetime = lifetime.max(SHORTEST);
52        self
53    }
54
55    /// Ends a session once `idle` passes without a request from it, before its
56    /// [`lifetime`](Self::lifetime) does; never under a minute. Off by default.
57    ///
58    /// Each request the panel's gate admits counts, a background one included; an open page that
59    /// sends none, such as one showing the notification bell, does not. The session row records
60    /// the end, moved forward at most once per tenth of `idle`, capped at five minutes, so a
61    /// session may end that much early. A session opened before the timeout was set ends `idle`
62    /// after its next request.
63    #[must_use]
64    pub fn idle_timeout(mut self, idle: Duration) -> Self {
65        self.idle = Some(idle.max(SHORTEST));
66        self
67    }
68
69    /// The lifetime: what a new session's cookie and row last.
70    pub(in crate::auth) fn lasts(&self) -> Duration {
71        self.lifetime
72    }
73
74    /// When a session starting at `now` first ends: the idle timeout, or the lifetime.
75    pub(in crate::auth) fn first_end(&self, now: Timestamp) -> Timestamp {
76        later(now, self.idle.unwrap_or(self.lifetime).min(self.lifetime))
77    }
78
79    /// What a request at `now` makes of `row`: whether it still stands, and the end to record.
80    pub(in crate::auth) fn check(&self, row: &AuthSession, now: Timestamp) -> Standing {
81        let last = later(row.created_at, self.lifetime);
82        if row.expires_at <= now || last <= now {
83            return Standing::Ended;
84        }
85        let Some(idle) = self.idle else {
86            return Standing::Live(None);
87        };
88        let end = later(now, idle).min(last);
89        let slack = (idle / 10).min(Duration::from_mins(5));
90        let moved = end.duration_since(row.expires_at).unsigned_abs() > slack;
91        Standing::Live(moved.then_some(end))
92    }
93}
94
95impl Default for Sessions {
96    fn default() -> Self {
97        Self::new()
98    }
99}
100
101/// What [`Sessions::check`] finds of a session row.
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub(in crate::auth) enum Standing {
104    /// Past its lifetime or its idle timeout.
105    Ended,
106    /// Standing, with the end a request that counts as activity records, when it moved.
107    Live(Option<Timestamp>),
108}
109
110/// `from` plus `span`, or the latest timestamp when that overflows.
111fn later(from: Timestamp, span: Duration) -> Timestamp {
112    from.checked_add(span).unwrap_or(Timestamp::MAX)
113}
114
115impl<U: PanelUser> Auth<U> {
116    /// How long the panel's sessions last: see [`Sessions`]. The default is seven days from
117    /// sign-in, with no idle timeout.
118    #[must_use]
119    pub fn sessions(mut self, sessions: Sessions) -> Self {
120        self.config.sessions = sessions;
121        self
122    }
123}
124
125#[cfg(test)]
126mod tests;