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)
}
pub async fn check(pool: &MySqlPool, token: String) -> Result<Option<Self>> {
let query_result = sqlx::query!(r#"SELECT * FROM AuthTokens WHERE token = ?;"#, token)
pub async fn check(pool: &MySqlPool, alphanumeric_token: String) -> Result<Option<Self>> {
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 {
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<Option<Self>> {
let query_result = sqlx::query!(r#"SELECT * FROM VerificationTokens WHERE token = ?;"#, token)
pub async fn check(pool: &MySqlPool, alphanumeric_token: String) -> Result<Option<Self>> {
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 {
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)),
}