diff --git a/src/main.rs b/src/main.rs index 489ff55..3a6926a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,7 +5,7 @@ mod persistence; use std::{collections::HashMap, sync::Arc}; -use chrono::{DateTime, Utc}; +use chrono::{DateTime, Utc, Duration}; use clap::Parser; use axum::{Router, routing::{get, post}, response::IntoResponse, Json, http::StatusCode}; use sea_orm::{DatabaseConnection, Database}; @@ -18,7 +18,7 @@ use tracing::{info, metadata::LevelFilter}; use crate::{routes::{ auth::{authenticate, validate, refresh}, session::{join, has_joined_wrapper, profile}, register::register_unmigrated, -}, persistence::load_secret}; +}, persistence::{load_secret, purge_expired_tokens}}; /// Reimplementation of legacy auth server for minecraft #[derive(Parser, Debug, Clone)] @@ -76,6 +76,8 @@ async fn main() -> Result<(), Box> { let db = Database::connect(cfg.database.clone()).await?; + purge_expired_tokens(&db, Duration::seconds(cfg.token_lifetime.into())).await?; + let secret = load_secret(&db).await?; let store = Arc::new(Mutex::new(HashMap::new())); // TODO do this as an Actor diff --git a/src/persistence.rs b/src/persistence.rs index 603e8a2..4d36cbe 100644 --- a/src/persistence.rs +++ b/src/persistence.rs @@ -1,8 +1,8 @@ -use chrono::Utc; +use chrono::{Utc, Duration}; use hmac::{Hmac, Mac}; use jwt::SignWithKey; use rand::{rngs::OsRng, Rng, distributions::Alphanumeric}; -use sea_orm::{EntityTrait, DatabaseConnection, ActiveValue::NotSet, Set, DbErr}; +use sea_orm::{EntityTrait, DatabaseConnection, ActiveValue::NotSet, Set, DbErr, QueryFilter, DeleteResult, ColumnTrait}; use sha2::Sha384; use tracing::info; use std::collections::BTreeMap; @@ -22,6 +22,14 @@ pub fn new_auth_token(secret: &[u8], fields: Vec<(&str, &str)>) -> Result Result { + let res = entities::token::Entity::delete_many().filter( + entities::token::Column::CreatedAt.lt(Utc::now() - lifetime) + ).exec(db).await?; + + Ok(res.rows_affected) +} + pub async fn load_secret(db: &DatabaseConnection) -> Result { let secret;