BasicOIDC/src/utils/string_utils.rs

73 lines
2.0 KiB
Rust

use lazy_regex::regex_find;
use rand::distributions::Alphanumeric;
use rand::Rng;
/// Generate a random string of a given size
pub fn rand_str(len: usize) -> String {
rand::thread_rng()
.sample_iter(&Alphanumeric)
.map(char::from)
.take(len)
.collect()
}
/// Parse environment variables
pub fn apply_env_vars(val: &str) -> String {
let mut val = val.to_string();
if let Some(varname_with_wrapper) = regex_find!(r#"\$\{[a-zA-Z0-9_-]+\}"#, &val) {
let varname = varname_with_wrapper
.strip_prefix("${")
.unwrap()
.strip_suffix('}')
.unwrap();
let value = match std::env::var(varname) {
Ok(v) => v,
Err(e) => {
log::error!("Failed to find environment variable {varname}!");
eprintln!("Failed to find environment variable! {e:?}");
std::process::exit(2);
}
};
val = val.replace(varname_with_wrapper, &value);
}
val
}
/// Check out whether a given login is acceptable or not
pub fn is_acceptable_login(login: &str) -> bool {
mailchecker::is_valid(login) || lazy_regex::regex!("^[a-zA-Z0-9-+]+$").is_match(login)
}
#[cfg(test)]
mod test {
use crate::utils::string_utils::{apply_env_vars, is_acceptable_login};
use std::env;
const VAR_ONE: &str = "VAR_ONE";
#[test]
fn test_apply_env_var() {
env::set_var(VAR_ONE, "good");
let src = format!("This is ${{{}}}", VAR_ONE);
assert_eq!("This is good", apply_env_vars(&src));
}
const VAR_INVALID: &str = "VAR_INV@LID";
#[test]
fn test_invalid_var_syntax() {
let src = format!("This is ${{{}}}", VAR_INVALID);
assert_eq!(src, apply_env_vars(&src));
}
#[test]
fn test_is_acceptable_login() {
assert!(is_acceptable_login("admin"));
assert!(is_acceptable_login("someone@somewhere.fr"));
assert!(!is_acceptable_login("someone@somewhere.#fr"));
assert!(!is_acceptable_login("bad bad"));
}
}