trifid/trifid-api/src/tokens.rs

61 lines
1.9 KiB
Rust

// trifid-api, an open source reimplementation of the Defined Networking nebula management server.
// Copyright (C) 2023 c0repwn3r
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use actix_web::http::header::HeaderValue;
use rand::Rng;
pub const ID_CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
pub const ID_LEN: u32 = 26;
pub const TOKEN_CHARSET: &[u8] =
b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
pub const TOKEN_LEN: u32 = 43;
// 26
// format: [ID]-[26 chars]
pub fn random_id(identifier: &str) -> String {
format!("{}-{}", identifier, random_with_charset(ID_LEN, ID_CHARSET))
}
// 26
// format: [ID]-[26 chars]
pub fn random_id_no_id() -> HeaderValue {
HeaderValue::from_str(&random_with_charset(ID_LEN, ID_CHARSET)).unwrap()
}
// 43
// format: [TYPE]-[43 chars]
pub fn random_token(identifier: &str) -> String {
format!(
"{}-{}",
identifier,
random_with_charset(TOKEN_LEN, TOKEN_CHARSET)
)
}
fn random_with_charset(len: u32, charset: &[u8]) -> String {
(0..len)
.map(|_| {
let idx = rand::thread_rng().gen_range(0..charset.len());
charset[idx] as char
})
.collect()
}
pub fn get_token_type(token: &str) -> Option<&str> {
token.split('-').collect::<Vec<&str>>().first().copied()
}