Files
craftlabs-authorization-sdk/native/craft-core/src/session.rs
T

43 lines
1.1 KiB
Rust

use std::collections::HashMap;
use std::sync::Mutex;
use once_cell::sync::Lazy;
pub struct SessionState {
pub config_json: String,
pub bit_handle: Option<usize>,
pub application_data: Vec<u8>,
pub logged_in: bool,
}
pub static SESSIONS: Lazy<Mutex<HashMap<i64, SessionState>>> =
Lazy::new(|| Mutex::new(HashMap::new()));
static NEXT_SESSION_ID: Lazy<Mutex<i64>> = Lazy::new(|| Mutex::new(1));
pub fn register_session(config_json: String, application_data: Vec<u8>) -> i64 {
let mut next_id = NEXT_SESSION_ID.lock().unwrap();
let id = *next_id;
*next_id += 1;
let mut sessions = SESSIONS.lock().unwrap();
sessions.insert(id, SessionState {
config_json,
bit_handle: None,
application_data,
logged_in: false,
});
id
}
pub fn with_session<F, R>(session_id: i64, f: F) -> Option<R>
where
F: FnOnce(&mut SessionState) -> R,
{
let mut sessions = SESSIONS.lock().unwrap();
sessions.get_mut(&session_id).map(f)
}
pub fn remove_session(session_id: i64) {
let mut sessions = SESSIONS.lock().unwrap();
sessions.remove(&session_id);
}