Skip to content

Commit

Permalink
feat: implement password reading from stdin
Browse files Browse the repository at this point in the history
  • Loading branch information
replydev committed Mar 12, 2024
1 parent e033e60 commit 0f3bef7
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 10 deletions.
12 changes: 7 additions & 5 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use interface::ui::Tui;
use otp::otp_element::{OTPDatabase, CURRENT_DATABASE_VERSION};
use ratatui::prelude::CrosstermBackend;
use ratatui::Terminal;
use reading::{get_elements, ReadResult};
use reading::{get_elements_from_input, get_elements_from_stdin, ReadResult};
use std::{io, vec};
use zeroize::Zeroize;

Expand All @@ -25,7 +25,7 @@ mod path;
mod reading;
mod utils;

fn init() -> color_eyre::Result<ReadResult> {
fn init(read_password_from_stdin: bool) -> color_eyre::Result<ReadResult> {
match utils::init_app() {
Ok(first_run) => {
if first_run {
Expand All @@ -39,8 +39,10 @@ fn init() -> color_eyre::Result<ReadResult> {
let save_result = database.save_with_pw(&pw);
pw.zeroize();
save_result.map(|(key, salt)| (database, key, salt.to_vec()))
} else if read_password_from_stdin {
get_elements_from_stdin()
} else {
get_elements()
get_elements_from_input()
}
}
Err(()) => Err(eyre!("An error occurred during database creation")),
Expand All @@ -50,8 +52,8 @@ fn init() -> color_eyre::Result<ReadResult> {
fn main() -> AppResult<()> {
color_eyre::install()?;

let cotp_args = CotpArgs::parse();
let (database, mut key, salt) = match init() {
let cotp_args: CotpArgs = CotpArgs::parse();
let (database, mut key, salt) = match init(cotp_args.password_from_stdin) {
Ok(v) => v,
Err(e) => {
println!("{e}");
Expand Down
21 changes: 16 additions & 5 deletions src/reading.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,26 @@ use crate::path::get_db_path;
use crate::utils;
use color_eyre::eyre::{eyre, ErrReport};
use std::fs::read_to_string;
use std::io;
use std::io::{self, BufRead};
use zeroize::Zeroize;

pub type ReadResult = (OTPDatabase, Vec<u8>, Vec<u8>);

pub fn get_elements() -> color_eyre::Result<ReadResult> {
let mut pw = utils::password("Password: ", 8);
let (elements, key, salt) = read_from_file(&pw)?;
pw.zeroize();
pub fn get_elements_from_input() -> color_eyre::Result<ReadResult> {
let pw = utils::password("Password: ", 8);
get_elements_with_password(pw)
}

pub fn get_elements_from_stdin() -> color_eyre::Result<ReadResult> {
for password in io::stdin().lock().lines() {
return get_elements_with_password(password?);
}
Err(eyre!("Failure during stdin reading"))
}

fn get_elements_with_password(mut password: String) -> color_eyre::Result<ReadResult> {
let (elements, key, salt) = read_from_file(&password)?;
password.zeroize();
Ok((elements, key, salt))
}

Expand Down

0 comments on commit 0f3bef7

Please sign in to comment.