From d7333373bb161d70bc425271d8058c6a7e9b7bfe Mon Sep 17 00:00:00 2001 From: Jef Roosens Date: Sun, 22 Aug 2021 13:14:19 +0200 Subject: [PATCH] Token refresh works! --- src/rb/auth.rs | 17 +++++++++++------ src/rb/lib.rs | 2 +- src/rbs/auth.rs | 3 ++- 3 files changed, 14 insertions(+), 8 deletions(-) diff --git a/src/rb/auth.rs b/src/rb/auth.rs index 36f5bb9..6bc03c3 100644 --- a/src/rb/auth.rs +++ b/src/rb/auth.rs @@ -126,9 +126,10 @@ pub fn refresh_token(conn: &PgConnection, refresh_token: &str) -> crate::Result< let token_bytes = base64::decode(refresh_token).map_err(|_| RBError::InvalidRefreshToken)?; // First, we request the token from the database to see if it's really a valid token - let token_entry = refresh_tokens::refresh_tokens + let (token_entry, user) = refresh_tokens::refresh_tokens + .inner_join(users::users) .filter(refresh_tokens::token.eq(token_bytes)) - .first::(conn) + .first::<(RefreshToken, User)>(conn) .map_err(|_| RBError::InvalidRefreshToken)?; // If we see that the token has already been used before, we block the user. @@ -142,15 +143,19 @@ pub fn refresh_token(conn: &PgConnection, refresh_token: &str) -> crate::Result< return Err(RBError::DuplicateRefreshToken); } + // Now we check if the token has already expired + let cur_time = Utc::now().naive_utc(); + + if token_entry.expires_at < cur_time { + return Err(RBError::TokenExpired); + } + // We update the last_used_at value for the refresh token let target = refresh_tokens::refresh_tokens.filter(refresh_tokens::token.eq(token_entry.token)); diesel::update(target) - .set(refresh_tokens::last_used_at.eq(Utc::now().naive_utc())) + .set(refresh_tokens::last_used_at.eq(cur_time)) .execute(conn) .map_err(|_| RBError::DBError)?; - // Finally, we query the new user & generate a new token - let user = users::users.filter(users::id.eq(token_entry.user_id)).first::(conn).map_err(|_| RBError::DBError)?; - generate_jwt_token(conn, &user) } diff --git a/src/rb/lib.rs b/src/rb/lib.rs index e3ca322..457665d 100644 --- a/src/rb/lib.rs +++ b/src/rb/lib.rs @@ -10,7 +10,7 @@ pub use errors::Result; // Any import defaults are defined here /// Expire time for the JWT tokens in seconds. -const JWT_EXP_SECONDS: i64 = 900; +const JWT_EXP_SECONDS: i64 = 600; /// Amount of bytes the refresh tokens should consist of const REFRESH_TOKEN_N_BYTES: usize = 64; /// Expire time for refresh tokens; here: one week diff --git a/src/rbs/auth.rs b/src/rbs/auth.rs index f9ffe55..119d973 100644 --- a/src/rbs/auth.rs +++ b/src/rbs/auth.rs @@ -32,6 +32,7 @@ async fn login(conn: RbDbConn, credentials: Json) -> rb::Result