From 4e9a09f74b336ab2ce99c5492aa2dde88657f389 Mon Sep 17 00:00:00 2001 From: fef Date: Tue, 20 Dec 2022 13:24:08 +0100 Subject: [PATCH] refactor password hash API --- src/route/api/nyano/v1/auth.rs | 2 +- src/util/password.rs | 17 +++++++++++++++-- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/src/route/api/nyano/v1/auth.rs b/src/route/api/nyano/v1/auth.rs index 6401e6b..1f1879d 100644 --- a/src/route/api/nyano/v1/auth.rs +++ b/src/route/api/nyano/v1/auth.rs @@ -31,7 +31,7 @@ async fn auth(body: web::Json, state: AppState) -> Result Error::BadCredentials, e => e, })?; - password::verify(&body.password, &user.password).map_err(|_| Error::BadCredentials)?; + password::verify(body.password.as_str(), user.password.as_str())?; let account = state.repo.accounts.by_id(user.account_id).await?; let token = token::issue(&state, &account)?; info!(target: "auth", "Successful login for user {}", &account.name); diff --git a/src/util/password.rs b/src/util/password.rs index a34eadd..fe17bbc 100644 --- a/src/util/password.rs +++ b/src/util/password.rs @@ -4,7 +4,7 @@ use argon2::{Argon2, PasswordHash, PasswordHasher, PasswordVerifier}; use crate::core::*; -pub fn hash(clear: &String) -> String { +pub fn hash(clear: &str) -> String { let salt = SaltString::generate(&mut OsRng); let argon2 = Argon2::default(); argon2 @@ -13,10 +13,23 @@ pub fn hash(clear: &String) -> String { .to_string() } -pub fn verify(clear: &String, hash: &String) -> Result<()> { +pub fn verify(clear: &str, hash: &str) -> Result<()> { let parsed_hash = PasswordHash::new(&hash).unwrap(); match Argon2::default().verify_password(clear.as_bytes(), &parsed_hash) { Ok(_) => Ok(()), Err(_) => Err(Error::BadCredentials), } } + +#[cfg(test)] +mod tests { + use crate::util::password::{hash, verify}; + + #[test] + fn validate_hashes() { + let h = hash("asdf"); + assert!(verify("asdf", h.as_str()).is_ok()); + assert!(verify("fdsa", h.as_str()).is_err()); + assert!(verify("asdf\0", h.as_str()).is_err()); + } +}