summaryrefslogtreecommitdiff
path: root/src/types/session.rs
blob: 9b949be4d1aae40e44a9127c95434c0f2c0f39b0 (plain)
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
use rand::{distributions::Alphanumeric, Rng};
use serde::Serialize;

use crate::database;
use crate::types::response::{Result, ResponseCode};

#[derive(Serialize)]
pub struct Session {
    pub user_id: u64,
    pub token: String
}

impl Session {

    pub fn from_token(token: &str) -> Result<Self> {
        let Ok(Some(session)) = database::sessions::get_session(token) else {
            return Err(ResponseCode::BadRequest.text("Invalid auth token"));
        };

        Ok(session)
    }

    pub fn new(user_id: u64) -> Result<Self> {
        let token: String = rand::thread_rng().sample_iter(&Alphanumeric).take(32).map(char::from).collect();
        match database::sessions::set_session(user_id, &token) {
            Err(_) => return Err(ResponseCode::BadRequest.text("Failed to create session")),
            Ok(_) => return Ok(Session {user_id, token})
        };
    }

    pub fn delete(user_id: u64) -> Result<()> {
        if let Err(_) = database::sessions::delete_session(user_id) {
            return Err(ResponseCode::InternalServerError.text("Failed to logout"));
        };
        Ok(())
    }
    
}