From 50e735e1a9eb46ed888a4c863864ac442d03de1f Mon Sep 17 00:00:00 2001 From: phoenix Date: Fri, 11 Apr 2025 01:01:18 +0000 Subject: [PATCH] Update last_login of user (#26) Reviewed-on: https://git.kundeng.us/phoenix/icarus_auth/pulls/26 Co-authored-by: phoenix Co-committed-by: phoenix --- src/callers/login.rs | 5 ++++- src/repo/mod.rs | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/src/callers/login.rs b/src/callers/login.rs index 6f2908e..83347e1 100644 --- a/src/callers/login.rs +++ b/src/callers/login.rs @@ -51,13 +51,16 @@ pub mod endpoint { let (token_literal, duration) = token_stuff::create_token(&key).unwrap(); if token_stuff::verify_token(&key, &token_literal) { + let current_time = time::OffsetDateTime::now_utc(); + let _ = repo::user::update_last_login(&pool, &user, ¤t_time).await; + ( StatusCode::OK, Json(response::Response { message: String::from("Successful"), data: vec![icarus_models::login_result::LoginResult { id: user.id, - username: user.username, + username: user.username.clone(), token: token_literal, token_type: String::from(token_stuff::TOKENTYPE), expiration: duration, diff --git a/src/repo/mod.rs b/src/repo/mod.rs index b8a8c8c..a58bab5 100644 --- a/src/repo/mod.rs +++ b/src/repo/mod.rs @@ -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 { + 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 { let result = sqlx::query( r#"