Skip to main content

revolt_database/models/sessions/
model.rs

1use iso8601_timestamp::Timestamp;
2
3use crate::{events::client::EventV1, Database};
4use revolt_result::Result;
5
6auto_derived_partial!(
7    /// Session information
8    pub struct Session {
9        /// Unique Id
10        #[serde(rename = "_id")]
11        pub id: String,
12
13        /// User Id
14        pub user_id: String,
15
16        /// Session token
17        pub token: String,
18
19        /// Display name
20        pub name: String,
21
22        /// When the session was last logged in
23        pub last_seen: Timestamp,
24
25        /// Where the session originated from
26        ///
27        /// This could be used to differentiate sessions that come from staging/test vs prod, etc.
28        #[serde(skip_serializing_if = "Option::is_none")]
29        pub origin: Option<String>,
30
31        /// Web Push subscription
32        #[serde(skip_serializing_if = "Option::is_none")]
33        pub subscription: Option<WebPushSubscription>,
34    },
35    "PartialSession"
36);
37
38auto_derived!(
39    /// Web Push subscription
40    pub struct WebPushSubscription {
41        pub endpoint: String,
42        pub p256dh: String,
43        pub auth: String,
44    }
45);
46
47impl Session {
48    /// Save model
49    pub async fn save(&self, db: &Database) -> Result<()> {
50        db.save_session(self).await
51    }
52
53    /// Delete session
54    pub async fn delete(self, db: &Database) -> Result<()> {
55        // Delete from database
56        db.delete_session(&self.id).await?;
57
58        // Create and push event
59        EventV1::DeleteSession {
60            user_id: self.user_id.clone(),
61            session_id: self.id,
62        }
63        .private(self.user_id)
64        .await;
65
66        Ok(())
67    }
68}