algohub_server/utils/
session.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
use anyhow::Result;
use surrealdb::{engine::remote::ws::Client, sql::Thing, Surreal};

use crate::models::account::{Account, Session};

use super::account;

pub async fn create(db: &Surreal<Client>, account_id: Thing) -> Result<Option<Session>> {
    let session: Option<Session> = db
        .upsert(("session", account_id.id.to_string()))
        .content(Session {
            id: None,
            account_id,
            token: uuid::Uuid::new_v4().to_string(),
        })
        .await?;
    Ok(session)
}

pub async fn verify(db: &Surreal<Client>, account_id: &str, token: &str) -> bool {
    match db.select::<Option<Session>>(("session", account_id)).await {
        Ok(Some(session)) => session.token == token,
        _ => false,
    }
}

pub async fn update(db: &Surreal<Client>, account: Thing) -> Result<Option<Session>> {
    let session: Option<Session> = db
        .upsert(("session", account.id.to_string()))
        .content(Session {
            id: None,
            account_id: account,
            token: uuid::Uuid::new_v4().to_string(),
        })
        .await?;
    Ok(session)
}

pub async fn authenticate(
    db: &Surreal<Client>,
    identity: &str,
    password: &str,
) -> Result<Option<Session>> {
    let account = account::get_by_identity::<Account>(db, identity).await?;
    if account.is_none() {
        return Ok(None);
    };
    let account = account.unwrap();
    if account.password == password {
        Ok(update(db, account.id.unwrap()).await?)
    } else {
        Ok(None)
    }
}