From 4741cfd14bf073a05d220c123000a75599baa224 Mon Sep 17 00:00:00 2001 From: Harald Eilertsen Date: Thu, 22 Mar 2018 21:04:22 +0100 Subject: Refactor moving is_pwned check to separate function. Also moves rest of reporting to main. --- src/main.rs | 56 +++++++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 43 insertions(+), 13 deletions(-) diff --git a/src/main.rs b/src/main.rs index 4e7cbb7..c36ebd6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -67,6 +67,16 @@ impl Password { rest: rest, } } + + pub fn is_pwned(&self, hashes: &str) -> usize { + if let Some(pos) = hashes.find(&self.rest) { + if let Some(res) = hashes[pos..].lines().take(1).collect::>().pop() { + return res.split(':').skip(1).collect::>().pop().unwrap().parse().unwrap(); + } + } + + 0 + } } #[test] @@ -76,20 +86,34 @@ fn test_creating_new_password() { assert_eq!(&pw.rest, "910077770C8340F63CD2DCA2AC1F120444F"); } -fn check(pw: Password) -> Result{ - let uri = &format!("https://api.pwnedpasswords.com/range/{}", pw.range); - let hashes = reqwest::get(uri)?.text()?; +#[test] +fn test_matching_response_with_no_matches() { + let pw = Password::new("Passw0rd"); + let hashes = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA:42"; - if let Some(pos) = hashes.find(&pw.rest) { - if let Some(res) = hashes[pos..].lines().take(1).collect::>().pop() { - let count = res.split(':').skip(1).collect::>().pop().unwrap(); - println!("The password {} was found in {} breaches", pw.pw, count); - } + assert_eq!(0, pw.is_pwned(&hashes)); +} - return Ok(true); - } +#[test] +fn test_matching_response_with_one_match() { + let pw = Password::new("Passw0rd"); + let hashes = "910077770C8340F63CD2DCA2AC1F120444F:42"; + + assert_eq!(42, pw.is_pwned(&hashes)); +} - Ok(false) +#[test] +fn test_matching_response_with_multiple_matches() { + let pw = Password::new("Passw0rd"); + let hashes = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA:3\n910077770C8340F63CD2DCA2AC1F120444F:42\n00000000000000000000:1"; + + assert_eq!(42, pw.is_pwned(&hashes)); +} + +fn check(pw: Password) -> Result{ + let uri = &format!("https://api.pwnedpasswords.com/range/{}", pw.range); + let hashes = reqwest::get(uri)?.text()?; + Ok(pw.is_pwned(&hashes)) } fn print_usage() { @@ -109,8 +133,14 @@ fn main() { for pw in passwords { match check(Password::new(&pw)) { Err(e) => println!("{}", e.description()), - Ok(true) => println!("Password is PWNED!"), - Ok(false) => println!("Password was not found in any breaches.") + Ok(num) => { + if num > 0 { + println!("Password is PWNED! It was found in {} breaches.", num); + } + else { + println!("Password was not found in any breaches"); + } + } } } } -- cgit v1.2.3