refactor password hash API

This commit is contained in:
anna 2022-12-20 13:24:08 +01:00
parent 271a912879
commit 4e9a09f74b
Signed by: fef
GPG key ID: EC22E476DC2D3D84
2 changed files with 16 additions and 3 deletions

View file

@ -31,7 +31,7 @@ async fn auth(body: web::Json<AuthRequest>, state: AppState) -> Result<HttpRespo
Error::NotFound => 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);

View file

@ -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());
}
}