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)), }