Skip to content

Commit

Permalink
chore: refactor refresh token validation / family invalidation
Browse files Browse the repository at this point in the history
  • Loading branch information
pnwatin committed Apr 6, 2024
1 parent b7ca848 commit 82721e9
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 17 deletions.
36 changes: 20 additions & 16 deletions src/handlers/auth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,14 @@ mod sign_in;
mod sign_up;
mod tokens;

use anyhow::Context;
use axum::{routing::post, Router};
use chrono::{DateTime, Utc};
use jsonwebtoken::{decode, encode, Header, Validation};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use sqlx::PgPool;
use uuid::Uuid;

use crate::{error::AppError, settings::JWT_CONFIG};
use crate::settings::JWT_CONFIG;

pub fn auth_router() -> Router {
Router::new()
Expand Down Expand Up @@ -117,31 +116,36 @@ impl RefreshToken {
Ok(self)
}

pub async fn validate(self, pool: &PgPool) -> Result<Self, AppError> {
pub async fn validate(self, pool: &PgPool) -> Result<Option<Self>, sqlx::Error> {
let result = sqlx::query!(
r#"
SELECT * FROM refresh_tokens WHERE jit = $1;
"#,
self.claims().jit
)
.fetch_optional(pool)
.await
.context("Failed to fetch execute query")?;
.await?;

if result.is_none() {
sqlx::query!(
r#"
DELETE FROM refresh_tokens WHERE family = $1;
"#,
self.claims().family
)
.execute(pool)
.await?;

return Err(AppError::InvalidRefreshToken);
self.invalidate_family(pool).await?;

return Ok(None);
}

Ok(self)
Ok(Some(self))
}

pub async fn invalidate_family(&self, pool: &PgPool) -> Result<(), sqlx::Error> {
sqlx::query!(
r#"
DELETE FROM refresh_tokens WHERE family = $1;
"#,
self.claims().family
)
.execute(pool)
.await?;

Ok(())
}
}

Expand Down
5 changes: 4 additions & 1 deletion src/handlers/auth/tokens.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,12 @@ async fn refresh_tokens(refresh_token: &str, pool: &PgPool) -> Result<TokensPair

let user_id = refresh_token_claims.sub;
let family = refresh_token_claims.family;

RefreshToken::from(refresh_token_claims)
.validate(pool)
.await?;
.await
.context("Failed to execute query.")?
.ok_or(AppError::InvalidRefreshToken)?;

let refresh_token = RefreshToken::new(user_id, family).save(pool).await?;

Expand Down

0 comments on commit 82721e9

Please sign in to comment.