use std::{error::Error, fs, path::Path};
use log::{debug, error};
use crate::{session, tty};
pub(crate) fn verify_path(
token_path_str: &str,
tty: &tty::Terminal,
) -> Result<bool, Box<dyn Error>> {
let token_path = Path::new(&token_path_str);
debug!("Verifying if token_path exist and is a directory");
if token_path.exists() && token_path.is_dir() {
error!("token_path is a directory and will be erased");
fs::remove_dir(token_path)?;
Ok(false)
} else if token_path.exists() && token_path.is_file() {
debug!("Token will be read from file and validate");
let token = session::read_token_file(token_path_str);
if token.is_err() {
debug!("Token was invalid");
return Ok(false);
}
if token?
.verify_token(&tty.terminal_name, &tty.terminal_uuid)
.is_err()
{
debug!("Token was invalid");
return Ok(false);
}
debug!("Token was valid");
Ok(true)
} else {
debug!("Token was non-existent");
Ok(false)
}
}
#[cfg(test)]
mod tests {
use super::{tty::Terminal, verify_path, Error};
#[test]
fn test_verify_path_non_existent() -> Result<(), Box<dyn Error>> {
let tty = Terminal {
terminal_name: String::from("pts/0/"),
terminal_uuid: String::from("964045904534593458953"),
};
let result = verify_path("/run/rudo/pts/0", &tty)?;
if result {
Err(From::from("Test failed: the path should not be valid"))
} else {
Ok(())
}
}
}