Compare commits

...
Author SHA1 Message Date
phoenix 778be1f4a2 Bump argon2 (#12)
Release Tagging / release (push) Successful in 25s
soaricarus_auth Build / Check (push) Successful in 28s
soaricarus_auth Build / Rustfmt (push) Successful in 21s
soaricarus_auth Build / Test Suite (push) Successful in 43s
soaricarus_auth Build / Clippy (push) Successful in 48s
soaricarus_auth Build / build (push) Successful in 2m6s
soaricarus_auth Build / Rustfmt (pull_request) Successful in 21s
soaricarus_auth Build / Clippy (pull_request) Successful in 28s
soaricarus_auth Build / build (pull_request) Successful in 47s
soaricarus_auth Build / Check (pull_request) Successful in 2m22s
soaricarus_auth Build / Test Suite (pull_request) Successful in 2m42s
Reviewed-on: http://git.kundeng.us/phoenix/soaricarus_auth/pulls/12
2026-11-01 19:18:31 -05:00
phoenix de4c698836 bump: uuid (#11)
soaricarus_auth Build / Check (push) Successful in 20s
Release Tagging / release (push) Successful in 26s
soaricarus_auth Build / Test Suite (push) Successful in 37s
soaricarus_auth Build / Rustfmt (push) Successful in 18s
soaricarus_auth Build / Clippy (push) Successful in 1m40s
soaricarus_auth Build / build (push) Successful in 1m53s
Reviewed-on: http://git.kundeng.us/phoenix/soaricarus_auth/pulls/11
2026-11-01 10:52:10 -05:00
phoenix db9d6f164e Update deps (#10)
soaricarus_auth Build / Rustfmt (push) Successful in 21s
Release Tagging / release (push) Successful in 26s
soaricarus_auth Build / Check (push) Successful in 30s
soaricarus_auth Build / Clippy (push) Successful in 2m29s
soaricarus_auth Build / build (push) Successful in 2m19s
soaricarus_auth Build / Test Suite (push) Successful in 2m41s
Reviewed-on: http://git.kundeng.us/phoenix/soaricarus_auth/pulls/10
2026-10-30 18:12:18 -04:00
phoenix 647bb6a379 Add missing test (#9)
Release Tagging / release (push) Successful in 1m2s
soaricarus_auth Build / Rustfmt (push) Successful in 1m2s
soaricarus_auth Build / Test Suite (push) Successful in 1m4s
soaricarus_auth Build / Check (push) Successful in 1m8s
soaricarus_auth Build / build (push) Successful in 1m5s
soaricarus_auth Build / Clippy (push) Successful in 1m7s
soaricarus_auth Build / Rustfmt (pull_request) Successful in 46s
soaricarus_auth Build / Check (pull_request) Successful in 2m58s
soaricarus_auth Build / Test Suite (pull_request) Successful in 3m31s
soaricarus_auth Build / Clippy (pull_request) Successful in 3m41s
soaricarus_auth Build / build (pull_request) Successful in 3m54s
Reviewed-on: http://git.kundeng.us/phoenix/soaricarus_auth/pulls/9
2026-10-09 13:30:14 -04:00
phoenix 0c0e1bdde3 Get user profile (#7)
soaricarus_auth Build / Check (push) Successful in 58s
soaricarus_auth Build / Rustfmt (push) Successful in 1m1s
Release Tagging / release (push) Successful in 1m2s
soaricarus_auth Build / Clippy (push) Successful in 1m7s
soaricarus_auth Build / build (push) Successful in 1m9s
soaricarus_auth Build / Test Suite (push) Successful in 1m20s
soaricarus_auth Build / Check (pull_request) Successful in 36s
soaricarus_auth Build / Test Suite (pull_request) Successful in 49s
soaricarus_auth Build / Rustfmt (pull_request) Successful in 41s
soaricarus_auth Build / Clippy (pull_request) Successful in 47s
soaricarus_auth Build / build (pull_request) Successful in 37s
Reviewed-on: http://git.kundeng.us/phoenix/soaricarus_auth/pulls/7
2026-10-08 17:17:36 -04:00
phoenix 5ff75f66b8 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 / Rustfmt (pull_request) Successful in 52s
soaricarus_auth Build / Clippy (pull_request) Successful in 2m16s
soaricarus_auth Build / build (pull_request) Successful in 2m30s
soaricarus_auth Build / Check (pull_request) Successful in 4m19s
soaricarus_auth Build / Test Suite (pull_request) Successful in 4m31s
Reviewed-on: http://git.kundeng.us/phoenix/soaricarus_auth/pulls/6
2026-09-22 12:47:43 -04:00
12 changed files with 885 additions and 393 deletions

No files matched your search

+1 -1
View File
@@ -17,7 +17,7 @@ jobs:
- name: Install Rust - name: Install Rust
uses: actions-rs/toolchain@v1 uses: actions-rs/toolchain@v1
with: with:
toolchain: 1.97 toolchain: 1.99
components: cargo components: cargo
- uses: Swatinem/rust-cache@v2 - uses: Swatinem/rust-cache@v2
+6 -6
View File
@@ -16,7 +16,7 @@ jobs:
- uses: actions/checkout@v6 - uses: actions/checkout@v6
- uses: actions-rust-lang/setup-rust-toolchain@v1 - uses: actions-rust-lang/setup-rust-toolchain@v1
with: with:
toolchain: 1.97 toolchain: 1.99
- uses: Swatinem/rust-cache@v2 - uses: Swatinem/rust-cache@v2
- run: | - run: |
mkdir -p ~/.ssh mkdir -p ~/.ssh
@@ -34,7 +34,7 @@ jobs:
runs-on: ubuntu-24.04 runs-on: ubuntu-24.04
services: services:
postgres: postgres:
image: postgres:18.4-alpine image: postgres:18.6-alpine
env: env:
POSTGRES_USER: ${{ secrets.DB_TEST_USER || 'testuser' }} POSTGRES_USER: ${{ secrets.DB_TEST_USER || 'testuser' }}
POSTGRES_PASSWORD: ${{ secrets.DB_TEST_PASSWORD || 'testpassword' }} POSTGRES_PASSWORD: ${{ secrets.DB_TEST_PASSWORD || 'testpassword' }}
@@ -49,7 +49,7 @@ jobs:
- uses: actions/checkout@v6 - uses: actions/checkout@v6
- uses: actions-rust-lang/setup-rust-toolchain@v1 - uses: actions-rust-lang/setup-rust-toolchain@v1
with: with:
toolchain: 1.97 toolchain: 1.99
- uses: Swatinem/rust-cache@v2 - uses: Swatinem/rust-cache@v2
- name: Verify Docker Environment - name: Verify Docker Environment
run: | run: |
@@ -88,7 +88,7 @@ jobs:
- uses: actions/checkout@v6 - uses: actions/checkout@v6
- uses: actions-rust-lang/setup-rust-toolchain@v1 - uses: actions-rust-lang/setup-rust-toolchain@v1
with: with:
toolchain: 1.97 toolchain: 1.99
- uses: Swatinem/rust-cache@v2 - uses: Swatinem/rust-cache@v2
- run: rustup component add rustfmt - run: rustup component add rustfmt
- run: | - run: |
@@ -108,7 +108,7 @@ jobs:
- uses: actions/checkout@v6 - uses: actions/checkout@v6
- uses: actions-rust-lang/setup-rust-toolchain@v1 - uses: actions-rust-lang/setup-rust-toolchain@v1
with: with:
toolchain: 1.97 toolchain: 1.99
- uses: Swatinem/rust-cache@v2 - uses: Swatinem/rust-cache@v2
- run: rustup component add clippy - run: rustup component add clippy
- run: | - run: |
@@ -128,7 +128,7 @@ jobs:
- uses: actions/checkout@v6 - uses: actions/checkout@v6
- uses: actions-rust-lang/setup-rust-toolchain@v1 - uses: actions-rust-lang/setup-rust-toolchain@v1
with: with:
toolchain: 1.97 toolchain: 1.99
- uses: Swatinem/rust-cache@v2 - uses: Swatinem/rust-cache@v2
- run: | - run: |
mkdir -p ~/.ssh mkdir -p ~/.ssh
Generated
+240 -311
View File
File diff suppressed because it is too large. Load diff
+11 -10
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "soaricarus_auth" name = "soaricarus_auth"
version = "0.8.2" version = "0.8.7"
edition = "2024" edition = "2024"
rust-version = "1.95" rust-version = "1.95"
license = "MIT" license = "MIT"
@@ -10,20 +10,21 @@ description = "Auth API for soaricarus"
axum = { version = "0.8.9" } axum = { version = "0.8.9" }
openssl = { version = "0.10.81", features = ["vendored"] } openssl = { version = "0.10.81", features = ["vendored"] }
serde = { version = "1.0.229", features = ["derive"] } serde = { version = "1.0.229", features = ["derive"] }
serde_json = { version = "1.0.151" } serde_json = { version = "1.0.154" }
tokio = { version = "1.53.1", features = ["rt-multi-thread"] } tokio = { version = "1.54.1", features = ["rt-multi-thread"] }
tracing-subscriber = { version = "0.3.23" } tracing-subscriber = { version = "0.3.23" }
tower = { version = "0.5.3", features = ["full"] } tower = { version = "0.5.3", features = ["full"] }
tower-http = { version = "0.7.0", features = ["cors"] } tower-http = { version = "0.7.1", features = ["cors"] }
sqlx = { version = "0.9.0", features = ["postgres", "runtime-tokio", "tls-native-tls", "time", "uuid"] } sqlx = { version = "0.9.0", features = ["postgres", "runtime-tokio", "tls-native-tls", "time", "uuid"] }
uuid = { version = "1.24.1", features = ["v4", "serde"] } uuid = { version = "1.29.0", features = ["v4", "serde"] }
argon2 = { version = "0.5.3", features = ["std"] } argon2 = { version = "0.6.0", features = ["alloc", "getrandom", "rand_core"] }
time = { version = "0.3.55", features = ["macros", "serde"] } time = { version = "0.3.55", features = ["macros", "serde"] }
josekit = { version = "0.10.3" } josekit = { version = "0.10.3" }
utoipa = { version = "5.5.0", features = ["axum_extras"] } utoipa = { version = "6.0.0", features = ["axum_extras", "uuid", "time"] }
utoipa-swagger-ui = { version = "9.0.2", features = ["axum"] } utoipa-swagger-ui = { version = "10.0.2", features = ["axum"] }
simodels = { git = "ssh://git@git.kundeng.us/phoenix/simodels.git", tag = "v0.11.4" } rand = { version = "0.10.3" }
sienvy = { git = "ssh://git@git.kundeng.us/phoenix/sienvy.git", tag = "v0.8.1" } simodels = { git = "ssh://git@git.kundeng.us/phoenix/simodels.git", tag = "v0.11.7" }
sienvy = { git = "ssh://git@git.kundeng.us/phoenix/sienvy.git", tag = "v0.8.2" }
[dev-dependencies] [dev-dependencies]
http-body-util = { version = "0.1.5" } http-body-util = { version = "0.1.5" }
+1 -1
View File
@@ -1,4 +1,4 @@
FROM rust:1.97 as builder FROM rust:1.99 as builder
# Set the working directory inside the container # Set the working directory inside the container
WORKDIR /usr/src/app WORKDIR /usr/src/app
+1 -3
View File
@@ -1,5 +1,3 @@
version: '3.8' # Use a recent version
services: services:
auth_api: auth_api:
build: build:
@@ -16,7 +14,7 @@ services:
restart: unless-stopped restart: unless-stopped
auth_db: auth_db:
image: postgres:18.4-alpine image: postgres:18.6-alpine
container_name: soaricarus_auth_db container_name: soaricarus_auth_db
environment: environment:
POSTGRES_USER: ${POSTGRES_AUTH_USER:-soaricarus_op} POSTGRES_USER: ${POSTGRES_AUTH_USER:-soaricarus_op}
+184
View File
@@ -20,6 +20,29 @@ pub mod request {
pub access_token: String, 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 { pub mod response {
@@ -46,6 +69,26 @@ pub mod response {
pub data: Vec<simodels::login_result::LoginResult>, 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>,
}
}
pub mod get_user_profile {
use serde::{Deserialize, Serialize};
#[derive(Default, Deserialize, Serialize, utoipa::ToSchema)]
pub struct GetUserProfileResponse {
pub message: String,
pub data: Vec<simodels::user::UserProfile>,
}
}
} }
/// Module for login endpoints /// Module for login endpoints
@@ -261,4 +304,145 @@ pub mod endpoint {
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response)) (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().clone(),
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))
}
}
}
/// Endpoint to get user profile
#[utoipa::path(
get,
path = super::super::endpoints::GET_USER_PROFILE,
params(("id" = uuid::Uuid, Path, description = "Get user profile")),
responses(
(status = 200, description = "User profile found", body = super::response::get_user_profile::GetUserProfileResponse),
(status = 404, description = "Song not found", body = super::response::get_user_profile::GetUserProfileResponse),
(status = 400, description = "Error downloading song", body = super::response::get_user_profile::GetUserProfileResponse),
)
)]
pub async fn get_user_profile(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
axum::extract::Path(id): axum::extract::Path<uuid::Uuid>,
) -> (
axum::http::StatusCode,
axum::Json<super::response::get_user_profile::GetUserProfileResponse>,
) {
let mut response = super::response::get_user_profile::GetUserProfileResponse::default();
if id.is_nil() {
response.message = "Invalid request".to_string();
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
} else {
match repo::user::get_with_id(&pool, &id).await {
Ok(user) => {
let user_profile = simodels::user::UserProfile {
firstname: user.firstname,
lastname: user.lastname,
username: user.username,
email: user.email,
};
response.message = "SUCCESSFUL".to_string();
response.data.push(user_profile);
(axum::http::StatusCode::OK, axum::Json(response))
}
Err(err) => {
response.message = err.to_string();
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response),
)
}
}
}
}
} }
+2
View File
@@ -7,6 +7,8 @@ pub mod endpoints {
pub const REGISTER: &str = "/api/v2/register"; pub const REGISTER: &str = "/api/v2/register";
pub const DBTEST: &str = "/api/v2/test/db"; pub const DBTEST: &str = "/api/v2/test/db";
pub const LOGIN: &str = "/api/v2/login"; 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 SERVICE_LOGIN: &str = "/api/v2/service/login";
pub const REFRESH_TOKEN: &str = "/api/v2/token/refresh"; pub const REFRESH_TOKEN: &str = "/api/v2/token/refresh";
pub const GET_USER_PROFILE: &str = "/api/v2/user/profile/{id}";
} }
+1 -1
View File
@@ -93,7 +93,7 @@ pub async fn register_user(
let salt_string = hashing::generate_salt().unwrap(); let salt_string = hashing::generate_salt().unwrap();
let mut salt = simodels::user::salt::Salt::default(); let mut salt = simodels::user::salt::Salt::default();
let generated_salt = salt_string; let generated_salt = salt_string;
salt.salt = generated_salt.to_string(); salt.salt = generated_salt.to_string().clone();
salt.id = repo::salt::insert(&pool, &salt).await.unwrap(); salt.id = repo::salt::insert(&pool, &salt).await.unwrap();
user.salt_id = salt.id; user.salt_id = salt.id;
let hashed_password = let hashed_password =
+49 -23
View File
@@ -1,17 +1,39 @@
use argon2::{ use argon2::{Argon2, PasswordVerifier, password_hash::PasswordHasher};
Argon2, // The Argon2 algorithm struct use rand::distr::SampleString;
PasswordVerifier,
password_hash::{ pub struct SaltString {
PasswordHasher, pub raw: String,
SaltString, pub in_bytes: Vec<u8>,
rand_core::OsRng, // Secure random number generator }
},
impl SaltString {
pub fn generate() -> Result<SaltString, argon2::Error> {
let mut rng = rand::rng();
let s = rand::distr::Alphanumeric.sample_string(&mut rng, 20);
let salt_string = SaltString {
raw: s.to_string(),
in_bytes: s.into_bytes(),
}; };
Ok(salt_string)
}
pub fn from_b64(s: &str) -> Result<SaltString, argon2::password_hash::Error> {
let salt_string = SaltString {
raw: (&s).to_string(),
in_bytes: s.to_string().into_bytes(),
};
Ok(salt_string)
}
pub fn to_string(&self) -> &String {
&self.raw
}
}
pub fn generate_salt() -> Result<SaltString, argon2::Error> { pub fn generate_salt() -> Result<SaltString, argon2::Error> {
// Generate a random salt SaltString::generate()
// SaltString::generate uses OsRng internally for cryptographic security
Ok(SaltString::generate(&mut OsRng))
} }
pub fn get_salt(s: &str) -> Result<SaltString, argon2::password_hash::Error> { pub fn get_salt(s: &str) -> Result<SaltString, argon2::password_hash::Error> {
@@ -24,14 +46,11 @@ pub fn hash_password(
) -> Result<String, argon2::password_hash::Error> { ) -> Result<String, argon2::password_hash::Error> {
let password_bytes = password.as_bytes(); let password_bytes = password.as_bytes();
// Create an Argon2 instance with default parameters (recommended)
// You could customize parameters here if needed, but defaults are strong
let argon2 = Argon2::default(); let argon2 = Argon2::default();
// Hash the password with the salt Ok(argon2
// The output is a PasswordHash string format that includes algorithm, version, .hash_password_with_salt(password_bytes, &salt.in_bytes)?
// parameters, salt, and the hash itself. .to_string())
Ok(argon2.hash_password(password_bytes, salt)?.to_string())
} }
pub fn verify_password( pub fn verify_password(
@@ -49,7 +68,7 @@ pub fn verify_password(
// This automatically uses the correct salt and parameters embedded in `parsed_hash` // This automatically uses the correct salt and parameters embedded in `parsed_hash`
match Argon2::default().verify_password(password_bytes, &parsed_hash) { match Argon2::default().verify_password(password_bytes, &parsed_hash) {
Ok(()) => Ok(true), // Passwords match Ok(()) => Ok(true), // Passwords match
Err(argon2::password_hash::Error::Password) => Ok(false), // Passwords don't match Err(argon2::password_hash::Error::PasswordInvalid) => Ok(false), // Passwords don't match
Err(e) => Err(e), // Some other error occurred (e.g., invalid hash format) Err(e) => Err(e), // Some other error occurred (e.g., invalid hash format)
} }
} }
@@ -58,10 +77,15 @@ pub fn verify_password(
mod tests { mod tests {
use super::*; use super::*;
pub const TEST_PASSWORD: &str = "somethingrandom";
pub const TEST_WRONG_PASSWORD: &str = "Differentanotherlevel";
#[test] #[test]
fn test_hash_password() { fn test_hash_password() {
let some_password = String::from("somethingrandom"); let some_password = String::from(TEST_PASSWORD);
match hash_password(&some_password, &generate_salt().unwrap()) { let salt = generate_salt().unwrap();
match hash_password(&some_password, &salt) {
Ok(p) => match verify_password(&some_password, p.clone()) { Ok(p) => match verify_password(&some_password, p.clone()) {
Ok(res) => { Ok(res) => {
assert_eq!(res, true); assert_eq!(res, true);
@@ -78,8 +102,10 @@ mod tests {
#[test] #[test]
fn test_wrong_password() { fn test_wrong_password() {
let some_password = String::from("somethingrandom"); let some_password = String::from(TEST_PASSWORD);
match hash_password(&some_password, &generate_salt().unwrap()) { let salt = generate_salt().unwrap();
match hash_password(&some_password, &salt) {
Ok(p) => { Ok(p) => {
match verify_password(&some_password, p.clone()) { match verify_password(&some_password, p.clone()) {
Ok(res) => { Ok(res) => {
@@ -89,7 +115,7 @@ mod tests {
assert!(false, "Error: {:?}", err.to_string()); assert!(false, "Error: {:?}", err.to_string());
} }
} }
let wrong_password = String::from("Differentanotherlevel"); let wrong_password = String::from(TEST_WRONG_PASSWORD);
let result = verify_password(&wrong_password, p.clone()).unwrap(); let result = verify_password(&wrong_password, p.clone()).unwrap();
assert_eq!(false, result, "Passwords should not match"); assert_eq!(false, result, "Passwords should not match");
} }
+261 -23
View File
@@ -21,7 +21,7 @@ async fn main() {
mod init { mod init {
use axum::{ use axum::{
Router, Router,
routing::{get, post}, routing::{get, patch, post},
}; };
use utoipa::OpenApi; use utoipa::OpenApi;
@@ -38,11 +38,11 @@ mod init {
paths( paths(
common_callers::endpoint::db_ping, common_callers::endpoint::root, common_callers::endpoint::db_ping, common_callers::endpoint::root,
register_caller::register_user, 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, login_endpoints::get_user_profile,
), ),
components(schemas(common_callers::response::TestResult, components(schemas(common_callers::response::TestResult,
register_responses::Response, 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, login_responses::get_user_profile::GetUserProfileResponse)),
tags( tags(
(name = "soaricarus Auth API", description = "Auth API for soaricarus API") (name = "soaricarus Auth API", description = "Auth API for soaricarus API")
) )
@@ -51,20 +51,20 @@ mod init {
mod cors { mod cors {
pub async fn configure_cors() -> tower_http::cors::CorsLayer { pub async fn configure_cors() -> tower_http::cors::CorsLayer {
// Start building the CORS layer with common settings
let cors = tower_http::cors::CorsLayer::new() let cors = tower_http::cors::CorsLayer::new()
.allow_methods([ .allow_methods([
axum::http::Method::GET, axum::http::Method::GET,
axum::http::Method::PATCH,
axum::http::Method::POST, axum::http::Method::POST,
axum::http::Method::PUT, axum::http::Method::PUT,
axum::http::Method::DELETE, axum::http::Method::DELETE,
]) // Specify allowed methods:cite[2] ])
.allow_headers([ .allow_headers([
axum::http::header::CONTENT_TYPE, axum::http::header::CONTENT_TYPE,
axum::http::header::AUTHORIZATION, axum::http::header::AUTHORIZATION,
]) // Specify allowed headers:cite[2] ])
.allow_credentials(true) // If you need to send cookies or authentication headers:cite[2] .allow_credentials(true)
.max_age(std::time::Duration::from_secs(3600)); // Cache the preflight response for 1 hour:cite[2] .max_age(std::time::Duration::from_secs(3600));
// Dynamically set the allowed origin based on the environment // Dynamically set the allowed origin based on the environment
match std::env::var(sienvy::keys::APP_ENV).as_deref() { match std::env::var(sienvy::keys::APP_ENV).as_deref() {
@@ -116,6 +116,10 @@ mod init {
callers::endpoints::LOGIN, callers::endpoints::LOGIN,
post(callers::login::endpoint::login), post(callers::login::endpoint::login),
) )
.route(
callers::endpoints::UPDATE_PASSWORD,
patch(callers::login::endpoint::update_password),
)
.route( .route(
callers::endpoints::SERVICE_LOGIN, callers::endpoints::SERVICE_LOGIN,
post(callers::login::endpoint::service_login), post(callers::login::endpoint::service_login),
@@ -124,6 +128,10 @@ mod init {
callers::endpoints::REFRESH_TOKEN, callers::endpoints::REFRESH_TOKEN,
post(callers::login::endpoint::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) .layer(cors::configure_cors().await)
} }
@@ -247,6 +255,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 { pub mod requests {
use tower::ServiceExt; // for `call`, `oneshot`, and `ready` use tower::ServiceExt; // for `call`, `oneshot`, and `ready`
@@ -264,6 +293,53 @@ mod tests {
app.clone().oneshot(req).await 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
}
pub async fn get_user_profile(
app: &axum::Router,
user_id: &uuid::Uuid,
) -> Result<axum::response::Response, std::convert::Infallible> {
let raw_uri = String::from(crate::callers::endpoints::GET_USER_PROFILE);
let end_index = raw_uri.len() - 4;
let uri = format!("{}{user_id}", (&raw_uri[..end_index]).to_string());
let req = axum::http::Request::builder()
.method(axum::http::Method::GET)
.uri(uri)
.header(axum::http::header::CONTENT_TYPE, "application/json")
.body(axum::body::Body::empty())
.unwrap();
app.clone().oneshot(req).await
}
} }
#[tokio::test] #[tokio::test]
@@ -394,22 +470,11 @@ mod tests {
); );
assert!(returned_usr.date_created.is_some(), "Date Created is empty"); assert!(returned_usr.date_created.is_some(), "Date Created is empty");
let login_payload = json!({ let mut n_usr = callers::login::request::Request::default();
"username": &usr.username, n_usr.username = usr.username.clone();
"password": &usr.password, n_usr.password = usr.password.clone();
});
match app match requests::login(&app, &n_usr).await {
.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
{
Ok(resp) => { Ok(resp) => {
assert_eq!(StatusCode::OK, resp.status(), "Status is not right"); assert_eq!(StatusCode::OK, resp.status(), "Status is not right");
let body = axum::body::to_bytes(resp.into_body(), usize::MAX) let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
@@ -553,4 +618,177 @@ 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_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;
}
#[tokio::test]
async fn test_get_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: callers::register::response::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 mut n_usr = callers::login::request::Request::default();
n_usr.username = usr.username.clone();
n_usr.password = usr.password.clone();
match requests::get_user_profile(&app, &user_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::get_user_profile::GetUserProfileResponse =
serde_json::from_slice(&body).unwrap();
let user_profile = &parsed_body.data[0];
assert!(
!user_profile.username.is_empty(),
"Username should not be null is nil"
);
}
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;
}
} }
+128 -14
View File
@@ -24,26 +24,114 @@ pub mod user {
match result { match result {
Ok(r) => match r { Ok(r) => match r {
Some(r) => Ok(simodels::user::User { Some(r) => parse_row(&r).await,
id: r.try_get("id")?,
username: r.try_get("username")?,
password: r.try_get("password")?,
email: r.try_get("email")?,
email_verified: r.try_get("email_verified")?,
phone: r.try_get("phone")?,
salt_id: r.try_get("salt_id")?,
firstname: r.try_get("firstname")?,
lastname: r.try_get("lastname")?,
date_created: r.try_get("date_created")?,
last_login: r.try_get("last_login")?,
status: r.try_get("status")?,
}),
None => Err(sqlx::Error::RowNotFound), None => Err(sqlx::Error::RowNotFound),
}, },
Err(e) => Err(e), Err(e) => Err(e),
} }
} }
pub async fn get_with_id(
pool: &sqlx::PgPool,
id: &uuid::Uuid,
) -> Result<simodels::user::User, sqlx::Error> {
let result = sqlx::query(
r#"
SELECT * FROM "user" WHERE id = $1
"#,
)
.bind(id)
.fetch_optional(pool)
.await;
match result {
Ok(r) => match r {
Some(roww) => parse_row(&roww).await,
None => Err(sqlx::Error::RowNotFound),
},
Err(e) => Err(e),
}
}
async fn parse_row(row: &sqlx::postgres::PgRow) -> Result<simodels::user::User, sqlx::Error> {
Ok(simodels::user::User {
id: row
.try_get("id")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
username: row
.try_get("username")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
password: row
.try_get("password")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
email: row
.try_get("email")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
phone: row
.try_get("phone")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
firstname: row
.try_get("firstname")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
lastname: row
.try_get("lastname")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
email_verified: row
.try_get("email_verified")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
date_created: row
.try_get("date_created")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
status: row
.try_get("status")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
last_login: row
.try_get("last_login")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
salt_id: row
.try_get("salt_id")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
})
}
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( pub async fn update_last_login(
pool: &sqlx::PgPool, pool: &sqlx::PgPool,
user: &simodels::user::User, user: &simodels::user::User,
@@ -196,4 +284,30 @@ pub mod salt {
Err(sqlx::Error::RowNotFound) 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),
}
}
} }