diff --git a/Cargo.lock b/Cargo.lock index cbdfbb2..fbc37a0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2213,7 +2213,7 @@ dependencies = [ [[package]] name = "textsender_auth" -version = "0.1.18" +version = "0.1.19" dependencies = [ "argon2", "async-std", diff --git a/Cargo.toml b/Cargo.toml index 8ac862d..173aa37 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "textsender_auth" -version = "0.1.18" +version = "0.1.19" edition = "2024" rust-version = "1.95" diff --git a/src/callers/login.rs b/src/callers/login.rs index e39fc3d..60ad921 100644 --- a/src/callers/login.rs +++ b/src/callers/login.rs @@ -37,6 +37,28 @@ pub mod request { pub struct RefreshTokenRequest { pub access_token: String, } + + #[derive(Deserialize, utoipa::ToSchema)] + pub struct UpdatePasswordRequest { + pub user_id: uuid::Uuid, + pub current_password: String, + pub updated_password: String, + pub confirmed_password: String, + } + + impl UpdatePasswordRequest { + pub fn is_valid(&self) -> bool { + if self.user_id.is_nil() + || self.current_password.is_empty() + || self.updated_password.is_empty() + || self.confirmed_password.is_empty() + { + false + } else { + self.updated_password == self.confirmed_password + } + } + } } pub mod response { @@ -68,6 +90,12 @@ pub mod response { pub message: String, pub data: Vec, } + + #[derive(Deserialize, Serialize, utoipa::ToSchema)] + pub struct UpdatePasswordResponse { + pub message: String, + pub data: Vec, + } } /// Endpoint for a user login @@ -509,3 +537,181 @@ pub async fn refresh_token( } } } + +/// Endpoint for a updating password +#[utoipa::path( + patch, + path = super::endpoints::UPDATE_PASSWORD, + request_body( + content = request::UpdatePasswordRequest, + description = "Data required to update password", + content_type = "application/json" + ), + responses( + (status = 200, description = "User login successful", body = response::UpdatePasswordResponse), + (status = 400, description = "Bad data", body = response::UpdatePasswordResponse), + (status = 500, description = "Something went wrong", body = response::UpdatePasswordResponse) + ) +)] +pub async fn update_password( + axum::Extension(pool): axum::Extension, + axum::Json(payload): axum::Json, +) -> ( + axum::http::StatusCode, + axum::Json, +) { + if !payload.is_valid() { + ( + axum::http::StatusCode::BAD_REQUEST, + axum::Json(response::UpdatePasswordResponse { + message: String::from("Invalid passwords"), + data: Vec::new(), + }), + ) + } else { + let verify_password = |current_password, hashed_password| -> Result { + match hashing::verify_password(current_password, hashed_password) { + Ok(matches) => Ok(matches), + Err(err) => Err(std::io::Error::other(err.to_string())), + } + }; + + match repo::user::get_with_id(&pool, &payload.user_id).await { + Ok(user) => { + let hashed_password = user.password.clone(); + match verify_password(&payload.current_password, hashed_password) { + Ok(matches) => { + if matches { + let (generate_salt, mut salt) = super::register::generate_the_salt(); + salt.id = repo::salt::insert(&pool, &salt).await.unwrap(); + let updated_hashed_password = match hashing::hash_password( + &payload.updated_password, + &generate_salt, + ) { + Ok(hashed) => hashed, + Err(err) => { + eprintln!("Error: {err:?}"); + String::new() + } + }; + + match repo::user::update_password( + &pool, + &user, + &updated_hashed_password, + ) + .await + { + Ok(()) => ( + axum::http::StatusCode::OK, + axum::Json(response::UpdatePasswordResponse { + message: String::from(super::messages::SUCCESSFUL_MESSAGE), + data: vec![user.id], + }), + ), + Err(err) => ( + axum::http::StatusCode::INTERNAL_SERVER_ERROR, + axum::Json(response::UpdatePasswordResponse { + message: err.to_string(), + data: Vec::new(), + }), + ), + } + } else { + ( + axum::http::StatusCode::INTERNAL_SERVER_ERROR, + axum::Json(response::UpdatePasswordResponse { + message: String::from("Issue updating password"), + data: Vec::new(), + }), + ) + } + } + Err(err) => ( + axum::http::StatusCode::INTERNAL_SERVER_ERROR, + axum::Json(response::UpdatePasswordResponse { + message: err.to_string(), + data: Vec::new(), + }), + ), + } + } + Err(err) => { + println!("No User found, trying Service User: {err:?}"); + + // Try service user + match repo::service::get(&pool, &payload.user_id).await { + Ok(service_user) => { + let hashed_password = service_user.passphrase.clone(); + match verify_password(&payload.current_password, hashed_password) { + Ok(matches) => { + if matches { + let (generate_salt, mut salt) = + super::register::generate_the_salt(); + salt.id = repo::salt::insert(&pool, &salt).await.unwrap(); + let updated_hashed_password = match hashing::hash_password( + &payload.updated_password, + &generate_salt, + ) { + Ok(hashed) => hashed, + Err(err) => { + eprintln!("Error: {err:?}"); + String::new() + } + }; + + match repo::service::update_passphrase( + &pool, + &service_user, + &updated_hashed_password, + ) + .await + { + Ok(()) => ( + axum::http::StatusCode::OK, + axum::Json(response::UpdatePasswordResponse { + message: String::from( + super::messages::SUCCESSFUL_MESSAGE, + ), + data: vec![service_user.id], + }), + ), + Err(err) => ( + axum::http::StatusCode::INTERNAL_SERVER_ERROR, + axum::Json(response::UpdatePasswordResponse { + message: err.to_string(), + data: Vec::new(), + }), + ), + } + } else { + ( + axum::http::StatusCode::INTERNAL_SERVER_ERROR, + axum::Json(response::UpdatePasswordResponse { + message: String::from("Issue updating password"), + data: Vec::new(), + }), + ) + } + } + Err(err) => ( + axum::http::StatusCode::INTERNAL_SERVER_ERROR, + axum::Json(response::UpdatePasswordResponse { + message: err.to_string(), + data: Vec::new(), + }), + ), + } + } + Err(err) => ( + axum::http::StatusCode::INTERNAL_SERVER_ERROR, + axum::Json(response::UpdatePasswordResponse { + message: err.to_string(), + data: Vec::new(), + }), + ), + } + } + } + } +} diff --git a/src/callers/mod.rs b/src/callers/mod.rs index 7a05735..cbd82aa 100644 --- a/src/callers/mod.rs +++ b/src/callers/mod.rs @@ -15,4 +15,6 @@ pub mod endpoints { pub const LOGIN_SERVICE_USER: &str = "/api/v1/service/login"; /// Endpoint constant for refresh token pub const REFRESH_TOKEN: &str = "/api/v1/token/refresh"; + /// Endpoint constant for updating password + pub const UPDATE_PASSWORD: &str = "/api/v1/user/password/update"; } diff --git a/src/callers/register.rs b/src/callers/register.rs index 3474d75..3ac4747 100644 --- a/src/callers/register.rs +++ b/src/callers/register.rs @@ -59,7 +59,7 @@ pub mod response { } } -fn generate_the_salt() -> ( +pub fn generate_the_salt() -> ( argon2::password_hash::SaltString, textsender_models::user::Salt, ) { diff --git a/src/lib.rs b/src/lib.rs index 0a92e92..fbfa407 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -8,7 +8,7 @@ pub mod token_stuff; pub mod init { use axum::{ Router, - routing::{get, post}, + routing::{get, patch, post}, }; use utoipa::OpenApi; @@ -110,6 +110,10 @@ pub mod init { callers::endpoints::REFRESH_TOKEN, post(callers::login::refresh_token), ) + .route( + callers::endpoints::UPDATE_PASSWORD, + patch(callers::login::update_password), + ) .layer(cors::configure_cors().await) } diff --git a/src/repo/mod.rs b/src/repo/mod.rs index f7aeaad..d0ff331 100644 --- a/src/repo/mod.rs +++ b/src/repo/mod.rs @@ -104,6 +104,32 @@ pub mod user { } } + pub async fn update_password( + pool: &sqlx::PgPool, + user: &textsender_models::user::User, + updated_hashed_password: &String, + ) -> Result<(), sqlx::Error> { + match sqlx::query( + r#" + UPDATE "user" SET password = $1 WHERE id = $2 + "#, + ) + .bind(updated_hashed_password) + .bind(user.id) + .execute(pool) + .await + { + Ok(row) => { + if row.rows_affected() > 0 { + Ok(()) + } else { + Err(sqlx::Error::RowNotFound) + } + } + Err(err) => Err(err), + } + } + pub async fn exists(pool: &sqlx::PgPool, username: &String) -> Result { let result = sqlx::query( r#" diff --git a/src/repo/service.rs b/src/repo/service.rs index 078751e..da80247 100644 --- a/src/repo/service.rs +++ b/src/repo/service.rs @@ -154,6 +154,32 @@ pub async fn update_last_login( } } +pub async fn update_passphrase( + pool: &sqlx::PgPool, + user: &textsender_models::user::ServiceUser, + updated_hashed_passphrase: &String, +) -> Result<(), sqlx::Error> { + match sqlx::query( + r#" + UPDATE "service_user" SET passphrase = $1 WHERE id = $2 + "#, + ) + .bind(updated_hashed_passphrase) + .bind(user.id) + .execute(pool) + .await + { + Ok(row) => { + if row.rows_affected() > 0 { + Ok(()) + } else { + Err(sqlx::Error::RowNotFound) + } + } + Err(err) => Err(err), + } +} + pub async fn insert( pool: &sqlx::PgPool, service_user: &textsender_models::user::ServiceUser, diff --git a/tests/tests.rs b/tests/tests.rs index e861f47..e6e09b3 100644 --- a/tests/tests.rs +++ b/tests/tests.rs @@ -171,6 +171,33 @@ pub mod requests { app.clone().oneshot(req).await } + + pub async fn update_password( + app: &axum::Router, + user_id: &uuid::Uuid, + current_password: &str, + updated_password: &str, + confirmed_password: &str, + ) -> Result { + let payload = serde_json::json!({ + "user_id": user_id, + "current_password": current_password, + "updated_password": updated_password, + "confirmed_password": confirmed_password, + }); + match axum::http::Request::builder() + .method(axum::http::Method::PATCH) + .uri(super::callers::endpoints::UPDATE_PASSWORD) + .header(axum::http::header::CONTENT_TYPE, "application/json") + .body(axum::body::Body::from(payload.to_string())) + { + Ok(req) => match app.clone().oneshot(req).await { + Ok(resp) => Ok(resp), + Err(err) => Err(axum::http::Error::from(err)), + }, + Err(err) => Err(err), + } + } } /// Test user firstname @@ -183,11 +210,15 @@ const TEST_USERNAME: &str = "BillyBob01"; const TEST_PASSWORD: &str = "923ndcry392qryudx328qrdy328r"; /// Test user phone number const TEST_PHONE_NUMBER: &str = "+10123456789"; +/// Test updated user password +const TEST_UPDATED_PASSWORD: &str = "3cnf29ry8q27i3yrc928qi37ryndxc2198q7yd9xzq12837e"; /// Test service username const TEST_SERVICE_USERNAME: &str = "swoon"; /// Test service passphrase const TEST_SERVICE_PASSPHRASE: &str = "4n5cf349tfy34w857ty39wq45nfdq23"; +/// Test updated service user passphrase +const TEST_SERVICE_UPDATED_PASSPHRASE: &str = "3487ncfyth934287fcrty32487fry32in7"; mod util { pub async fn convert_response( @@ -378,6 +409,50 @@ mod flow { Err(err) => Err(std::io::Error::other(err.to_string())), } } + + pub async fn update_password( + app: &axum::Router, + user_id: &uuid::Uuid, + current_password: &str, + updated_password: &str, + confirmed_password: &str, + ) -> Result { + match requests::update_password( + app, + user_id, + current_password, + updated_password, + confirmed_password, + ) + .await + { + Ok(response) => { + if axum::http::StatusCode::OK != response.status() { + Err(std::io::Error::other(format!( + "Status code is off {:?}", + response.status() + ))) + } else { + match util::convert_response::( + response, + ) + .await + { + Ok(response) => { + if response.data.len() > 0 { + let id = response.data[0].clone(); + Ok(id) + } else { + Err(std::io::Error::other("No data returned")) + } + } + Err(err) => Err(err), + } + } + } + Err(err) => Err(std::io::Error::other(err.to_string())), + } + } } #[tokio::test] @@ -671,3 +746,110 @@ async fn test_refresh_token() { } } } + +#[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)); + + match flow::register_user(&app).await { + Ok(user) => match flow::login_user(&app, &user.username, TEST_PASSWORD).await { + Ok(login_result) => { + assert_eq!( + false, + login_result.access_token.is_empty(), + "Access token is empty when it should not be" + ); + + match flow::update_password( + &app, + &user.id, + TEST_PASSWORD, + TEST_UPDATED_PASSWORD, + TEST_UPDATED_PASSWORD, + ) + .await + { + Ok(id) => { + assert_eq!(id, user.id, "Ids do not match"); + } + Err(err) => { + assert!(false, "Error: {err:?}"); + } + } + } + Err(err) => { + assert!(false, "Error: {err:?}"); + } + }, + Err(err) => { + assert!(false, "Error: {err:?}"); + } + } + + match flow::register_service_user(&app).await { + Ok(service_user) => { + assert_eq!( + false, + service_user.id.is_nil(), + "The service user id should not be nil" + ); + match flow::login_service_user(&app, TEST_SERVICE_USERNAME, TEST_SERVICE_PASSPHRASE) + .await + { + Ok(login_result) => { + assert_eq!( + false, + login_result.access_token.is_empty(), + "Access token is empty when it should not be" + ); + + match flow::update_password( + &app, + &service_user.id, + TEST_SERVICE_PASSPHRASE, + TEST_SERVICE_UPDATED_PASSPHRASE, + TEST_SERVICE_UPDATED_PASSPHRASE, + ) + .await + { + Ok(id) => { + assert_eq!(id, service_user.id, "Ids do not match"); + } + Err(err) => { + assert!(false, "Error: {err:?}"); + } + } + } + Err(err) => { + assert!(false, "Error: {err:?}"); + } + } + } + Err(err) => { + assert!(false, "Error: {err:?}"); + } + } + + match db_mgr::drop_database(&tm_pool, &db_name).await { + Ok(()) => {} + Err(err) => { + assert!(false, "Error: {err:?}"); + } + } +}