1
0
Fork 0
mirror of https://github.com/dani-garcia/vaultwarden.git synced 2025-08-09 20:49:07 +00:00

Add support for API keys

This is mainly useful for CLI-based login automation.
This commit is contained in:
Jeremy Lin 2022-01-19 02:51:26 -08:00
commit 69ee4a70b4
13 changed files with 164 additions and 7 deletions

View file

@ -51,6 +51,28 @@ pub fn get_random(mut array: Vec<u8>) -> Vec<u8> {
array
}
/// Generates a random string over a specified alphabet.
pub fn get_random_string(alphabet: &[u8], num_chars: usize) -> String {
// Ref: https://rust-lang-nursery.github.io/rust-cookbook/algorithms/randomness.html
use rand::Rng;
let mut rng = rand::thread_rng();
(0..num_chars)
.map(|_| {
let i = rng.gen_range(0..alphabet.len());
alphabet[i] as char
})
.collect()
}
/// Generates a random alphanumeric string.
pub fn get_random_string_alphanum(num_chars: usize) -> String {
const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
abcdefghijklmnopqrstuvwxyz\
0123456789";
get_random_string(ALPHABET, num_chars)
}
pub fn generate_id(num_bytes: usize) -> String {
HEXLOWER.encode(&get_random(vec![0; num_bytes]))
}
@ -84,6 +106,12 @@ pub fn generate_token(token_size: u32) -> Result<String, Error> {
Ok(token)
}
/// Generates a personal API key.
/// Upstream uses 30 chars, which is ~178 bits of entropy.
pub fn generate_api_key() -> String {
get_random_string_alphanum(30)
}
//
// Constant time compare
//