From 8c38a2faf6b994f7cab3970e7b4150b20b149e22 Mon Sep 17 00:00:00 2001 From: philipp Date: Wed, 10 May 2023 08:57:20 +0200 Subject: [PATCH] add last_access column for user table --- migration.sql | 3 ++- src/model/user.rs | 20 +++++++++++++++++--- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/migration.sql b/migration.sql index aaa127a..654a8b6 100644 --- a/migration.sql +++ b/migration.sql @@ -5,7 +5,8 @@ CREATE TABLE IF NOT EXISTS "user" ( "is_cox" boolean NOT NULL DEFAULT FALSE, "is_admin" boolean NOT NULL DEFAULT FALSE, "is_guest" boolean NOT NULL DEFAULT TRUE, - "deleted" boolean NOT NULL DEFAULT FALSE + "deleted" boolean NOT NULL DEFAULT FALSE, + "last_access" DATETIME ); CREATE TABLE IF NOT EXISTS "trip_type" ( diff --git a/src/model/user.rs b/src/model/user.rs index f46ba6e..0e5f8c2 100644 --- a/src/model/user.rs +++ b/src/model/user.rs @@ -5,7 +5,7 @@ use rocket::{ async_trait, http::Status, request::{self, FromRequest, Outcome}, - Request, + Request, State, }; use serde::{Deserialize, Serialize}; use sqlx::{FromRow, SqlitePool}; @@ -149,6 +149,16 @@ ORDER BY name .to_string() } + pub async fn logged_in(&self, db: &SqlitePool) { + sqlx::query!( + "UPDATE user SET last_access = CURRENT_TIMESTAMP where id = ?", + self.id + ) + .execute(db) + .await + .unwrap(); //Okay, because we can only create a User of a valid id + } + pub async fn delete(&self, db: &SqlitePool) { sqlx::query!("UPDATE user SET deleted=1 WHERE id=?", self.id) .execute(db) @@ -163,8 +173,12 @@ impl<'r> FromRequest<'r> for User { async fn from_request(req: &'r Request<'_>) -> request::Outcome { match req.cookies().get_private("loggedin_user") { - Some(user) => match serde_json::from_str(user.value()) { - Ok(user) => Outcome::Success(user), + Some(user) => match serde_json::from_str::(user.value()) { + Ok(user) => { + let db = req.rocket().state::().unwrap(); + user.logged_in(db).await; + Outcome::Success(user) + } Err(_) => { Outcome::Failure((Status::Unauthorized, LoginError::DeserializationError)) }