automatically remove expired auth sessions

This commit is contained in:
2025-07-23 14:13:16 +02:00
parent 7f8726c225
commit bb79ea56f8
2 changed files with 46 additions and 3 deletions

View File

@@ -1,3 +1,5 @@
use std::time::Duration;
use anyhow::{Context as _, anyhow}; use anyhow::{Context as _, anyhow};
use argon2::{ use argon2::{
Argon2, PasswordHash, PasswordVerifier as _, Argon2, PasswordHash, PasswordVerifier as _,
@@ -7,7 +9,8 @@ use argon2::{
}, },
}; };
use chrono::Utc; use chrono::Utc;
use sqlx::{Acquire as _, PgConnection}; use sqlx::{Acquire as _, PgConnection, PgPool};
use tokio::task::JoinHandle;
use uuid::Uuid; use uuid::Uuid;
use crate::domain::warren::{ use crate::domain::warren::{
@@ -340,6 +343,44 @@ impl AuthRepository for Postgres {
} }
impl Postgres { impl Postgres {
pub(super) fn start_session_cleanup_task(pool: PgPool, interval: Duration) -> JoinHandle<()> {
tokio::spawn(async move {
loop {
{
let Ok(mut connection) = pool.acquire().await else {
break;
};
if let Ok(count) = Self::delete_expired_auth_sessions(&mut connection).await {
tracing::debug!("Removed {count} expired auth session(s)");
}
}
tokio::time::sleep(interval).await;
}
tracing::debug!("Session cleanup task stopped");
})
}
async fn delete_expired_auth_sessions(
connection: &mut PgConnection,
) -> Result<u64, sqlx::Error> {
let delete_count = sqlx::query(
"
DELETE FROM
auth_sessions
WHERE
expires_at <= CURRENT_TIMESTAMP
",
)
.execute(connection)
.await?
.rows_affected();
Ok(delete_count)
}
async fn create_user( async fn create_user(
&self, &self,
connection: &mut PgConnection, connection: &mut PgConnection,

View File

@@ -1,11 +1,10 @@
use std::str::FromStr as _; use std::{str::FromStr as _, time::Duration};
use anyhow::Context as _; use anyhow::Context as _;
use sqlx::{ use sqlx::{
ConnectOptions as _, Connection as _, PgConnection, PgPool, ConnectOptions as _, Connection as _, PgConnection, PgPool,
postgres::{PgConnectOptions, PgPoolOptions}, postgres::{PgConnectOptions, PgPoolOptions},
}; };
pub mod auth; pub mod auth;
pub mod warrens; pub mod warrens;
@@ -58,6 +57,9 @@ impl Postgres {
.await?; .await?;
sqlx::migrate!("./migrations").run(&pool).await?; sqlx::migrate!("./migrations").run(&pool).await?;
// 3600 seconds = 1 hour
Self::start_session_cleanup_task(pool.clone(), Duration::from_secs(3600));
Ok(Self { pool }) Ok(Self { pool })
} }
} }