feat(tokens): implemented token expiration logic

This commit is contained in:
antifallobst 2023-08-16 20:24:12 +02:00
parent e3ea93f4ae
commit 2f2aa0e4a3
Signed by: antifallobst
GPG Key ID: 2B4F402172791BAF
1 changed files with 54 additions and 18 deletions

View File

@ -46,17 +46,35 @@ impl AuthToken {
Ok(token) Ok(token)
} }
pub async fn check(pool: &MySqlPool, token: String) -> Result<Option<Self>> { pub async fn check(pool: &MySqlPool, alphanumeric_token: String) -> Result<Option<Self>> {
let query_result = sqlx::query!(r#"SELECT * FROM AuthTokens WHERE token = ?;"#, token) let query_result = sqlx::query!(
.fetch_one(pool) r#"SELECT * FROM AuthTokens WHERE token = ?;"#,
.await; alphanumeric_token
)
.fetch_one(pool)
.await;
match query_result { match query_result {
Ok(row) => Ok(Some(Self { Ok(row) => {
token: row.token, let token = Self {
account: row.account, token: row.token,
expire: row.expire, 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(sqlx::Error::RowNotFound) => Ok(None),
Err(e) => Err(Error::new(e)), Err(e) => Err(Error::new(e)),
} }
@ -108,17 +126,35 @@ impl VerificationToken {
Ok(token) Ok(token)
} }
pub async fn check(pool: &MySqlPool, token: String) -> Result<Option<Self>> { pub async fn check(pool: &MySqlPool, alphanumeric_token: String) -> Result<Option<Self>> {
let query_result = sqlx::query!(r#"SELECT * FROM VerificationTokens WHERE token = ?;"#, token) let query_result = sqlx::query!(
.fetch_one(pool) r#"SELECT * FROM VerificationTokens WHERE token = ?;"#,
.await; alphanumeric_token
)
.fetch_one(pool)
.await;
match query_result { match query_result {
Ok(row) => Ok(Some(Self { Ok(row) => {
token: row.token, let token = Self {
account: row.account, token: row.token,
expire: row.expire, 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(sqlx::Error::RowNotFound) => Ok(None),
Err(e) => Err(Error::new(e)), Err(e) => Err(Error::new(e)),
} }