Update password (#6)
Release Tagging / release (push) Successful in 55s
soaricarus_auth Build / Clippy (push) Successful in 56s
soaricarus_auth Build / Rustfmt (push) Successful in 1m0s
soaricarus_auth Build / Check (push) Successful in 1m8s
soaricarus_auth Build / Test Suite (push) Successful in 1m8s
soaricarus_auth Build / build (push) Successful in 1m7s
soaricarus_auth Build / Check (pull_request) Successful in 3m42s
soaricarus_auth Build / Test Suite (pull_request) Successful in 4m2s
soaricarus_auth Build / Rustfmt (pull_request) Successful in 21s
soaricarus_auth Build / Clippy (pull_request) Successful in 2m58s
soaricarus_auth Build / build (pull_request) Successful in 4m7s
Release Tagging / release (push) Successful in 55s
soaricarus_auth Build / Clippy (push) Successful in 56s
soaricarus_auth Build / Rustfmt (push) Successful in 1m0s
soaricarus_auth Build / Check (push) Successful in 1m8s
soaricarus_auth Build / Test Suite (push) Successful in 1m8s
soaricarus_auth Build / build (push) Successful in 1m7s
soaricarus_auth Build / Check (pull_request) Successful in 3m42s
soaricarus_auth Build / Test Suite (pull_request) Successful in 4m2s
soaricarus_auth Build / Rustfmt (pull_request) Successful in 21s
soaricarus_auth Build / Clippy (pull_request) Successful in 2m58s
soaricarus_auth Build / build (pull_request) Successful in 4m7s
Reviewed-on: #6
This commit was merged in pull request #6.
This commit is contained in:
Generated
+3
-3
@@ -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",
|
||||
|
||||
+2
-2
@@ -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]
|
||||
|
||||
@@ -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<simodels::login_result::LoginResult>,
|
||||
}
|
||||
}
|
||||
|
||||
pub mod update_password {
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Default, Deserialize, Serialize, utoipa::ToSchema)]
|
||||
pub struct Response {
|
||||
pub message: String,
|
||||
pub data: Vec<uuid::Uuid>,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<sqlx::PgPool>,
|
||||
axum::Json(payload): axum::Json<super::request::update_password::Request>,
|
||||
) -> (
|
||||
axum::http::StatusCode,
|
||||
axum::Json<super::response::update_password::Response>,
|
||||
) {
|
||||
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))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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";
|
||||
}
|
||||
|
||||
+159
-23
@@ -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<axum::response::Response, std::convert::Infallible> {
|
||||
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<axum::response::Response, std::convert::Infallible> {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,6 +44,32 @@ pub mod user {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn update_password(
|
||||
pool: &sqlx::PgPool,
|
||||
user: &simodels::user::User,
|
||||
password: &str,
|
||||
) -> Result<bool, sqlx::Error> {
|
||||
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<bool, sqlx::Error> {
|
||||
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),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user