From 5ff75f66b8a1260e6d3a42c88f9bdbbea6c72361 Mon Sep 17 00:00:00 2001 From: phoenix Date: Tue, 22 Sep 2026 12:47:43 -0400 Subject: [PATCH] Update password (#6) Reviewed-on: http://git.kundeng.us/phoenix/soaricarus_auth/pulls/6 --- Cargo.lock | 6 +- Cargo.toml | 4 +- src/callers/login.rs | 127 ++++++++++++++++++++++++++++++ src/callers/mod.rs | 1 + src/main.rs | 182 +++++++++++++++++++++++++++++++++++++------ src/repo/mod.rs | 52 +++++++++++++ 6 files changed, 344 insertions(+), 28 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 85c6be2..c6d9c1b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1551,8 +1551,8 @@ checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" [[package]] name = "simodels" -version = "0.11.4" -source = "git+ssh://git@git.kundeng.us/phoenix/simodels.git?tag=v0.11.4#d6d719741945ef7719ab1db3e0ef3c617b5bb909" +version = "0.11.6" +source = "git+ssh://git@git.kundeng.us/phoenix/simodels.git?tag=v0.11.6#e6ab0bcd83fd2ab3ab47298022c885132eed9945" dependencies = [ "josekit", "rand", @@ -1580,7 +1580,7 @@ dependencies = [ [[package]] name = "soaricarus_auth" -version = "0.8.2" +version = "0.8.3" dependencies = [ "argon2", "axum", diff --git a/Cargo.toml b/Cargo.toml index ee6f536..f138004 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "soaricarus_auth" -version = "0.8.2" +version = "0.8.3" edition = "2024" rust-version = "1.95" license = "MIT" @@ -22,7 +22,7 @@ time = { version = "0.3.55", features = ["macros", "serde"] } josekit = { version = "0.10.3" } utoipa = { version = "5.5.0", features = ["axum_extras"] } utoipa-swagger-ui = { version = "9.0.2", features = ["axum"] } -simodels = { git = "ssh://git@git.kundeng.us/phoenix/simodels.git", tag = "v0.11.4" } +simodels = { git = "ssh://git@git.kundeng.us/phoenix/simodels.git", tag = "v0.11.6" } sienvy = { git = "ssh://git@git.kundeng.us/phoenix/sienvy.git", tag = "v0.8.1" } [dev-dependencies] diff --git a/src/callers/login.rs b/src/callers/login.rs index c583d97..f84a1ac 100644 --- a/src/callers/login.rs +++ b/src/callers/login.rs @@ -20,6 +20,29 @@ pub mod request { pub access_token: String, } } + + pub mod update_password { + use serde::{Deserialize, Serialize}; + + #[derive(Default, Deserialize, Serialize, utoipa::ToSchema)] + pub struct Request { + pub user_id: uuid::Uuid, + pub username: String, + pub current_password: String, + pub updated_password: String, + pub confirmed_password: String, + } + + impl Request { + pub fn is_valid(&self) -> bool { + !self.user_id.is_nil() + || !self.username.is_empty() + || !self.current_password.is_empty() + || !self.updated_password.is_empty() + || !self.confirmed_password.is_empty() + } + } + } } pub mod response { @@ -46,6 +69,16 @@ pub mod response { pub data: Vec, } } + + pub mod update_password { + use serde::{Deserialize, Serialize}; + + #[derive(Default, Deserialize, Serialize, utoipa::ToSchema)] + pub struct Response { + pub message: String, + pub data: Vec, + } + } } /// Module for login endpoints @@ -261,4 +294,98 @@ pub mod endpoint { (axum::http::StatusCode::BAD_REQUEST, axum::Json(response)) } } + + #[utoipa::path( + patch, + path = super::super::endpoints::UPDATE_PASSWORD, + request_body( + content = super::request::update_password::Request, + description = "Update user password", + content_type = "application/json" + ), + responses( + (status = 200, description = "Password updated successfully", body = super::response::update_password::Response), + (status = 400, description = "Invalid", body = super::response::update_password::Response), + (status = 500, description = "Failure", body = super::response::update_password::Response) + ) + )] + pub async fn update_password( + axum::Extension(pool): axum::Extension, + axum::Json(payload): axum::Json, + ) -> ( + axum::http::StatusCode, + axum::Json, + ) { + let mut response = super::response::update_password::Response::default(); + + if !payload.is_valid() { + response.message = "Invalid request".to_string(); + println!("Invalid request"); + return (axum::http::StatusCode::BAD_REQUEST, axum::Json(response)); + } + + println!("Get User"); + match repo::user::get(&pool, &payload.username).await { + Ok(user) => { + if hashing::verify_password(&payload.current_password, user.password.clone()) + .unwrap() + { + match repo::salt::get(&pool, &user.salt_id).await { + Ok(salt) => { + let updated_salt_string = hashing::generate_salt().unwrap(); + let updated_salt = simodels::user::salt::Salt { + salt: updated_salt_string.to_string(), + id: salt.id, + }; + let updated_hashed_password = hashing::hash_password( + &payload.updated_password, + &updated_salt_string, + ) + .unwrap(); + + match repo::salt::update_salt(&pool, &salt, &updated_salt.salt).await { + Ok(_) => { + match repo::user::update_password( + &pool, + &user, + &updated_hashed_password, + ) + .await + { + Ok(_) => { + response.message = "Successful".to_string(); + response.data.push(user.id); + (axum::http::StatusCode::OK, axum::Json(response)) + } + Err(err) => { + response.message = err.to_string(); + ( + axum::http::StatusCode::INTERNAL_SERVER_ERROR, + axum::Json(response), + ) + } + } + } + Err(err) => { + response.message = err.to_string(); + (axum::http::StatusCode::BAD_REQUEST, axum::Json(response)) + } + } + } + Err(err) => { + response.message = err.to_string(); + (axum::http::StatusCode::BAD_REQUEST, axum::Json(response)) + } + } + } else { + response.message = "Invalid".to_string(); + (axum::http::StatusCode::BAD_REQUEST, axum::Json(response)) + } + } + Err(err) => { + response.message = err.to_string(); + (axum::http::StatusCode::BAD_REQUEST, axum::Json(response)) + } + } + } } diff --git a/src/callers/mod.rs b/src/callers/mod.rs index f280a4f..512f720 100644 --- a/src/callers/mod.rs +++ b/src/callers/mod.rs @@ -7,6 +7,7 @@ pub mod endpoints { pub const REGISTER: &str = "/api/v2/register"; pub const DBTEST: &str = "/api/v2/test/db"; pub const LOGIN: &str = "/api/v2/login"; + pub const UPDATE_PASSWORD: &str = "/api/v2/user/password"; pub const SERVICE_LOGIN: &str = "/api/v2/service/login"; pub const REFRESH_TOKEN: &str = "/api/v2/token/refresh"; } diff --git a/src/main.rs b/src/main.rs index 71ef3ba..c0e947c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -21,7 +21,7 @@ async fn main() { mod init { use axum::{ Router, - routing::{get, post}, + routing::{get, patch, post}, }; use utoipa::OpenApi; @@ -38,11 +38,11 @@ mod init { paths( common_callers::endpoint::db_ping, common_callers::endpoint::root, register_caller::register_user, - login_endpoints::login, login_endpoints::service_login, login_endpoints::refresh_token + login_endpoints::login, login_endpoints::update_password, login_endpoints::service_login, login_endpoints::refresh_token ), components(schemas(common_callers::response::TestResult, register_responses::Response, - login_responses::Response, login_responses::service_login::Response, login_responses::refresh_token::Response)), + login_responses::Response, login_responses::service_login::Response, login_responses::update_password::Response, login_responses::refresh_token::Response)), tags( (name = "soaricarus Auth API", description = "Auth API for soaricarus API") ) @@ -51,20 +51,20 @@ mod init { mod cors { pub async fn configure_cors() -> tower_http::cors::CorsLayer { - // Start building the CORS layer with common settings let cors = tower_http::cors::CorsLayer::new() .allow_methods([ axum::http::Method::GET, + axum::http::Method::PATCH, axum::http::Method::POST, axum::http::Method::PUT, axum::http::Method::DELETE, - ]) // Specify allowed methods:cite[2] + ]) .allow_headers([ axum::http::header::CONTENT_TYPE, axum::http::header::AUTHORIZATION, - ]) // Specify allowed headers:cite[2] - .allow_credentials(true) // If you need to send cookies or authentication headers:cite[2] - .max_age(std::time::Duration::from_secs(3600)); // Cache the preflight response for 1 hour:cite[2] + ]) + .allow_credentials(true) + .max_age(std::time::Duration::from_secs(3600)); // Dynamically set the allowed origin based on the environment match std::env::var(sienvy::keys::APP_ENV).as_deref() { @@ -116,6 +116,10 @@ mod init { callers::endpoints::LOGIN, post(callers::login::endpoint::login), ) + .route( + callers::endpoints::UPDATE_PASSWORD, + patch(callers::login::endpoint::update_password), + ) .route( callers::endpoints::SERVICE_LOGIN, post(callers::login::endpoint::service_login), @@ -247,6 +251,27 @@ mod tests { }) } + fn get_test_login_payload(usr: &callers::login::request::Request) -> serde_json::Value { + json!({ + "username": &usr.username, + "password": &usr.password, + }) + } + + pub mod test_data { + use serde_json::json; + + pub fn get_updated_password(user_id: &uuid::Uuid) -> serde_json::Value { + json!({ + "username": "somethingsss", + "user_id": user_id, + "current_password": "Raindown!", + "updated_password": "SpeakWithUrChest22!", + "confirmed_password": "SpeakWithUrChest22!" + }) + } + } + pub mod requests { use tower::ServiceExt; // for `call`, `oneshot`, and `ready` @@ -264,6 +289,36 @@ mod tests { app.clone().oneshot(req).await } + + pub async fn login( + app: &axum::Router, + usr: &super::callers::login::request::Request, + ) -> Result { + let payload = super::get_test_login_payload(&usr); + let req = axum::http::Request::builder() + .method(axum::http::Method::POST) + .uri(crate::callers::endpoints::LOGIN) + .header(axum::http::header::CONTENT_TYPE, "application/json") + .body(axum::body::Body::from(payload.to_string())) + .unwrap(); + + app.clone().oneshot(req).await + } + + pub async fn update_password( + app: &axum::Router, + user_id: &uuid::Uuid, + ) -> Result { + let payload = super::test_data::get_updated_password(user_id); + let req = axum::http::Request::builder() + .method(axum::http::Method::PATCH) + .uri(crate::callers::endpoints::UPDATE_PASSWORD) + .header(axum::http::header::CONTENT_TYPE, "application/json") + .body(axum::body::Body::from(payload.to_string())) + .unwrap(); + + app.clone().oneshot(req).await + } } #[tokio::test] @@ -394,22 +449,11 @@ mod tests { ); assert!(returned_usr.date_created.is_some(), "Date Created is empty"); - let login_payload = json!({ - "username": &usr.username, - "password": &usr.password, - }); + let mut n_usr = callers::login::request::Request::default(); + n_usr.username = usr.username.clone(); + n_usr.password = usr.password.clone(); - match app - .oneshot( - Request::builder() - .method(axum::http::Method::POST) - .uri(callers::endpoints::LOGIN) - .header(axum::http::header::CONTENT_TYPE, "application/json") - .body(Body::from(login_payload.to_string())) - .unwrap(), - ) - .await - { + match requests::login(&app, &n_usr).await { Ok(resp) => { assert_eq!(StatusCode::OK, resp.status(), "Status is not right"); let body = axum::body::to_bytes(resp.into_body(), usize::MAX) @@ -553,4 +597,96 @@ mod tests { let _ = db_mgr::drop_database(&tm_pool, &db_name).await; } + + #[tokio::test] + async fn test_update_password() { + let tm_pool = db_mgr::get_pool().await.unwrap(); + + let db_name = db_mgr::generate_db_name().await; + + match db_mgr::create_database(&tm_pool, &db_name).await { + Ok(_) => { + println!("Success"); + } + Err(e) => { + assert!(false, "Error: {:?}", e.to_string()); + } + } + + let pool = db_mgr::connect_to_db(&db_name).await.unwrap(); + + db::init::migrations(&pool).await; + + let app = init::routes().await.layer(axum::Extension(pool)); + + let usr = get_test_register_request(); + + match requests::register(&app, &usr).await { + Ok(resp) => { + assert_eq!( + resp.status(), + StatusCode::CREATED, + "Message: {:?} {:?}", + resp, + usr.username + ); + let body = axum::body::to_bytes(resp.into_body(), usize::MAX) + .await + .unwrap(); + let parsed_body: callers::register::response::Response = + serde_json::from_slice(&body).unwrap(); + let returned_usr = &parsed_body.data[0]; + + assert_eq!(false, returned_usr.id.is_nil(), "Id is not populated"); + + assert_eq!( + usr.username, returned_usr.username, + "Usernames do not match" + ); + assert!(returned_usr.date_created.is_some(), "Date Created is empty"); + + let mut n_usr = callers::login::request::Request::default(); + n_usr.username = usr.username.clone(); + n_usr.password = usr.password.clone(); + + match requests::login(&app, &n_usr).await { + Ok(resp) => { + assert_eq!(StatusCode::OK, resp.status(), "Status is not right"); + let body = axum::body::to_bytes(resp.into_body(), usize::MAX) + .await + .unwrap(); + let parsed_body: callers::login::response::Response = + serde_json::from_slice(&body).unwrap(); + let login_result = &parsed_body.data[0]; + assert!(!login_result.id.is_nil(), "Id is nil"); + + match requests::update_password(&app, &login_result.id).await { + Ok(resp) => { + assert_eq!(StatusCode::OK, resp.status(), "Status is not right"); + let body = axum::body::to_bytes(resp.into_body(), usize::MAX) + .await + .unwrap(); + let parsed_body: callers::login::response::update_password::Response = + serde_json::from_slice(&body).unwrap(); + let id = parsed_body.data[0]; + + assert_eq!(id, login_result.id, "Ids do not match"); + } + Err(err) => { + assert!(false, "Error: {err:?}"); + } + } + } + Err(err) => { + assert!(false, "Error: {:?}", err.to_string()); + } + } + } + Err(err) => { + assert!(false, "Error: {err:?}"); + } + } + + let _ = db_mgr::drop_database(&tm_pool, &db_name).await; + } } diff --git a/src/repo/mod.rs b/src/repo/mod.rs index b127180..3346e6c 100644 --- a/src/repo/mod.rs +++ b/src/repo/mod.rs @@ -44,6 +44,32 @@ pub mod user { } } + pub async fn update_password( + pool: &sqlx::PgPool, + user: &simodels::user::User, + password: &str, + ) -> Result { + match sqlx::query( + r#" + UPDATE "user" SET password = $1 WHERE id = $2 + "#, + ) + .bind(password) + .bind(user.id) + .execute(pool) + .await + { + Ok(r) => { + if r.rows_affected() > 0 { + Ok(true) + } else { + Ok(false) + } + } + Err(err) => Err(err), + } + } + pub async fn update_last_login( pool: &sqlx::PgPool, user: &simodels::user::User, @@ -196,4 +222,30 @@ pub mod salt { Err(sqlx::Error::RowNotFound) } } + + pub async fn update_salt( + pool: &sqlx::PgPool, + salt: &simodels::user::salt::Salt, + updated_salt: &str, + ) -> Result { + match sqlx::query( + r#" + UPDATE "salt" SET salt = $1 WHERE id = $2 + "#, + ) + .bind(updated_salt) + .bind(salt.id) + .execute(pool) + .await + { + Ok(row) => { + if row.rows_affected() > 0 { + Ok(true) + } else { + Ok(false) + } + } + Err(err) => Err(err), + } + } }