this repo has no description
at main 118 lines 3.1 kB view raw
1use atrium_api::types::string::Did; 2use serde::{Deserialize, Serialize}; 3use sqlx::PgPool; 4 5/// [AuthSession] data type 6#[derive(Debug, Clone, Deserialize, Serialize)] 7pub struct AuthSession { 8 pub key: String, 9 pub session: String, 10} 11 12impl AuthSession { 13 /// Creates a new [AuthSession] 14 pub fn new<V>(key: String, session: V) -> Self 15 where 16 V: Serialize, 17 { 18 let session = serde_json::to_string(&session).unwrap(); 19 Self { 20 key: key.to_string(), 21 session, 22 } 23 } 24 25 /// Gets an [AuthSession] by the users did(key) 26 pub async fn get_by_did(pool: &PgPool, did: String) -> Result<Option<Self>, sqlx::Error> { 27 let did = Did::new(did).unwrap(); 28 29 sqlx::query_as!( 30 AuthSession, 31 r#" 32 SELECT * 33 FROM auth_sessions 34 WHERE key = $1 35 "#, 36 did.as_str() 37 ) 38 .fetch_optional(pool) 39 .await 40 } 41 42 /// Saves or updates the [AuthSession] by its did(key) 43 pub async fn save_or_update(&self, pool: &PgPool) -> Result<(), sqlx::Error> { 44 let mut transaction = pool.begin().await?; 45 let exists: Option<bool> = sqlx::query_scalar!( 46 r#" 47 SELECT EXISTS( 48 SELECT * 49 FROM auth_sessions 50 WHERE key = $1 51 ) 52 "#, 53 self.key.clone() 54 ) 55 .fetch_one(transaction.as_mut()) 56 .await?; 57 58 if let Some(exists) = exists { 59 match exists { 60 true => { 61 sqlx::query!( 62 r#" 63 UPDATE auth_sessions 64 SET session = $2 65 WHERE key = $1 66 "#, 67 self.key, 68 self.session 69 ) 70 .execute(transaction.as_mut()) 71 .await?; 72 } 73 false => { 74 sqlx::query!( 75 r#" 76 INSERT INTO auth_sessions (key, session) VALUES ($1, $2) 77 "#, 78 self.key, 79 self.session 80 ) 81 .execute(transaction.as_mut()) 82 .await?; 83 } 84 } 85 } 86 87 transaction.commit().await?; 88 89 Ok(()) 90 } 91 92 /// Deletes the [AuthSession] by did 93 pub async fn delete_by_did(pool: &PgPool, did: String) -> Result<(), sqlx::Error> { 94 sqlx::query!( 95 r#" 96 DELETE FROM auth_sessions WHERE key = $1 97 "#, 98 did.as_str() 99 ) 100 .execute(pool) 101 .await?; 102 103 Ok(()) 104 } 105 106 /// Deletes all [AuthSession] rows 107 pub async fn delete_all(pool: &PgPool) -> Result<(), sqlx::Error> { 108 sqlx::query!( 109 r#" 110 DELETE FROM auth_sessions 111 "# 112 ) 113 .execute(pool) 114 .await?; 115 116 Ok(()) 117 } 118}