From 95786070c414625408c94b492a6bb5ce0c3d27ec Mon Sep 17 00:00:00 2001 From: Frederic Henrichs Date: Tue, 10 Dec 2024 10:23:27 +0100 Subject: [PATCH] backend/login: make calculation of token expiration more robust by using the chrono features for it instead of calculating it by hand. --- backend/src/routes/auth/jwt_refresh.rs | 8 ++++++-- backend/src/routes/auth/login.rs | 14 +++++++++++--- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/backend/src/routes/auth/jwt_refresh.rs b/backend/src/routes/auth/jwt_refresh.rs index 3e76850..d0cf3ec 100644 --- a/backend/src/routes/auth/jwt_refresh.rs +++ b/backend/src/routes/auth/jwt_refresh.rs @@ -3,7 +3,7 @@ use std::str::FromStr; use actix_web::{ cookie::Cookie, error::ErrorUnauthorized, get, web, HttpRequest, HttpResponse, Responder, }; -use chrono::{Duration, Utc}; +use chrono::{TimeDelta, Utc}; use db_connector::models::{refresh_tokens::RefreshToken, users::User}; use diesel::{prelude::*, result::Error::NotFound}; use jsonwebtoken::{decode, DecodingKey, Validation}; @@ -139,7 +139,11 @@ pub async fn jwt_refresh( let now = Utc::now(); let iat = now.timestamp() as usize; - let exp = (now + Duration::minutes(super::login::MAX_TOKEN_AGE_MINUTES)).timestamp() as usize; + let exp = if let Some(exp) = now.checked_add_signed(TimeDelta::minutes(super::login::MAX_TOKEN_AGE_MINUTES)) { + exp.timestamp() as usize + } else { + return Err(Error::InternalError.into()) + }; let claims = TokenClaims { iat, exp, diff --git a/backend/src/routes/auth/login.rs b/backend/src/routes/auth/login.rs index 381db17..000c693 100644 --- a/backend/src/routes/auth/login.rs +++ b/backend/src/routes/auth/login.rs @@ -20,7 +20,7 @@ use actix_web::{cookie::Cookie, post, web, HttpResponse, Responder}; use actix_web_validator::Json; use argon2::{Argon2, PasswordHash, PasswordVerifier}; -use chrono::{Duration, Utc}; +use chrono::{Days, TimeDelta, Utc}; use db_connector::models::{refresh_tokens::RefreshToken, users::User}; use diesel::{ prelude::*, @@ -122,7 +122,11 @@ pub async fn login( let now = Utc::now(); let iat = now.timestamp() as usize; - let exp = (now + Duration::minutes(MAX_TOKEN_AGE_MINUTES)).timestamp() as usize; + let exp = if let Some(exp) = now.checked_add_signed(TimeDelta::minutes(super::login::MAX_TOKEN_AGE_MINUTES)) { + exp.timestamp() as usize + } else { + return Err(Error::InternalError.into()) + }; let claims = TokenClaims { iat, exp, @@ -166,7 +170,11 @@ pub async fn create_refresh_token( let now = Utc::now(); let iat = now.timestamp() as usize; - let exp = (now + Duration::days(MAX_REFRESH_TOKEN_AGE_DAYS)).timestamp() as usize; + let exp = if let Some(exp) = now.checked_add_days(Days::new(MAX_REFRESH_TOKEN_AGE_DAYS as u64)) { + exp.timestamp() as usize + } else { + return Err(Error::InternalError.into()) + }; let claims = TokenClaims { iat, exp,