forge
Explore
Log in

Don't you dare go Hollow

im_old

Clone
★ 0

0 watching0 forksRustGPL-3.0755.6 KiB84318dcTahinli2 months ago77 commits

stats.rs151 lines, 5.6 KiBHistoryRawDownload
1//! The profile page's statistics: how often this identity has been used,
2//! and what is holding it right now.
3//!
4//! Everything here derives from rows the system already keeps — a session
5//! row per sign-in, an app-session row per app a sign-in was handed to. No
6//! counters, nothing to drift: the page's numbers are the tables, read.
7
8use crate::model::UserId;
9use crate::store::{self, Result, Store, backend};
10
11/// One person's counts, for the profile section of the signed-in landing.
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct ProfileStats {
14 /// Every sign-in ever: one central-session row is written per login.
15 pub sign_ins: u64,
16 /// Sessions neither revoked nor expired — the devices that could act
17 /// as this person right now.
18 pub active_sessions: u64,
19 /// Apps holding a live token for this person (distinct OIDC clients
20 /// with an unrevoked, unexpired app session).
21 pub connected_apps: u64,
22}
23
24/// Reads the three counts. One round-trip: the tables are small, and the
25/// landing is the only reader.
26pub async fn profile_stats(store: &Store, user: &UserId) -> Result<ProfileStats> {
27 let conn = store.conn.lock().await;
28 let id = user.to_string();
29 let now = store::stamp(store::now())?;
30 let mut rows = conn
31 .query(
32 "SELECT \
33 (SELECT COUNT(*) FROM sessions WHERE user_id = ?1), \
34 (SELECT COUNT(*) FROM sessions \
35 WHERE user_id = ?1 AND revoked_at IS NULL AND expires_at > ?2), \
36 (SELECT COUNT(DISTINCT client_id) FROM app_sessions \
37 WHERE user_id = ?1 AND revoked_at IS NULL AND expires_at > ?2)",
38 turso::params![id, now],
39 )
40 .await
41 .map_err(backend)?;
42 let row = rows
43 .next()
44 .await
45 .map_err(backend)?
46 .ok_or_else(|| backend("counts query returned no row"))?;
47 Ok(ProfileStats {
48 sign_ins: store::int(&row, 0)? as u64,
49 active_sessions: store::int(&row, 1)? as u64,
50 connected_apps: store::int(&row, 2)? as u64,
51 })
52}
53
54#[cfg(test)]
55mod tests {
56 use super::*;
57 use crate::accounts::{create_invite, create_user_from_invite};
58 use std::path::Path;
59
60 async fn fixture() -> (Store, UserId) {
61 let store = Store::open(Path::new(":memory:")).await.unwrap();
62 let invite = create_invite(&store, "ann@example.com", None, false)
63 .await
64 .unwrap();
65 let user = create_user_from_invite(&store, invite.expose(), "Ann", "tDLr9!mZQ2xv")
66 .await
67 .unwrap();
68 (store, user.id)
69 }
70
71 /// Stamps relative to now, so "expired" and "live" rows stay on their
72 /// own sides of the comparison whatever the clock says at test time.
73 fn stamp_in(hours: i64) -> String {
74 store::stamp(store::now() + time::Duration::hours(hours)).unwrap()
75 }
76
77 #[tokio::test]
78 async fn counts_reflect_the_tables() {
79 let (store, user_id) = fixture().await;
80 let id = user_id.to_string();
81 {
82 let conn = store.conn.lock().await;
83 // Three sign-ins: one expired, one revoked, one live.
84 for (hash, expires, revoked) in [
85 ("h-expired", stamp_in(-1), None),
86 ("h-revoked", stamp_in(24), Some(stamp_in(-1))),
87 ("h-live", stamp_in(24), None),
88 ] {
89 conn.execute(
90 "INSERT INTO sessions (token_hash, user_id, created_at, expires_at, revoked_at) \
91 VALUES (?1, ?2, ?3, ?4, ?5)",
92 turso::params![hash, id.clone(), stamp_in(-24), expires, revoked],
93 )
94 .await
95 .unwrap();
96 }
97 // A client the app sessions point at, then three app sessions:
98 // two live for one client (counts once), one revoked for another.
99 conn.execute(
100 "INSERT INTO oidc_clients (client_id, name, secret_hash, redirect_uris, created_at) \
101 VALUES ('client-a', 'A', 'x', '[]', ?1)",
102 turso::params![stamp_in(-24)],
103 )
104 .await
105 .unwrap();
106 conn.execute(
107 "INSERT INTO oidc_clients (client_id, name, secret_hash, redirect_uris, created_at) \
108 VALUES ('client-b', 'B', 'x', '[]', ?1)",
109 turso::params![stamp_in(-24)],
110 )
111 .await
112 .unwrap();
113 for (hash, client, expires, revoked) in [
114 ("a1", "client-a", stamp_in(24), None),
115 ("a2", "client-a", stamp_in(24), None),
116 ("b1", "client-b", stamp_in(24), Some(stamp_in(-1))),
117 ] {
118 conn.execute(
119 "INSERT INTO app_sessions \
120 (token_hash, user_id, client_id, session_hash, created_at, expires_at, revoked_at) \
121 VALUES (?1, ?2, ?3, 'h-live', ?4, ?5, ?6)",
122 turso::params![hash, id.clone(), client, stamp_in(-24), expires, revoked],
123 )
124 .await
125 .unwrap();
126 }
127 }
128 let stats = profile_stats(&store, &user_id).await.unwrap();
129 assert_eq!(
130 stats,
131 ProfileStats {
132 sign_ins: 3,
133 active_sessions: 1,
134 connected_apps: 1,
135 }
136 );
137 }
138
139 #[tokio::test]
140 async fn a_fresh_account_reads_zero() {
141 let (store, user_id) = fixture().await;
142 assert_eq!(
143 profile_stats(&store, &user_id).await.unwrap(),
144 ProfileStats {
145 sign_ins: 0,
146 active_sessions: 0,
147 connected_apps: 0,
148 }
149 );
150 }
151}