forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

session.rs84 lines, 2.1 KiBHistoryRawDownload
1use uuid::Uuid;
2
3use crate::domain::monotonic_id::next_uuid;
4use crate::domain::timestamp::Timestamp;
5use crate::domain::user::UserId;
6use crate::error::AppError;
7
8/// Typed session row id. A UUIDv7 minted by the process-wide monotonic
9/// generator. (The table is `user_session` in PostgreSQL — the Rust type
10/// keeps its name.)
11#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)]
12#[sqlx(transparent)]
13pub struct SessionId(Uuid);
14
15impl SessionId {
16 pub fn generate() -> Self {
17 Self(next_uuid())
18 }
19
20 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
21 /// cannot take the newtype. Static `query!` binds take `self` directly.
22 pub fn uuid(&self) -> Uuid {
23 self.0
24 }
25
26 /// The hyphenated wire form.
27 #[allow(dead_code)]
28 pub fn key(&self) -> String {
29 self.0.to_string()
30 }
31}
32
33/// A random, opaque session token (64 hex chars).
34#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
35#[sqlx(transparent)]
36pub struct SessionToken(String);
37
38impl SessionToken {
39 pub fn generate() -> Result<Self, AppError> {
40 let mut bytes = [0u8; 32];
41 getrandom::fill(&mut bytes).map_err(|e| AppError::Internal(format!("rng: {e}")))?;
42 Ok(Self(hex::encode(bytes)))
43 }
44
45 pub fn as_str(&self) -> &str {
46 &self.0
47 }
48}
49
50/// Fields are crate-visible: [`crate::db::session`] mints the rows on login.
51#[derive(Debug, Clone, sqlx::FromRow)]
52pub struct Session {
53 #[sqlx(rename = "app_user")]
54 pub(crate) user: UserId,
55 pub(crate) token: SessionToken,
56 pub(crate) expires_at: Timestamp,
57}
58
59impl Session {
60 pub fn token(&self) -> &SessionToken {
61 &self.token
62 }
63
64 pub fn user(&self) -> &UserId {
65 &self.user
66 }
67
68 pub fn is_expired(&self) -> bool {
69 self.expires_at.is_past()
70 }
71}
72
73#[cfg(test)]
74mod tests {
75 use super::*;
76
77 #[tokio::test]
78 async fn token_is_64_hex_and_unique() {
79 let token = SessionToken::generate().unwrap();
80 assert_eq!(token.as_str().len(), 64);
81 assert!(token.as_str().chars().all(|c| c.is_ascii_hexdigit()));
82 assert_ne!(SessionToken::generate().unwrap().as_str(), token.as_str());
83 }
84}