pkgs: mailnix: Refactor dovecot::update_dynamic_passdb in preparation for unit tests

This commit is contained in:
Thomas Preisner 2025-02-25 17:15:20 +01:00
parent 79b2ec800e
commit 6f8bcdf9c0

View file

@ -22,6 +22,27 @@ pub fn generate_static_passdb(cfg: Config) {
}
}
fn try_load_passdb<P: AsRef<Path>>(path: P) -> Result<HashMap<String, String>, Box<dyn Error>> {
let mut curr_dynamic_users = HashMap::new();
if path.as_ref().exists() {
let re = Regex::new(r"^(?P<name>.*):(?P<hashed_password>.*)::::::$").unwrap();
let curr_passdb = fs::read_to_string(path.as_ref()).unwrap();
for line in curr_passdb.lines() {
let caps = re
.captures(line)
.unwrap_or_else(|| panic!("Regex does not match line: {line}"));
curr_dynamic_users.insert(
caps["name"].to_string(),
caps["hashed_password"].to_string(),
);
}
eprintln!("current passdb entries: {curr_dynamic_users:#?}");
}
Ok(curr_dynamic_users)
}
pub fn update_dynamic_passdb<P: AsRef<Path>>(cfg: Config, path: P) -> Result<(), Box<dyn Error>> {
// create hashmap of all accounts with their initial passdb-lines
let mut accounts: HashMap<String, AccountConfig> = cfg
@ -32,21 +53,12 @@ pub fn update_dynamic_passdb<P: AsRef<Path>>(cfg: Config, path: P) -> Result<(),
eprintln!("settings: {:#?}", accounts);
// load current passdb and update account password hashes
if path.as_ref().exists() {
let re = Regex::new(r"^(?P<name>.*):(?P<hashed_password>.*)::::::$").unwrap();
let curr_passdb = fs::read_to_string(path.as_ref()).unwrap();
eprintln!("current passdb: {curr_passdb}");
for line in curr_passdb.lines() {
//let caps = re.captures(line).ok_or_else(panic!("Regex does not match").unwrap();
let caps = re
.captures(line)
.unwrap_or_else(|| panic!("Regex does not match line: {line}"));
accounts.entry(caps["name"].to_string()).and_modify(|e| {
e.hashed_password = caps["hashed_password"].to_string();
let curr_dynamic_users = try_load_passdb(path)?;
for (name, hashed_password) in curr_dynamic_users.into_iter() {
accounts.entry(name).and_modify(|e| {
e.hashed_password = hashed_password;
});
}
}
for (name, acc) in accounts.into_iter() {
println!("{}:{}::::::", name, acc.hashed_password);