Skip to content

Commit

Permalink
feat: add support for windows(env path)
Browse files Browse the repository at this point in the history
  • Loading branch information
gustav888 committed Sep 27, 2022
1 parent 7330ff3 commit d494175
Showing 1 changed file with 26 additions and 8 deletions.
34 changes: 26 additions & 8 deletions src/network/secure.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::fs::OpenOptions;
use std::io::BufReader;
use std::io::BufWriter;
use std::env;
use std::path::Path;
use colorful::Colorful;
use colorful::Color;
use libp2p::identity;
Expand All @@ -17,14 +18,20 @@ pub fn new_secret_key() -> Result<(), Box<dyn Error>> {
let s = format!("{}", secret_key.display_secret());
println!("{}", s);

let home_path = env::var("HOME").unwrap();
std::fs::create_dir_all(format!("{}{}", home_path, "/.tochat"))?;
let home_path = match env::var("HOME") {
Ok(path) => path,
Err(_) => env::var("HOMEPATH").unwrap(),
};

let tochat_path = Path::new("/.tochat").to_string_lossy();
std::fs::create_dir_all(format!("{}{}", home_path, tochat_path))?;

let secret_path = Path::new("/.tochat/secret.json").to_string_lossy();
let buf = BufWriter::new(
OpenOptions::new()
.write(true)
.create(true)
.open(format!("{}{}", home_path, "/.tochat/secret.json"))?);
.open(format!("{}{}", home_path, secret_path))?);
serde_json::to_writer_pretty(buf, &s).unwrap();
Ok(())
}
Expand All @@ -36,24 +43,35 @@ pub fn generate_ed25519(key: &String) -> identity::Keypair {
}

pub fn get_secret() -> String {
let home_path = env::var("HOME").unwrap();
let home_path = match env::var("HOME") {
Ok(path) => path,
Err(_) => env::var("HOMEPATH").unwrap(),
};

let secret_path = Path::new("/.tochat/secret.json").to_string_lossy();
let buf = BufReader::new(
OpenOptions::new()
.read(true)
.open(format!("{}{}", home_path, "/.tochat/secret.json"))
.open(format!("{}{}", home_path, secret_path))
.expect("Please create or import a secret key"));
serde_json::from_reader(buf).unwrap()
}

pub fn import_secret(key: &String) -> Result<(), Box<dyn Error>> {
let home_path = env::var("HOME").unwrap();
std::fs::create_dir_all(format!("{}{}", home_path, "/.tochat"))?;
let home_path = match env::var("HOME") {
Ok(path) => path,
Err(_) => env::var("HOMEPATH").unwrap(),
};

let tochat_path = Path::new("/.tochat").to_string_lossy();
std::fs::create_dir_all(format!("{}{}", home_path, tochat_path))?;

let secret_path = Path::new("/.tochat/secret.json").to_string_lossy();
let buf = BufWriter::new(
OpenOptions::new()
.write(true)
.create(true)
.open(format!("{}{}", home_path, "/.tochat/secret.json"))?);
.open(format!("{}{}", home_path, secret_path))?);
serde_json::to_writer_pretty(buf, key).unwrap();
Ok(())
}

0 comments on commit d494175

Please sign in to comment.