Skip to content

Commit

Permalink
backend/login: make calculation of token expiration more robust by us…
Browse files Browse the repository at this point in the history
…ing the chrono features for it instead of calculating it by hand.
  • Loading branch information
ffreddow committed Dec 10, 2024
1 parent c8786a6 commit 9578607
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
8 changes: 6 additions & 2 deletions backend/src/routes/auth/jwt_refresh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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,
Expand Down
14 changes: 11 additions & 3 deletions backend/src/routes/auth/login.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::*,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down

0 comments on commit 9578607

Please sign in to comment.