Skip to main content

instapi360_cloud/
session.rs

1//! Session / token state and the pluggable persistence trait.
2//!
3//! A [`Session`] holds the tokens returned by login. Persistence is delegated
4//! to a [`SessionStore`] the caller provides — the CLI uses a JSON file (and
5//! optionally the OS keyring); a future Android build uses
6//! EncryptedSharedPreferences. Keeping this behind a trait keeps the core crate
7//! free of any filesystem assumption.
8
9use serde::{Deserialize, Serialize};
10
11/// The bearer material for authenticated requests.
12#[derive(Debug, Clone, Serialize, Deserialize)]
13pub struct Session {
14    /// Sent as `X-User-Token`.
15    pub user_token: String,
16    /// Used with `/account/v2/refreshToken` to mint a fresh `user_token`.
17    pub refresh_token: Option<String>,
18    /// Unix seconds at which `user_token` expires, if known.
19    pub expires_at: Option<i64>,
20    /// The account id this session belongs to (for cache/scoping).
21    pub user_id: Option<String>,
22}
23
24impl Session {
25    /// Build a session from just a captured `X-User-Token` (auth strategy 5c).
26    pub fn from_token(user_token: impl Into<String>) -> Self {
27        Session {
28            user_token: user_token.into(),
29            refresh_token: None,
30            expires_at: None,
31            user_id: None,
32        }
33    }
34
35    /// True when the token is known to be expired at `now_unix`.
36    pub fn is_expired(&self, now_unix: i64) -> bool {
37        self.expires_at.map(|e| now_unix >= e).unwrap_or(false)
38    }
39}
40
41/// Persistence for a [`Session`]. Implementations decide *where* (file, keyring,
42/// Android secure storage). All methods are synchronous and cheap.
43pub trait SessionStore: Send + Sync {
44    fn load(&self) -> crate::Result<Option<Session>>;
45    fn save(&self, session: &Session) -> crate::Result<()>;
46    fn clear(&self) -> crate::Result<()>;
47}