mirror of
https://github.com/hpd840321/craftlabs-authorization-sdk.git
synced 2026-06-09 18:10:30 +08:00
feat(native): add session management with global handle registry
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
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);
|
||||
}
|
||||
Reference in New Issue
Block a user