valis_core/modules/admin/
authinfo.rs

1use std::fs::File;
2use std::io::{self, BufRead};
3use std::path::Path;
4
5#[derive(Clone, Debug)]
6pub struct AuthInfo {
7    pub machine: String,
8    pub login: Login,
9    pub password: String,
10    pub port: Option<u16>,
11}
12
13#[derive(Clone, Debug)]
14pub struct Login {
15    pub name: String,
16    pub domain: Option<String>,
17}
18
19pub fn parse_auth_info(line: &str) -> Result<AuthInfo, &str> {
20    let mut parts: Vec<&str> = line.split_whitespace().collect();
21
22    if parts.len() < 6 {
23        return Err("Invalid auth info format");
24    }
25
26    let machine = parts[1].to_string();
27    let password = parts[5].to_string();
28    let mut port = None;
29
30    if parts.len() > 6 {
31        if parts[6] == "port" {
32            port = parts.get(7).and_then(|s| s.parse::<u16>().ok());
33            parts.truncate(6); // to make sure we ignore anything beyond the port info
34        }
35    }
36
37    let login_parts: Vec<&str> = parts[3].split('^').collect();
38    let login = if login_parts.len() == 2 {
39        Login {
40            name: login_parts[0].to_string(),
41            domain: Some(login_parts[1].to_string()),
42        }
43    } else if login_parts.len() == 1 {
44        Login {
45            name: login_parts[0].to_string(),
46            domain: None,
47        }
48    } else {
49        return Err("Invalid login format");
50    };
51
52    Ok(AuthInfo {
53        machine,
54        login,
55        password,
56        port,
57    })
58}
59
60pub fn read_auth_file(file_path: &Path) -> Result<Vec<AuthInfo>, Box<dyn std::error::Error>> {
61    let file = File::open(&file_path)?;
62    let reader = io::BufReader::new(file);
63    let mut auth_infos = Vec::new();
64
65    for line in reader.lines() {
66        let line = line?.trim().to_string(); // trim white spaces
67        if line.is_empty() {
68            continue; // Skip empty lines
69        }
70
71        match parse_auth_info(&line) {
72            Ok(auth_info) => auth_infos.push(auth_info),
73            Err(e) => eprintln!("Skipping line due to error: {}", e),
74        }
75    }
76    Ok(auth_infos)
77}
78
79
80pub fn find_auth_info_for_machine(machine: &str, auth_infos: Vec<AuthInfo>) -> Vec<AuthInfo> {
81    auth_infos.into_iter().filter(|info| info.machine == machine).collect()
82}