From cda067d57a49d65a1b3070d5b8bf8e395c16e87f Mon Sep 17 00:00:00 2001 From: antifallobst Date: Wed, 16 Aug 2023 20:24:12 +0200 Subject: [PATCH] feat(tokens): implemented token token expiration logic --- src/tokens/mod.rs | 72 +++++++++++++++++++++++++++++++++++------------ 1 file changed, 54 insertions(+), 18 deletions(-) diff --git a/src/tokens/mod.rs b/src/tokens/mod.rs index f574313..804fd65 100644 --- a/src/tokens/mod.rs +++ b/src/tokens/mod.rs @@ -46,17 +46,35 @@ impl AuthToken { Ok(token) } - pub async fn check(pool: &MySqlPool, token: String) -> Result> { - let query_result = sqlx::query!(r#"SELECT * FROM AuthTokens WHERE token = ?;"#, token) - .fetch_one(pool) - .await; + pub async fn check(pool: &MySqlPool, alphanumeric_token: String) -> Result> { + let query_result = sqlx::query!( + r#"SELECT * FROM AuthTokens WHERE token = ?;"#, + alphanumeric_token + ) + .fetch_one(pool) + .await; match query_result { - Ok(row) => Ok(Some(Self { - token: row.token, - account: row.account, - expire: row.expire, - })), + Ok(row) => { + let token = Self { + token: row.token, + account: row.account, + expire: row.expire, + }; + + if token.expire.timestamp() > chrono::Utc::now().timestamp() { + Ok(Some(token)) + } else { + // The token expired + sqlx::query!( + r#"DELETE FROM AuthTokens WHERE token = ?;"#, + alphanumeric_token + ) + .execute(pool) + .await?; + Ok(None) + } + } Err(sqlx::Error::RowNotFound) => Ok(None), Err(e) => Err(Error::new(e)), } @@ -108,17 +126,35 @@ impl VerificationToken { Ok(token) } - pub async fn check(pool: &MySqlPool, token: String) -> Result> { - let query_result = sqlx::query!(r#"SELECT * FROM VerificationTokens WHERE token = ?;"#, token) - .fetch_one(pool) - .await; + pub async fn check(pool: &MySqlPool, alphanumeric_token: String) -> Result> { + let query_result = sqlx::query!( + r#"SELECT * FROM VerificationTokens WHERE token = ?;"#, + alphanumeric_token + ) + .fetch_one(pool) + .await; match query_result { - Ok(row) => Ok(Some(Self { - token: row.token, - account: row.account, - expire: row.expire, - })), + Ok(row) => { + let token = Self { + token: row.token, + account: row.account, + expire: row.expire, + }; + + if token.expire.timestamp() > chrono::Utc::now().timestamp() { + Ok(Some(token)) + } else { + // The token expired + sqlx::query!( + r#"DELETE FROM VerificationTokens WHERE token = ?;"#, + alphanumeric_token + ) + .execute(pool) + .await?; + Ok(None) + } + } Err(sqlx::Error::RowNotFound) => Ok(None), Err(e) => Err(Error::new(e)), }