mirror of
https://gitlab.com/comunic/comunicapiv3
synced 2025-06-20 16:35:17 +00:00
Can authenticate admin with reset token
This commit is contained in:
80
src/helpers/admin_access_token_helper.rs
Normal file
80
src/helpers/admin_access_token_helper.rs
Normal file
@ -0,0 +1,80 @@
|
||||
//! # Admin access token helper
|
||||
//!
|
||||
//! @author Pierre Hubert
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use crate::constants::{ADMIN_ACCESS_TOKEN_LENGTH, ADMIN_ACCESS_TOKEN_LIFETIME};
|
||||
use crate::data::admin::{AdminAccessToken, AdminID};
|
||||
use crate::data::error::{ExecError, Res};
|
||||
use crate::utils::crypt_utils::rand_str;
|
||||
use crate::utils::date_utils::time;
|
||||
|
||||
static mut CACHE: Option<Arc<Mutex<HashMap<AdminID, AdminAccessToken>>>> = None;
|
||||
|
||||
/// Initialize this helper
|
||||
pub fn init() {
|
||||
unsafe {
|
||||
let map = HashMap::new();
|
||||
CACHE = Some(Arc::new(Mutex::new(map)));
|
||||
}
|
||||
}
|
||||
|
||||
/// Create and return a new access token for an admin
|
||||
pub fn create(id: AdminID) -> Res<String> {
|
||||
let map = unsafe {
|
||||
CACHE.as_ref().unwrap().lock()
|
||||
};
|
||||
|
||||
let token = AdminAccessToken {
|
||||
token: rand_str(ADMIN_ACCESS_TOKEN_LENGTH),
|
||||
id,
|
||||
last_refresh: time(),
|
||||
};
|
||||
|
||||
map?.insert(id, token.clone());
|
||||
|
||||
Ok(token.token)
|
||||
}
|
||||
|
||||
/// Remove an access token from the list
|
||||
pub fn destroy(id: AdminID) -> Res {
|
||||
let map = unsafe {
|
||||
CACHE.as_ref().unwrap().lock()
|
||||
};
|
||||
|
||||
map?.remove(&id);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Find an admin by its access token
|
||||
pub fn find_by_token(t: &str) -> Res<AdminAccessToken> {
|
||||
let map = unsafe {
|
||||
CACHE.as_ref().unwrap().lock()
|
||||
};
|
||||
let mut map = map?;
|
||||
|
||||
let token = map.iter()
|
||||
.filter(|p| p.1.token.eq(t))
|
||||
.next();
|
||||
|
||||
let mut token = match token {
|
||||
None => {
|
||||
return Err(ExecError::boxed_new("The token was not recognized as an admin token!"));
|
||||
}
|
||||
Some(t) => t.1
|
||||
}.clone();
|
||||
|
||||
|
||||
if token.last_refresh + ADMIN_ACCESS_TOKEN_LIFETIME < time() {
|
||||
return Err(ExecError::boxed_new("The token has expired!"));
|
||||
}
|
||||
|
||||
token.last_refresh = time();
|
||||
|
||||
map.insert(token.id, token.clone());
|
||||
|
||||
Ok(token)
|
||||
}
|
@ -22,4 +22,5 @@ pub mod push_notifications_helper;
|
||||
pub mod independent_push_notifications_service_helper;
|
||||
pub mod firebase_notifications_helper;
|
||||
pub mod forez_presence_helper;
|
||||
pub mod admin_account_helper;
|
||||
pub mod admin_account_helper;
|
||||
pub mod admin_access_token_helper;
|
Reference in New Issue
Block a user