passafe/
initial_setup.rs

1pub mod initial_setup {
2    use crate::data::Data;
3    use bcrypt;
4    use home::home_dir;
5    use rpassword::read_password;
6    use serde_json;
7    use std::fs::{write, File};
8
9    // The function checks if the passwords.json file exists
10    // and if it doesn't, it creates the file
11    // If the file exists also the program wont panic which is the intedended behaviour
12    pub fn check_if_file_exists() {
13        let password_dir = home_dir().unwrap().join(".local/share/passafe");
14        let password_file = password_dir.join("passwords.json");
15
16        // Create the program dir where we can store the passwords file
17        std::fs::create_dir_all(&password_dir).unwrap();
18
19        // Create the file where we can store the passwords
20        File::create(&password_file).unwrap();
21
22        let master_password = get_master_password_from_user().unwrap();
23
24        let initial_data = Data {
25            master_password,
26            password: vec![],
27        };
28
29        write(
30            &password_file,
31            serde_json::to_string_pretty(&initial_data).unwrap(),
32        )
33        .unwrap();
34    }
35
36    fn get_master_password_from_user() -> Result<String, &'static str> {
37        println!("Lets setup your new password for this app");
38        let mut master_password = read_password().unwrap();
39        master_password = String::from(master_password.trim());
40
41        let hashed_master_password = {
42            let this = bcrypt::hash(&master_password, 12);
43            match this {
44                Ok(t) => t,
45                Err(_) => return Err("What the hell are you doing"),
46            }
47        };
48
49        Ok(hashed_master_password)
50    }
51}