algohub_server/utils/
session.rs1use anyhow::Result;
2use surrealdb::{engine::remote::ws::Client, sql::Thing, Surreal};
3
4use crate::models::account::{Account, Session};
5
6use super::account;
7
8pub async fn create(db: &Surreal<Client>, account_id: Thing) -> Result<Option<Session>> {
9 let session: Option<Session> = db
10 .upsert(("session", account_id.id.to_string()))
11 .content(Session {
12 id: None,
13 account_id,
14 token: uuid::Uuid::new_v4().to_string(),
15 })
16 .await?;
17 Ok(session)
18}
19
20pub async fn verify(db: &Surreal<Client>, account_id: &str, token: &str) -> bool {
21 match db.select::<Option<Session>>(("session", account_id)).await {
22 Ok(Some(session)) => session.token == token,
23 _ => false,
24 }
25}
26
27pub async fn update(db: &Surreal<Client>, account: Thing) -> Result<Option<Session>> {
28 let session: Option<Session> = db
29 .upsert(("session", account.id.to_string()))
30 .content(Session {
31 id: None,
32 account_id: account,
33 token: uuid::Uuid::new_v4().to_string(),
34 })
35 .await?;
36 Ok(session)
37}
38
39pub async fn authenticate(
40 db: &Surreal<Client>,
41 identity: &str,
42 password: &str,
43) -> Result<Option<Session>> {
44 let account = account::get_by_identity::<Account>(db, identity).await?;
45 if account.is_none() {
46 return Ok(None);
47 };
48 let account = account.unwrap();
49 if account.password == password {
50 Ok(update(db, account.id.unwrap()).await?)
51 } else {
52 Ok(None)
53 }
54}