Compare commits

...
4 Commits
Author SHA1 Message Date
phoenix 453538582b tsk-14: bump: soaricarus_auth
soaricarus_auth Build / Rustfmt (pull_request) Successful in 30s
soaricarus_auth Build / Clippy (pull_request) Failing after 1m55s
soaricarus_auth Build / build (pull_request) Successful in 2m6s
soaricarus_auth Build / Check (pull_request) Successful in 2m37s
soaricarus_auth Build / Test Suite (pull_request) Successful in 2m46s
2026-11-10 21:45:05 -05:00
phoenix aa4b7d34db tsk-14: cargo fmt 2026-11-10 21:44:40 -05:00
phoenix 70c64cdaf7 tsk-14: Adding test 2026-11-10 21:44:23 -05:00
phoenix 5b9b852c8d tsk-14: Reorganized some things 2026-11-10 21:31:40 -05:00
5 changed files with 316 additions and 160 deletions

No files matched your search

Generated
+1 -1
View File
@@ -1526,7 +1526,7 @@ dependencies = [
[[package]] [[package]]
name = "soaricarus_auth" name = "soaricarus_auth"
version = "0.8.8" version = "0.8.9"
dependencies = [ dependencies = [
"argon2", "argon2",
"axum", "axum",
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "soaricarus_auth" name = "soaricarus_auth"
version = "0.8.8" version = "0.8.9"
edition = "2024" edition = "2024"
rust-version = "1.95" rust-version = "1.95"
license = "MIT" license = "MIT"
+25 -11
View File
@@ -51,7 +51,7 @@ pub mod request {
pub struct UpdateUserProfileRequest { pub struct UpdateUserProfileRequest {
pub user_id: uuid::Uuid, pub user_id: uuid::Uuid,
pub firstname: String, pub firstname: String,
pub lastname: String pub lastname: String,
} }
impl UpdateUserProfileRequest { impl UpdateUserProfileRequest {
@@ -115,7 +115,6 @@ pub mod response {
pub message: String, pub message: String,
pub data: Vec<simodels::user::UserProfile>, pub data: Vec<simodels::user::UserProfile>,
} }
} }
} }
@@ -489,10 +488,17 @@ pub mod endpoint {
(status = 500, description = "Failure", body = super::response::update_user_profile::UpdateUserProfileResponse) (status = 500, description = "Failure", body = super::response::update_user_profile::UpdateUserProfileResponse)
) )
)] )]
pub async fn update_user_profile(axum::Extension(pool): axum::Extension<sqlx::PgPool>, pub async fn update_user_profile(
axum::Json(payload): axum::Json<super::request::update_user_profile::UpdateUserProfileRequest>, axum::Extension(pool): axum::Extension<sqlx::PgPool>,
) -> (axum::http::StatusCode, axum::Json<super::response::update_user_profile::UpdateUserProfileResponse>,) { axum::Json(payload): axum::Json<
let mut response = super::response::update_user_profile::UpdateUserProfileResponse::default(); super::request::update_user_profile::UpdateUserProfileRequest,
>,
) -> (
axum::http::StatusCode,
axum::Json<super::response::update_user_profile::UpdateUserProfileResponse>,
) {
let mut response =
super::response::update_user_profile::UpdateUserProfileResponse::default();
if !payload.is_valid() { if !payload.is_valid() {
response.message = "Invalid".to_string(); response.message = "Invalid".to_string();
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response)) (axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
@@ -502,7 +508,9 @@ pub mod endpoint {
Ok(user) => { Ok(user) => {
let firstname = payload.firstname; let firstname = payload.firstname;
let lastname = payload.lastname; let lastname = payload.lastname;
match repo::user::update_user_profile(&pool, &user_id, &firstname, &lastname).await { match repo::user::update_user_profile(&pool, &user_id, &firstname, &lastname)
.await
{
Ok(_) => { Ok(_) => {
let user_profile = simodels::user::UserProfile { let user_profile = simodels::user::UserProfile {
firstname, firstname,
@@ -513,18 +521,24 @@ pub mod endpoint {
response.message = "SUCCESSFUL".to_string(); response.message = "SUCCESSFUL".to_string();
response.data.push(user_profile); response.data.push(user_profile);
(axum::http::StatusCode::OK, axum::Json(response)) (axum::http::StatusCode::OK, axum::Json(response))
}, }
Err(err) => { Err(err) => {
eprintln!("Error: {err:?}"); eprintln!("Error: {err:?}");
response.message = "ERROR - Updating user profile".to_string(); response.message = "ERROR - Updating user profile".to_string();
(axum::http::StatusCode::INTERNAL_SERVER_ERROR, axum::Json(response)) (
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response),
)
}
} }
} }
},
Err(err) => { Err(err) => {
eprintln!("Error: {err:?}"); eprintln!("Error: {err:?}");
response.message = "ERROR".to_string(); response.message = "ERROR".to_string();
(axum::http::StatusCode::INTERNAL_SERVER_ERROR, axum::Json(response)) (
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response),
)
} }
} }
} }
+145
View File
@@ -0,0 +1,145 @@
pub mod callers;
pub mod config;
pub mod db;
pub mod hashing;
pub mod repo;
pub mod token_stuff;
pub mod init {
use axum::{
Router,
routing::{get, patch, post, put},
};
use utoipa::OpenApi;
use super::callers;
use callers::common as common_callers;
use callers::login as login_caller;
use callers::register as register_caller;
use login_caller::endpoint as login_endpoints;
use login_caller::response as login_responses;
use register_caller::response as register_responses;
#[derive(utoipa::OpenApi)]
#[openapi(
paths(
common_callers::endpoint::db_ping, common_callers::endpoint::root,
register_caller::register_user,
login_endpoints::login, login_endpoints::update_password, login_endpoints::service_login, login_endpoints::refresh_token, login_endpoints::get_user_profile,
),
components(schemas(common_callers::response::TestResult,
register_responses::Response,
login_responses::Response, login_responses::service_login::Response, login_responses::update_password::Response, login_responses::refresh_token::Response, login_responses::get_user_profile::GetUserProfileResponse)),
tags(
(name = "soaricarus Auth API", description = "Auth API for soaricarus API")
)
)]
struct ApiDoc;
mod cors {
pub async fn configure_cors() -> tower_http::cors::CorsLayer {
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,
])
.allow_headers([
axum::http::header::CONTENT_TYPE,
axum::http::header::AUTHORIZATION,
])
.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() {
Ok("production") => {
let allowed_origins_env = sienvy::environment::get_allowed_origins();
match sienvy::utility::delimitize(&allowed_origins_env) {
Ok(alwd) => {
let allowed_origins: Vec<axum::http::HeaderValue> = alwd
.into_iter()
.map(|s| s.parse::<axum::http::HeaderValue>().unwrap())
.collect();
cors.allow_origin(allowed_origins)
}
Err(err) => {
eprintln!(
"Could not parse out allowed origins from env: Error: {err:?}"
);
std::process::exit(-1);
}
}
}
_ => {
// Development (default): Allow localhost origins
cors.allow_origin(vec![
"http://localhost:4200".parse().unwrap(),
"http://127.0.0.1:4200".parse().unwrap(),
])
}
}
}
}
pub async fn routes() -> Router {
// build our application with a route
Router::new()
.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),
)
.route(
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),
)
.route(
callers::endpoints::REFRESH_TOKEN,
post(callers::login::endpoint::refresh_token),
)
.route(
callers::endpoints::GET_USER_PROFILE,
get(callers::login::endpoint::get_user_profile),
)
.route(
callers::endpoints::UPDATE_USER_PROFILE,
put(callers::login::endpoint::update_user_profile),
)
.layer(cors::configure_cors().await)
.layer(cors::configure_cors().await)
}
pub async fn app() -> Router {
let pool = super::db::init::create_pool()
.await
.expect("Failed to create pool");
super::db::init::migrations(&pool).await;
routes()
.await
.merge(
utoipa_swagger_ui::SwaggerUi::new("/swagger-ui")
.url("/api-docs/openapi.json", ApiDoc::openapi()),
)
.layer(axum::Extension(pool))
}
}
+144 -147
View File
@@ -1,9 +1,5 @@
pub mod callers; use soaricarus_auth;
pub mod config; use soaricarus_auth::init;
pub mod db;
pub mod hashing;
pub mod repo;
pub mod token_stuff;
#[tokio::main] #[tokio::main]
async fn main() { async fn main() {
@@ -13,148 +9,17 @@ async fn main() {
let app = init::app().await; let app = init::app().await;
// run our app with hyper, listening globally on port 8001 // run our app with hyper, listening globally on port 8001
let url = config::get_full(); let url = soaricarus_auth::config::get_full();
let listener = tokio::net::TcpListener::bind(url).await.unwrap(); let listener = tokio::net::TcpListener::bind(url).await.unwrap();
axum::serve(listener, app).await.unwrap(); axum::serve(listener, app).await.unwrap();
} }
mod init {
use axum::{
Router,
routing::{get, patch, post},
};
use utoipa::OpenApi;
use super::callers;
use callers::common as common_callers;
use callers::login as login_caller;
use callers::register as register_caller;
use login_caller::endpoint as login_endpoints;
use login_caller::response as login_responses;
use register_caller::response as register_responses;
#[derive(utoipa::OpenApi)]
#[openapi(
paths(
common_callers::endpoint::db_ping, common_callers::endpoint::root,
register_caller::register_user,
login_endpoints::login, login_endpoints::update_password, login_endpoints::service_login, login_endpoints::refresh_token, login_endpoints::get_user_profile,
),
components(schemas(common_callers::response::TestResult,
register_responses::Response,
login_responses::Response, login_responses::service_login::Response, login_responses::update_password::Response, login_responses::refresh_token::Response, login_responses::get_user_profile::GetUserProfileResponse)),
tags(
(name = "soaricarus Auth API", description = "Auth API for soaricarus API")
)
)]
struct ApiDoc;
mod cors {
pub async fn configure_cors() -> tower_http::cors::CorsLayer {
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,
])
.allow_headers([
axum::http::header::CONTENT_TYPE,
axum::http::header::AUTHORIZATION,
])
.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() {
Ok("production") => {
let allowed_origins_env = sienvy::environment::get_allowed_origins();
match sienvy::utility::delimitize(&allowed_origins_env) {
Ok(alwd) => {
let allowed_origins: Vec<axum::http::HeaderValue> = alwd
.into_iter()
.map(|s| s.parse::<axum::http::HeaderValue>().unwrap())
.collect();
cors.allow_origin(allowed_origins)
}
Err(err) => {
eprintln!(
"Could not parse out allowed origins from env: Error: {err:?}"
);
std::process::exit(-1);
}
}
}
_ => {
// Development (default): Allow localhost origins
cors.allow_origin(vec![
"http://localhost:4200".parse().unwrap(),
"http://127.0.0.1:4200".parse().unwrap(),
])
}
}
}
}
pub async fn routes() -> Router {
// build our application with a route
Router::new()
.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),
)
.route(
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),
)
.route(
callers::endpoints::REFRESH_TOKEN,
post(callers::login::endpoint::refresh_token),
)
.route(
callers::endpoints::GET_USER_PROFILE,
get(callers::login::endpoint::get_user_profile),
)
.layer(cors::configure_cors().await)
}
pub async fn app() -> Router {
let pool = super::db::init::create_pool()
.await
.expect("Failed to create pool");
super::db::init::migrations(&pool).await;
routes()
.await
.merge(
utoipa_swagger_ui::SwaggerUi::new("/swagger-ui")
.url("/api-docs/openapi.json", ApiDoc::openapi()),
)
.layer(axum::Extension(pool))
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use soaricarus_auth;
use soaricarus_auth::callers;
use soaricarus_auth::db;
use axum::{ use axum::{
body::Body, body::Body,
@@ -265,6 +130,9 @@ mod tests {
pub mod test_data { pub mod test_data {
use serde_json::json; use serde_json::json;
pub const UPDATED_FIRSTNAME: &str = "Bolt";
pub const UPDATED_LASTNAME: &str = "Thunder";
pub fn get_updated_password(user_id: &uuid::Uuid) -> serde_json::Value { pub fn get_updated_password(user_id: &uuid::Uuid) -> serde_json::Value {
json!({ json!({
"username": "somethingsss", "username": "somethingsss",
@@ -274,9 +142,22 @@ mod tests {
"confirmed_password": "SpeakWithUrChest22!" "confirmed_password": "SpeakWithUrChest22!"
}) })
} }
pub fn update_user_profile(
user_id: &uuid::Uuid,
firstname: &str,
lastname: &str,
) -> serde_json::Value {
json!({
"firstname": firstname,
"lastname": lastname,
"user_id": user_id
})
}
} }
pub mod requests { pub mod requests {
use soaricarus_auth::callers;
use tower::ServiceExt; // for `call`, `oneshot`, and `ready` use tower::ServiceExt; // for `call`, `oneshot`, and `ready`
pub async fn register( pub async fn register(
@@ -286,7 +167,7 @@ mod tests {
let payload = super::get_test_register_payload(&usr); let payload = super::get_test_register_payload(&usr);
let req = axum::http::Request::builder() let req = axum::http::Request::builder()
.method(axum::http::Method::POST) .method(axum::http::Method::POST)
.uri(crate::callers::endpoints::REGISTER) .uri(callers::endpoints::REGISTER)
.header(axum::http::header::CONTENT_TYPE, "application/json") .header(axum::http::header::CONTENT_TYPE, "application/json")
.body(axum::body::Body::from(payload.to_string())) .body(axum::body::Body::from(payload.to_string()))
.unwrap(); .unwrap();
@@ -301,7 +182,7 @@ mod tests {
let payload = super::get_test_login_payload(&usr); let payload = super::get_test_login_payload(&usr);
let req = axum::http::Request::builder() let req = axum::http::Request::builder()
.method(axum::http::Method::POST) .method(axum::http::Method::POST)
.uri(crate::callers::endpoints::LOGIN) .uri(callers::endpoints::LOGIN)
.header(axum::http::header::CONTENT_TYPE, "application/json") .header(axum::http::header::CONTENT_TYPE, "application/json")
.body(axum::body::Body::from(payload.to_string())) .body(axum::body::Body::from(payload.to_string()))
.unwrap(); .unwrap();
@@ -316,7 +197,7 @@ mod tests {
let payload = super::test_data::get_updated_password(user_id); let payload = super::test_data::get_updated_password(user_id);
let req = axum::http::Request::builder() let req = axum::http::Request::builder()
.method(axum::http::Method::PATCH) .method(axum::http::Method::PATCH)
.uri(crate::callers::endpoints::UPDATE_PASSWORD) .uri(callers::endpoints::UPDATE_PASSWORD)
.header(axum::http::header::CONTENT_TYPE, "application/json") .header(axum::http::header::CONTENT_TYPE, "application/json")
.body(axum::body::Body::from(payload.to_string())) .body(axum::body::Body::from(payload.to_string()))
.unwrap(); .unwrap();
@@ -328,7 +209,7 @@ mod tests {
app: &axum::Router, app: &axum::Router,
user_id: &uuid::Uuid, user_id: &uuid::Uuid,
) -> Result<axum::response::Response, std::convert::Infallible> { ) -> Result<axum::response::Response, std::convert::Infallible> {
let raw_uri = String::from(crate::callers::endpoints::GET_USER_PROFILE); let raw_uri = String::from(callers::endpoints::GET_USER_PROFILE);
let end_index = raw_uri.len() - 4; let end_index = raw_uri.len() - 4;
let uri = format!("{}{user_id}", (&raw_uri[..end_index]).to_string()); let uri = format!("{}{user_id}", (&raw_uri[..end_index]).to_string());
@@ -340,6 +221,28 @@ mod tests {
.unwrap(); .unwrap();
app.clone().oneshot(req).await app.clone().oneshot(req).await
} }
pub async fn update_user_profile(
app: &axum::Router,
user_id: &uuid::Uuid,
firstname: &str,
lastname: &str,
) -> Result<axum::response::Response, std::convert::Infallible> {
let payload = super::test_data::update_user_profile(user_id, firstname, lastname);
let req = axum::http::Request::builder()
.method(axum::http::Method::PUT)
.uri(callers::endpoints::UPDATE_USER_PROFILE)
.header(axum::http::header::CONTENT_TYPE, "application/json")
.body(axum::body::Body::from(payload.to_string()))
.unwrap();
app.clone().oneshot(req).await
}
}
pub mod responses {
pub use soaricarus_auth::callers::login::response as login_responses;
pub use soaricarus_auth::callers::register::response as register_responses;
} }
#[tokio::test] #[tokio::test]
@@ -575,7 +478,7 @@ mod tests {
let id = uuid::Uuid::parse_str("22f9c775-cce9-457a-a147-9dafbb801f61").unwrap(); let id = uuid::Uuid::parse_str("22f9c775-cce9-457a-a147-9dafbb801f61").unwrap();
let key = sienvy::environment::get_secret_key().value; let key = sienvy::environment::get_secret_key().value;
match token_stuff::create_service_token(&key, &id) { match soaricarus_auth::token_stuff::create_service_token(&key, &id) {
Ok((token, _expire)) => { Ok((token, _expire)) => {
let payload = serde_json::json!({ let payload = serde_json::json!({
"access_token": token "access_token": token
@@ -771,7 +674,8 @@ mod tests {
let body = axum::body::to_bytes(resp.into_body(), usize::MAX) let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await .await
.unwrap(); .unwrap();
let parsed_body: callers::login::response::get_user_profile::GetUserProfileResponse =
let parsed_body: responses::login_responses::get_user_profile::GetUserProfileResponse =
serde_json::from_slice(&body).unwrap(); serde_json::from_slice(&body).unwrap();
let user_profile = &parsed_body.data[0]; let user_profile = &parsed_body.data[0];
assert!( assert!(
@@ -791,4 +695,97 @@ mod tests {
let _ = db_mgr::drop_database(&tm_pool, &db_name).await; let _ = db_mgr::drop_database(&tm_pool, &db_name).await;
} }
#[tokio::test]
async fn test_update_user_profile() {
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();
let response = requests::register(&app, &usr).await;
match response {
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: responses::register_responses::Response =
serde_json::from_slice(&body).unwrap();
let returned_usr = &parsed_body.data[0];
let user_id = returned_usr.id;
assert_eq!(false, user_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 updated_firstname = test_data::UPDATED_FIRSTNAME;
let updated_lastname = test_data::UPDATED_LASTNAME;
match requests::update_user_profile(
&app,
&user_id,
&updated_firstname,
&updated_lastname,
)
.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: responses::login_responses::update_user_profile::UpdateUserProfileResponse =
serde_json::from_slice(&body).unwrap();
let user_profile = &parsed_body.data[0];
assert_eq!(
updated_firstname, user_profile.firstname,
"Firstname has not been updated"
);
assert_eq!(
updated_lastname, user_profile.lastname,
"Lastname has not been updated"
);
}
Err(err) => {
assert!(false, "Error: {:?}", err.to_string());
}
}
}
Err(err) => {
assert!(false, "Error: {:?}", err.to_string());
}
};
let _ = db_mgr::drop_database(&tm_pool, &db_name).await;
}
} }