refactor password hash API
This commit is contained in:
parent
271a912879
commit
4e9a09f74b
2 changed files with 16 additions and 3 deletions
|
@ -31,7 +31,7 @@ async fn auth(body: web::Json<AuthRequest>, state: AppState) -> Result<HttpRespo
|
||||||
Error::NotFound => Error::BadCredentials,
|
Error::NotFound => Error::BadCredentials,
|
||||||
e => e,
|
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 account = state.repo.accounts.by_id(user.account_id).await?;
|
||||||
let token = token::issue(&state, &account)?;
|
let token = token::issue(&state, &account)?;
|
||||||
info!(target: "auth", "Successful login for user {}", &account.name);
|
info!(target: "auth", "Successful login for user {}", &account.name);
|
||||||
|
|
|
@ -4,7 +4,7 @@ use argon2::{Argon2, PasswordHash, PasswordHasher, PasswordVerifier};
|
||||||
|
|
||||||
use crate::core::*;
|
use crate::core::*;
|
||||||
|
|
||||||
pub fn hash(clear: &String) -> String {
|
pub fn hash(clear: &str) -> String {
|
||||||
let salt = SaltString::generate(&mut OsRng);
|
let salt = SaltString::generate(&mut OsRng);
|
||||||
let argon2 = Argon2::default();
|
let argon2 = Argon2::default();
|
||||||
argon2
|
argon2
|
||||||
|
@ -13,10 +13,23 @@ pub fn hash(clear: &String) -> String {
|
||||||
.to_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();
|
let parsed_hash = PasswordHash::new(&hash).unwrap();
|
||||||
match Argon2::default().verify_password(clear.as_bytes(), &parsed_hash) {
|
match Argon2::default().verify_password(clear.as_bytes(), &parsed_hash) {
|
||||||
Ok(_) => Ok(()),
|
Ok(_) => Ok(()),
|
||||||
Err(_) => Err(Error::BadCredentials),
|
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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in a new issue