Optimized password hash errors

This commit is contained in:
xeovalyte 2025-02-14 12:31:45 +01:00
parent 1e2247abe2
commit 701d430742
Signed by: xeovalyte
SSH Key Fingerprint: SHA256:GWI1hq+MNKR2UOcvk7n9tekASXT8vyazK7vDF9Xyciw
8 changed files with 28 additions and 55 deletions

View File

@ -58,9 +58,7 @@ pub fn get_token_from_bearer(bearer: &str) -> Result<String, AuthError> {
}
}
pub async fn generate_password_hash(
password: String,
) -> Result<String, argon2::password_hash::Error> {
pub async fn generate_password_hash(password: String) -> Result<String, AuthError> {
let password_hash: Result<String, argon2::password_hash::Error> =
task::spawn_blocking(move || {
let salt = SaltString::generate(&mut OsRng);
@ -76,22 +74,19 @@ pub async fn generate_password_hash(
.await
.unwrap();
password_hash
password_hash.map_err(|e| e.into())
}
pub async fn verify_password_hash(
password: &str,
hash: &str,
) -> Result<(), argon2::password_hash::Error> {
pub async fn verify_password_hash(password: &str, hash: &str) -> Result<(), AuthError> {
let parsed_hash = PasswordHash::new(hash)?;
Argon2::default().verify_password(password.as_bytes(), &parsed_hash)?;
Argon2::default()
.verify_password(password.as_bytes(), &parsed_hash)
.map_err(|_| AuthError::InvalidPassword)?;
Ok(())
}
pub fn generate_session_token() -> String {
ChaCha20Rng::from_os_rng()
.sample_iter(&Alphanumeric)
.take(60)

View File

@ -7,6 +7,7 @@ pub enum AuthError {
Unexpected,
InvalidPassword,
Unauthorized,
HashingFailed(String),
}
impl Display for AuthError {
@ -17,8 +18,15 @@ impl Display for AuthError {
Self::Unexpected => write!(f, "Unexpected error"),
Self::InvalidPassword => write!(f, "Password is incorrect"),
Self::Unauthorized => write!(f, "Authentication is required"),
Self::HashingFailed(msg) => write!(f, "Password hashing failed: {}", msg),
}
}
}
impl std::error::Error for AuthError {}
impl From<argon2::password_hash::Error> for AuthError {
fn from(value: argon2::password_hash::Error) -> Self {
AuthError::HashingFailed(value.to_string())
}
}

View File

@ -32,10 +32,6 @@ impl Member {
Ok(members)
}
pub async fn get_many(transaction: &PgPool, members: Vec<Self>) -> Result<(), sqlx::Error> {
Ok(())
}
pub async fn get_all(pool: &PgPool) -> Result<Vec<Self>, sqlx::Error> {
let members = sqlx::query_as!(Member, "SELECT * FROM members;",)
.fetch_all(pool)

View File

@ -36,9 +36,9 @@ impl Session {
Ok(())
}
pub async fn from_token(transaction: &PgPool, token: &str) -> Result<Self, sqlx::Error> {
pub async fn from_token(pool: &PgPool, token: &str) -> Result<Self, sqlx::Error> {
let session = sqlx::query_as!(Self, "SELECT * FROM sessions WHERE token = $1;", token)
.fetch_one(transaction)
.fetch_one(pool)
.await?;
Ok(session)

View File

@ -109,8 +109,8 @@ pub struct UserMember {
impl UserMember {
pub async fn insert_many(
transaction: &mut sqlx::Transaction<'_, Postgres>,
user_ids: &Vec<uuid::Uuid>,
member_ids: &Vec<String>,
user_ids: &[uuid::Uuid],
member_ids: &[String],
) -> Result<(), sqlx::Error> {
sqlx::query!(
"

View File

@ -33,10 +33,7 @@ pub async fn login<'a>(
let db_user = DbUser::get_from_email(&state.pool, login_request.email).await?;
if let Some(pass) = db_user.password {
match verify_password_hash(&login_request.password, &pass).await {
Ok(_) => (),
Err(_err) => return Err(crate::Error::Auth(crate::auth::AuthError::InvalidPassword)),
};
verify_password_hash(&login_request.password, &pass).await?;
} else {
return Err(AuthError::Unexpected.into());
}
@ -71,10 +68,7 @@ pub async fn register(
let member_ids: Vec<String> = members.into_iter().map(|m| m.member_id).collect();
// Hash password
let password_hash = match generate_password_hash(auth_request.password).await {
Ok(hash) => hash,
Err(_err) => return Err(crate::Error::Auth(crate::auth::AuthError::InvalidToken)),
};
let password_hash = generate_password_hash(auth_request.password).await?;
let mut transaction = state.pool.begin().await?;
@ -107,19 +101,13 @@ pub async fn change_password(
) -> Result<(), crate::Error> {
let (_, user) = get_user_from_header(&state.pool, &headers).await?;
let password_hash = match generate_password_hash(request.new_password).await {
Ok(hash) => hash,
Err(_err) => return Err(crate::Error::Auth(crate::auth::AuthError::InvalidPassword)),
};
// Verify that password is correct
let db_user: DbUser = user.into();
let old_password_hash = db_user.get_password(&state.pool).await?;
verify_password_hash(&request.old_password, &old_password_hash).await?;
match verify_password_hash(&request.old_password, &old_password_hash).await {
Ok(_) => (),
Err(_err) => return Err(crate::Error::Auth(crate::auth::AuthError::InvalidPassword)),
};
// Generate password hash for new password
let new_password_hash = generate_password_hash(request.new_password).await?;
let mut transaction = state.pool.begin().await?;
@ -128,7 +116,7 @@ pub async fn change_password(
&mut transaction,
UpdateUser {
email: None,
password: Some(password_hash),
password: Some(new_password_hash),
admin: None,
},
)
@ -152,14 +140,10 @@ pub async fn change_email(
) -> Result<(), crate::Error> {
let (_, user) = get_user_from_header(&state.pool, &headers).await?;
// Verify that password is correct
let db_user: DbUser = user.into();
let password_hash = db_user.get_password(&state.pool).await?;
match verify_password_hash(&request.password, &password_hash).await {
Ok(_) => (),
Err(_err) => return Err(crate::Error::Auth(crate::auth::AuthError::InvalidPassword)),
};
verify_password_hash(&request.password, &password_hash).await?;
let mut transaction = state.pool.begin().await?;

View File

@ -26,7 +26,3 @@ pub async fn get_current_members(
Ok(Json(members))
}
pub async fn get_members(State(state): State<AppState>, body: String) -> Result<(), crate::Error> {
Ok(())
}

View File

@ -1,11 +1,6 @@
use std::collections::HashMap;
use axum::{
extract::State,
http::HeaderMap,
Json,
};
use itertools::Itertools;
use axum::{extract::State, http::HeaderMap, Json};
use sqlx::PgPool;
use crate::{
@ -143,7 +138,6 @@ pub struct MigrationStore {
pub count: u32,
}
impl Row {
fn from_csv_many(input: &str) -> Result<Vec<Self>, csv::Error> {
let mut rdr = csv::ReaderBuilder::new()