Compare commits

...

8 Commits

Author SHA1 Message Date
50e735e1a9 Update last_login of user (#26)
All checks were successful
Release Tagging / release (push) Successful in 55s
Rust Build / Check (pull_request) Successful in 58s
Rust Build / Test Suite (pull_request) Successful in 1m3s
Rust Build / Rustfmt (pull_request) Successful in 33s
Rust Build / Clippy (pull_request) Successful in 50s
Rust Build / build (pull_request) Successful in 1m18s
Rust Build / Check (push) Successful in 44s
Rust Build / Test Suite (push) Successful in 57s
Rust Build / Rustfmt (push) Successful in 31s
Rust Build / Clippy (push) Successful in 46s
Rust Build / build (push) Successful in 1m11s
Reviewed-on: #26
Co-authored-by: phoenix <kundeng00@pm.me>
Co-committed-by: phoenix <kundeng00@pm.me>
2025-04-11 01:01:18 +00:00
f6cf968f86 main merge (#25)
All checks were successful
Release Tagging / release (push) Successful in 35s
Rust Build / Check (push) Successful in 49s
Rust Build / Test Suite (push) Successful in 1m8s
Rust Build / Rustfmt (push) Successful in 29s
Rust Build / Clippy (push) Successful in 1m0s
Rust Build / build (push) Successful in 1m24s
Rust Build / Check (pull_request) Successful in 48s
Rust Build / Test Suite (pull_request) Successful in 1m5s
Rust Build / Rustfmt (pull_request) Successful in 29s
Rust Build / Clippy (pull_request) Successful in 50s
Rust Build / build (pull_request) Successful in 1m19s
Reviewed-on: #25
2025-04-10 22:46:29 +00:00
70a547ca94 Next release (#23)
All checks were successful
Rust Build / Check (push) Successful in 45s
Rust Build / Test Suite (push) Successful in 1m12s
Rust Build / Rustfmt (push) Successful in 27s
Rust Build / Clippy (push) Successful in 1m1s
Rust Build / build (push) Successful in 1m38s
Release Tagging / release (push) Successful in 40s
Rust Build / Check (pull_request) Successful in 55s
Rust Build / Clippy (pull_request) Successful in 1m10s
Rust Build / build (pull_request) Successful in 1m38s
Rust Build / Test Suite (pull_request) Successful in 1m12s
Rust Build / Rustfmt (pull_request) Successful in 38s
Reviewed-on: #23
2025-04-08 23:42:04 +00:00
89c89a5524 Login endpoint bug fix (#24)
All checks were successful
Release Tagging / release (push) Successful in 46s
Rust Build / Check (push) Successful in 57s
Rust Build / Test Suite (push) Successful in 1m0s
Rust Build / Rustfmt (push) Successful in 35s
Rust Build / Clippy (push) Successful in 50s
Rust Build / build (push) Successful in 1m20s
Rust Build / Check (pull_request) Successful in 50s
Rust Build / Test Suite (pull_request) Successful in 1m7s
Rust Build / Rustfmt (pull_request) Successful in 29s
Rust Build / Clippy (pull_request) Successful in 1m7s
Rust Build / build (pull_request) Successful in 1m31s
Reviewed-on: #24
Co-authored-by: phoenix <kundeng00@pm.me>
Co-committed-by: phoenix <kundeng00@pm.me>
2025-04-07 20:15:58 +00:00
a58b0cb40b Changes to token (#21)
All checks were successful
Release Tagging / release (push) Successful in 31s
Rust Build / Check (push) Successful in 43s
Rust Build / Clippy (push) Successful in 48s
Rust Build / build (push) Successful in 1m17s
Rust Build / Test Suite (push) Successful in 1m0s
Rust Build / Rustfmt (push) Successful in 27s
Rust Build / Check (pull_request) Successful in 42s
Rust Build / Test Suite (pull_request) Successful in 57s
Rust Build / Rustfmt (pull_request) Successful in 28s
Rust Build / Clippy (pull_request) Successful in 44s
Rust Build / build (pull_request) Successful in 1m11s
Reviewed-on: #21
Co-authored-by: phoenix <kundeng00@pm.me>
Co-committed-by: phoenix <kundeng00@pm.me>
2025-04-07 17:35:47 +00:00
f601442f0e Release with login functionality (#19)
All checks were successful
Rust Build / Check (push) Successful in 46s
Rust Build / Test Suite (push) Successful in 55s
Rust Build / Rustfmt (push) Successful in 28s
Rust Build / Clippy (push) Successful in 46s
Rust Build / build (push) Successful in 1m10s
Release Tagging / release (push) Successful in 35s
Reviewed-on: #19
2025-04-07 02:04:46 +00:00
2229d98ab6 Next release (#15)
All checks were successful
Rust Build / Check (push) Successful in 45s
Rust Build / Test Suite (push) Successful in 52s
Rust Build / Rustfmt (push) Successful in 34s
Rust Build / Clippy (push) Successful in 47s
Rust Build / build (push) Successful in 1m11s
Release Tagging / release (push) Successful in 39s
Reviewed-on: #15
2025-04-05 19:41:15 +00:00
88f45645b3 devel (#5)
All checks were successful
Rust Build / Check (push) Successful in 34s
Rust Build / Test Suite (push) Successful in 32s
Rust Build / Rustfmt (push) Successful in 26s
Rust Build / Clippy (push) Successful in 35s
Rust Build / build (push) Successful in 37s
Reviewed-on: #5
2025-03-30 18:07:12 +00:00
7 changed files with 132 additions and 79 deletions

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "icarus_auth" name = "icarus_auth"
version = "0.3.0" version = "0.3.2"
edition = "2024" edition = "2024"
rust-version = "1.86" rust-version = "1.86"

View File

@@ -1,30 +1,37 @@
use axum::{Extension, Json, http::StatusCode}; pub mod response {
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize)] #[derive(Deserialize, Serialize)]
pub struct TestResult { pub struct TestResult {
message: String, pub message: String,
} }
}
pub mod endpoint {
use super::*;
use axum::{Extension, Json, http::StatusCode};
// basic handler that responds with a static string // basic handler that responds with a static string
pub async fn root() -> &'static str { pub async fn root() -> &'static str {
"Hello, World!" "Hello, World!"
} }
pub async fn db_ping(Extension(pool): Extension<sqlx::PgPool>) -> (StatusCode, Json<TestResult>) { pub async fn db_ping(
Extension(pool): Extension<sqlx::PgPool>,
) -> (StatusCode, Json<response::TestResult>) {
match sqlx::query("SELECT 1").execute(&pool).await { match sqlx::query("SELECT 1").execute(&pool).await {
Ok(_) => { Ok(_) => {
let tr = TestResult { let tr = response::TestResult {
message: String::from("This works"), message: String::from("This works"),
}; };
(StatusCode::OK, Json(tr)) (StatusCode::OK, Json(tr))
} }
Err(e) => ( Err(e) => (
StatusCode::BAD_REQUEST, StatusCode::BAD_REQUEST,
Json(TestResult { Json(response::TestResult {
message: e.to_string(), message: e.to_string(),
}), }),
), ),
} }
} }
}

View File

@@ -42,44 +42,25 @@ pub mod endpoint {
axum::Extension(pool): axum::Extension<sqlx::PgPool>, axum::Extension(pool): axum::Extension<sqlx::PgPool>,
Json(payload): Json<request::Request>, Json(payload): Json<request::Request>,
) -> (StatusCode, Json<response::Response>) { ) -> (StatusCode, Json<response::Response>) {
let usr = icarus_models::user::User {
username: payload.username,
password: payload.password,
..Default::default()
};
// Check if user exists // Check if user exists
match repo::user::exists(&pool, &usr.username).await { match repo::user::get(&pool, &payload.username).await {
Ok(exists) => { Ok(user) => {
if !exists { if hashing::verify_password(&payload.password, user.password.clone()).unwrap() {
return not_found("Not Found").await;
}
}
Err(err) => {
return not_found(&err.to_string()).await;
}
};
let user = repo::user::get(&pool, &usr.username).await.unwrap();
let salt = repo::salt::get(&pool, &user.salt_id).await.unwrap();
let salt_str = hashing::get_salt(&salt.salt).unwrap();
// Check if password is correct
match hashing::hash_password(&usr.password, &salt_str) {
Ok(hash_password) => {
if hashing::verify_password(&usr.password, hash_password.clone()).unwrap() {
// Create token // Create token
let key = token_stuff::get_key().unwrap(); let key = token_stuff::get_key().unwrap();
let (token_literal, duration) = token_stuff::create_token(&key).unwrap(); let (token_literal, duration) = token_stuff::create_token(&key).unwrap();
if token_stuff::verify_token(&key, &token_literal) { if token_stuff::verify_token(&key, &token_literal) {
let current_time = time::OffsetDateTime::now_utc();
let _ = repo::user::update_last_login(&pool, &user, &current_time).await;
( (
StatusCode::OK, StatusCode::OK,
Json(response::Response { Json(response::Response {
message: String::from("Successful"), message: String::from("Successful"),
data: vec![icarus_models::login_result::LoginResult { data: vec![icarus_models::login_result::LoginResult {
id: user.id, id: user.id,
username: user.username, username: user.username.clone(),
token: token_literal, token: token_literal,
token_type: String::from(token_stuff::TOKENTYPE), token_type: String::from(token_stuff::TOKENTYPE),
expiration: duration, expiration: duration,

View File

@@ -11,8 +11,7 @@ use argon2::{
pub fn generate_salt() -> Result<SaltString, argon2::Error> { pub fn generate_salt() -> Result<SaltString, argon2::Error> {
// Generate a random salt // Generate a random salt
// SaltString::generate uses OsRng internally for cryptographic security // SaltString::generate uses OsRng internally for cryptographic security
let salt = SaltString::generate(&mut OsRng); Ok(SaltString::generate(&mut OsRng))
Ok(salt)
} }
pub fn get_salt(s: &str) -> Result<SaltString, argon2::password_hash::Error> { pub fn get_salt(s: &str) -> Result<SaltString, argon2::password_hash::Error> {
@@ -32,9 +31,7 @@ pub fn hash_password(
// Hash the password with the salt // Hash the password with the salt
// The output is a PasswordHash string format that includes algorithm, version, // The output is a PasswordHash string format that includes algorithm, version,
// parameters, salt, and the hash itself. // parameters, salt, and the hash itself.
let password_hash = argon2.hash_password(password_bytes, salt)?.to_string(); Ok(argon2.hash_password(password_bytes, salt)?.to_string())
Ok(password_hash)
} }
pub fn verify_password( pub fn verify_password(
@@ -48,11 +45,9 @@ pub fn verify_password(
let parsed_hash = argon2::PasswordHash::new(stored_hash.as_str())?; let parsed_hash = argon2::PasswordHash::new(stored_hash.as_str())?;
// Create an Argon2 instance (it will use the parameters from the parsed hash) // Create an Argon2 instance (it will use the parameters from the parsed hash)
let argon2 = Argon2::default();
// Verify the password against the parsed hash // Verify the password against the parsed hash
// 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.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::Password) => 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)
@@ -66,8 +61,7 @@ mod tests {
#[test] #[test]
fn test_hash_password() { fn test_hash_password() {
let some_password = String::from("somethingrandom"); let some_password = String::from("somethingrandom");
let salt = generate_salt().unwrap(); match hash_password(&some_password, &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);
@@ -81,4 +75,27 @@ mod tests {
} }
} }
} }
#[test]
fn test_wrong_password() {
let some_password = String::from("somethingrandom");
match hash_password(&some_password, &generate_salt().unwrap()) {
Ok(p) => {
match verify_password(&some_password, p.clone()) {
Ok(res) => {
assert_eq!(res, true, "Passwords are not verified");
}
Err(err) => {
assert!(false, "Error: {:?}", err.to_string());
}
}
let wrong_password = String::from("Differentanotherlevel");
let result = verify_password(&wrong_password, p.clone()).unwrap();
assert_eq!(false, result, "Passwords should not match");
}
Err(err) => {
assert!(false, "Error: {:?}", err.to_string());
}
}
}
} }

View File

@@ -25,8 +25,14 @@ mod init {
pub async fn routes() -> Router { pub async fn routes() -> Router {
// build our application with a route // build our application with a route
Router::new() Router::new()
.route(callers::endpoints::DBTEST, get(callers::common::db_ping)) .route(
.route(callers::endpoints::ROOT, get(callers::common::root)) callers::endpoints::DBTEST,
get(callers::common::endpoint::db_ping),
)
.route(
callers::endpoints::ROOT,
get(callers::common::endpoint::root),
)
.route( .route(
callers::endpoints::REGISTER, callers::endpoints::REGISTER,
post(callers::register::register_user), post(callers::register::register_user),

View File

@@ -42,6 +42,39 @@ pub mod user {
} }
} }
pub async fn update_last_login(
pool: &sqlx::PgPool,
user: &icarus_models::user::User,
time: &time::OffsetDateTime,
) -> Result<time::OffsetDateTime, sqlx::Error> {
let result = sqlx::query(
r#"
UPDATE "user" SET last_login = $1 WHERE id = $2 RETURNING last_login
"#,
)
.bind(time)
.bind(user.id)
.fetch_optional(pool)
.await
.map_err(|e| {
eprintln!("Error updating time: {}", e);
e
});
match result {
Ok(row) => match row {
Some(r) => {
let last_login: time::OffsetDateTime = r
.try_get("last_login")
.map_err(|_e| sqlx::Error::RowNotFound)?;
Ok(last_login)
}
None => Err(sqlx::Error::RowNotFound),
},
Err(err) => Err(err),
}
}
pub async fn exists(pool: &sqlx::PgPool, username: &String) -> Result<bool, sqlx::Error> { pub async fn exists(pool: &sqlx::PgPool, username: &String) -> Result<bool, sqlx::Error> {
let result = sqlx::query( let result = sqlx::query(
r#" r#"

View File

@@ -18,11 +18,22 @@ pub fn get_key() -> Result<String, dotenvy::Error> {
Ok(key) Ok(key)
} }
pub fn get_expiration() -> time::Result<time::Duration> { pub fn get_issued() -> time::Result<time::OffsetDateTime> {
let now = time::OffsetDateTime::now_utc(); Ok(time::OffsetDateTime::now_utc())
let epoch = time::OffsetDateTime::UNIX_EPOCH; }
let since_the_epoch = now - epoch;
Ok(since_the_epoch) pub fn get_expiration(issued: &time::OffsetDateTime) -> Result<time::OffsetDateTime, time::Error> {
let duration_expire = time::Duration::hours(4);
Ok(*issued + duration_expire)
}
mod util {
pub fn time_to_std_time(
provided_time: &time::OffsetDateTime,
) -> Result<std::time::SystemTime, std::time::SystemTimeError> {
let converted = std::time::SystemTime::from(*provided_time);
Ok(converted)
}
} }
pub fn create_token(provided_key: &String) -> Result<(String, i64), josekit::JoseError> { pub fn create_token(provided_key: &String) -> Result<(String, i64), josekit::JoseError> {
@@ -33,13 +44,11 @@ pub fn create_token(provided_key: &String) -> Result<(String, i64), josekit::Jos
payload.set_subject(MESSAGE); payload.set_subject(MESSAGE);
payload.set_issuer(ISSUER); payload.set_issuer(ISSUER);
payload.set_audience(vec![AUDIENCE]); payload.set_audience(vec![AUDIENCE]);
match get_expiration() { match get_issued() {
Ok(duration) => { Ok(issued) => {
let expire = duration.whole_seconds(); let expire = get_expiration(&issued).unwrap();
let _ = payload.set_claim( payload.set_issued_at(&util::time_to_std_time(&issued).unwrap());
"expiration", payload.set_expires_at(&util::time_to_std_time(&expire).unwrap());
Some(serde_json::to_value(expire.to_string()).unwrap()),
);
let key: String = if provided_key.is_empty() { let key: String = if provided_key.is_empty() {
get_key().unwrap() get_key().unwrap()
@@ -50,7 +59,7 @@ pub fn create_token(provided_key: &String) -> Result<(String, i64), josekit::Jos
let signer = Hs256.signer_from_bytes(key.as_bytes()).unwrap(); let signer = Hs256.signer_from_bytes(key.as_bytes()).unwrap();
Ok(( Ok((
josekit::jwt::encode_with_signer(&payload, &header, &signer).unwrap(), josekit::jwt::encode_with_signer(&payload, &header, &signer).unwrap(),
duration.whole_seconds(), (expire - time::OffsetDateTime::UNIX_EPOCH).whole_seconds(),
)) ))
} }
Err(e) => Err(josekit::JoseError::InvalidClaim(e.into())), Err(e) => Err(josekit::JoseError::InvalidClaim(e.into())),