Add subcommands

This commit is contained in:
Pierre HUBERT 2022-03-21 13:56:52 +01:00
parent 5350b380e2
commit ac9f033656

View File

@ -1,7 +1,7 @@
use std::time::{SystemTime, UNIX_EPOCH}; use std::time::{SystemTime, UNIX_EPOCH};
use base32::Alphabet; use base32::Alphabet;
use clap::Parser; use clap::{Parser, Subcommand};
use totp_rfc6238::{HashAlgorithm, TotpGenerator}; use totp_rfc6238::{HashAlgorithm, TotpGenerator};
/// Get the current time since epoch /// Get the current time since epoch
@ -14,36 +14,50 @@ pub fn time() -> u64 {
#[derive(Parser, Debug)] #[derive(Parser, Debug)]
#[clap(author, version, about, long_about = None)] #[clap(author, version, about, long_about = None)]
struct Args { struct Args {
/// The secret to use #[clap(subcommand)]
#[clap(short, long)] command: SubCommands
secret: String, }
/// Interval between two numbers generation #[derive(Subcommand, Debug)]
#[clap(short, long, default_value_t = 30)] enum SubCommands {
topt_step: u64, /// Get a code
#[clap(arg_required_else_help = true)]
Code {
/// The secret to use
#[clap(short, long)]
secret: String,
/// Size of generated secret /// Interval between two numbers generation
#[clap(short, long, default_value_t = 6)] #[clap(short, long, default_value_t = 30)]
len: usize, topt_step: u64,
/// Size of generated secret
#[clap(short, long, default_value_t = 6)]
len: usize,
}
} }
fn main() { fn main() {
let args: Args = Args::parse(); let args: Args = Args::parse();
let totp_generator = TotpGenerator::new() match args.command {
.set_digit(args.len).unwrap() SubCommands::Code { secret, topt_step, len } => {
.set_step(args.topt_step).unwrap() let totp_generator = TotpGenerator::new()
.set_hash_algorithm(HashAlgorithm::SHA1) .set_digit(len).unwrap()
.build(); .set_step(topt_step).unwrap()
.set_hash_algorithm(HashAlgorithm::SHA1)
.build();
let key = base32::decode( let key = base32::decode(
Alphabet::RFC4648 { padding: true }, Alphabet::RFC4648 { padding: true },
&args.secret, &secret,
).unwrap(); ).unwrap();
let code = totp_generator.get_code(&key); let code = totp_generator.get_code(&key);
let next_update = totp_generator.get_next_update_time().unwrap(); let next_update = totp_generator.get_next_update_time().unwrap();
println!("Secret = {}", code); println!("Secret = {}", code);
println!("Next update = {} seconds", next_update - time()); println!("Next update = {} seconds", next_update - time());
}
}
} }