From 89c89a5524ab08c2309342d1f4bf406e0800a4d1 Mon Sep 17 00:00:00 2001 From: phoenix Date: Mon, 7 Apr 2025 20:15:58 +0000 Subject: [PATCH] Login endpoint bug fix (#24) Reviewed-on: https://git.kundeng.us/phoenix/icarus_auth/pulls/24 Co-authored-by: phoenix Co-committed-by: phoenix --- Cargo.toml | 2 +- src/callers/common.rs | 61 ++++++++++++++++++++++++------------------- src/callers/login.rs | 59 ++++++++++++++++------------------------- src/hashing/mod.rs | 37 +++++++++++++++++++------- src/main.rs | 10 +++++-- 5 files changed, 92 insertions(+), 77 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 701c694..f975e99 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "icarus_auth" -version = "0.3.0" +version = "0.3.2" edition = "2024" rust-version = "1.86" diff --git a/src/callers/common.rs b/src/callers/common.rs index afb5ffb..bf178b3 100644 --- a/src/callers/common.rs +++ b/src/callers/common.rs @@ -1,30 +1,37 @@ -use axum::{Extension, Json, http::StatusCode}; +pub mod response { + use serde::{Deserialize, Serialize}; -use serde::{Deserialize, Serialize}; - -#[derive(Deserialize, Serialize)] -pub struct TestResult { - message: String, -} - -// basic handler that responds with a static string -pub async fn root() -> &'static str { - "Hello, World!" -} - -pub async fn db_ping(Extension(pool): Extension) -> (StatusCode, Json) { - match sqlx::query("SELECT 1").execute(&pool).await { - Ok(_) => { - let tr = TestResult { - message: String::from("This works"), - }; - (StatusCode::OK, Json(tr)) - } - Err(e) => ( - StatusCode::BAD_REQUEST, - Json(TestResult { - message: e.to_string(), - }), - ), + #[derive(Deserialize, Serialize)] + pub struct TestResult { + pub message: String, + } +} + +pub mod endpoint { + use super::*; + use axum::{Extension, Json, http::StatusCode}; + + // basic handler that responds with a static string + pub async fn root() -> &'static str { + "Hello, World!" + } + + pub async fn db_ping( + Extension(pool): Extension, + ) -> (StatusCode, Json) { + match sqlx::query("SELECT 1").execute(&pool).await { + Ok(_) => { + let tr = response::TestResult { + message: String::from("This works"), + }; + (StatusCode::OK, Json(tr)) + } + Err(e) => ( + StatusCode::BAD_REQUEST, + Json(response::TestResult { + message: e.to_string(), + }), + ), + } } } diff --git a/src/callers/login.rs b/src/callers/login.rs index 76a4272..6f2908e 100644 --- a/src/callers/login.rs +++ b/src/callers/login.rs @@ -45,45 +45,30 @@ pub mod endpoint { // Check if user exists match repo::user::get(&pool, &payload.username).await { Ok(user) => { - let salt = repo::salt::get(&pool, &user.salt_id).await.unwrap(); - let salt_str = hashing::get_salt(&salt.salt).unwrap(); - let unhashed_password = payload.password; + if hashing::verify_password(&payload.password, user.password.clone()).unwrap() { + // Create token + let key = token_stuff::get_key().unwrap(); + let (token_literal, duration) = token_stuff::create_token(&key).unwrap(); - // Check if password is correct - match hashing::hash_password(&unhashed_password, &salt_str) { - Ok(hash_password) => { - if hashing::verify_password(&unhashed_password, hash_password.clone()) - .unwrap() - { - // Create token - let key = token_stuff::get_key().unwrap(); - let (token_literal, duration) = - token_stuff::create_token(&key).unwrap(); - - if token_stuff::verify_token(&key, &token_literal) { - ( - StatusCode::OK, - Json(response::Response { - message: String::from("Successful"), - data: vec![icarus_models::login_result::LoginResult { - id: user.id, - username: user.username, - token: token_literal, - token_type: String::from(token_stuff::TOKENTYPE), - expiration: duration, - }], - }), - ) - } else { - return not_found("Could not verify password").await; - } - } else { - return not_found("Error Hashing").await; - } - } - Err(err) => { - return not_found(&err.to_string()).await; + if token_stuff::verify_token(&key, &token_literal) { + ( + StatusCode::OK, + Json(response::Response { + message: String::from("Successful"), + data: vec![icarus_models::login_result::LoginResult { + id: user.id, + username: user.username, + token: token_literal, + token_type: String::from(token_stuff::TOKENTYPE), + expiration: duration, + }], + }), + ) + } else { + return not_found("Could not verify password").await; } + } else { + return not_found("Error Hashing").await; } } Err(err) => { diff --git a/src/hashing/mod.rs b/src/hashing/mod.rs index a3fbbd4..2c53f0b 100644 --- a/src/hashing/mod.rs +++ b/src/hashing/mod.rs @@ -11,8 +11,7 @@ use argon2::{ pub fn generate_salt() -> Result { // Generate a random salt // SaltString::generate uses OsRng internally for cryptographic security - let salt = SaltString::generate(&mut OsRng); - Ok(salt) + Ok(SaltString::generate(&mut OsRng)) } pub fn get_salt(s: &str) -> Result { @@ -32,9 +31,7 @@ pub fn hash_password( // Hash the password with the salt // The output is a PasswordHash string format that includes algorithm, version, // parameters, salt, and the hash itself. - let password_hash = argon2.hash_password(password_bytes, salt)?.to_string(); - - Ok(password_hash) + Ok(argon2.hash_password(password_bytes, salt)?.to_string()) } pub fn verify_password( @@ -48,11 +45,9 @@ pub fn verify_password( let parsed_hash = argon2::PasswordHash::new(stored_hash.as_str())?; // Create an Argon2 instance (it will use the parameters from the parsed hash) - let argon2 = Argon2::default(); - // Verify the password against the parsed hash // This automatically uses the correct salt and parameters embedded in `parsed_hash` - match argon2.verify_password(password_bytes, &parsed_hash) { + match Argon2::default().verify_password(password_bytes, &parsed_hash) { Ok(()) => Ok(true), // Passwords match Err(argon2::password_hash::Error::Password) => Ok(false), // Passwords don't match Err(e) => Err(e), // Some other error occurred (e.g., invalid hash format) @@ -66,8 +61,7 @@ mod tests { #[test] fn test_hash_password() { let some_password = String::from("somethingrandom"); - let salt = generate_salt().unwrap(); - match hash_password(&some_password, &salt) { + match hash_password(&some_password, &generate_salt().unwrap()) { Ok(p) => match verify_password(&some_password, p.clone()) { Ok(res) => { assert_eq!(res, true); @@ -81,4 +75,27 @@ mod tests { } } } + + #[test] + fn test_wrong_password() { + let some_password = String::from("somethingrandom"); + match hash_password(&some_password, &generate_salt().unwrap()) { + Ok(p) => { + match verify_password(&some_password, p.clone()) { + Ok(res) => { + assert_eq!(res, true, "Passwords are not verified"); + } + Err(err) => { + assert!(false, "Error: {:?}", err.to_string()); + } + } + let wrong_password = String::from("Differentanotherlevel"); + let result = verify_password(&wrong_password, p.clone()).unwrap(); + assert_eq!(false, result, "Passwords should not match"); + } + Err(err) => { + assert!(false, "Error: {:?}", err.to_string()); + } + } + } } diff --git a/src/main.rs b/src/main.rs index 2dfe642..48239d6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -25,8 +25,14 @@ mod init { pub async fn routes() -> Router { // build our application with a route Router::new() - .route(callers::endpoints::DBTEST, get(callers::common::db_ping)) - .route(callers::endpoints::ROOT, get(callers::common::root)) + .route( + callers::endpoints::DBTEST, + get(callers::common::endpoint::db_ping), + ) + .route( + callers::endpoints::ROOT, + get(callers::common::endpoint::root), + ) .route( callers::endpoints::REGISTER, post(callers::register::register_user),