From 501520a9df138abe2d207c00adb3bb66a7de2e45 Mon Sep 17 00:00:00 2001 From: Pierre HUBERT Date: Thu, 30 Jan 2025 21:53:51 +0100 Subject: [PATCH] Can update client last usage --- src/extractors/client_auth.rs | 14 +++++++++++++- src/user.rs | 11 ++++++++++- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/src/extractors/client_auth.rs b/src/extractors/client_auth.rs index fcaa58c..e71f57d 100644 --- a/src/extractors/client_auth.rs +++ b/src/extractors/client_auth.rs @@ -1,4 +1,5 @@ use crate::user::{APIClient, APIClientID, UserConfig, UserID}; +use crate::utils::curr_time; use actix_web::dev::Payload; use actix_web::{FromRequest, HttpRequest}; use jwt_simple::common::VerificationOptions; @@ -114,9 +115,20 @@ impl APIClientAuth { } // TODO : handle payload - // TODO : update last use (if required) // TODO : check for IP restriction + // Update last use (if needed) + if client.need_update_last_used() { + let mut user_up = user.clone(); + match user_up.find_client_by_id_mut(&client.id) { + None => log::error!("Client ID disappeared!!!"), + Some(u) => u.used = curr_time().unwrap(), + } + if let Err(e) = user_up.save().await { + log::error!("Failed to update last token usage! {e}"); + } + } + Ok(Self { client: client.clone(), payload: None, diff --git a/src/user.rs b/src/user.rs index 5766b43..c995753 100644 --- a/src/user.rs +++ b/src/user.rs @@ -80,6 +80,10 @@ impl APIClient { pub fn fmt_used(&self) -> String { format_time(self.used).unwrap_or_default() } + + pub fn need_update_last_used(&self) -> bool { + self.used + 60 * 15 < curr_time().unwrap() + } } impl APIClient { @@ -97,7 +101,7 @@ impl APIClient { } } -#[derive(serde::Serialize, serde::Deserialize)] +#[derive(serde::Serialize, serde::Deserialize, Clone)] pub struct UserConfig { /// Target user ID pub user_id: UserID, @@ -211,4 +215,9 @@ impl UserConfig { pub fn find_client_by_id(&self, id: &APIClientID) -> Option<&APIClient> { self.clients.iter().find(|c| &c.id == id) } + + /// Find a client by its id and get a mutable reference + pub fn find_client_by_id_mut(&mut self, id: &APIClientID) -> Option<&mut APIClient> { + self.clients.iter_mut().find(|c| &c.id == id) + } }