Skip to content

Commit

Permalink
Add Claims::new_expires_in() (#97)
Browse files Browse the repository at this point in the history
* Add Claims::new_expires_in()

* Add test for Claims::neW_expires_in()
  • Loading branch information
brycx authored Jun 10, 2023
1 parent 8562318 commit 2add733
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions src/claims.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#![cfg_attr(docsrs, doc(cfg(feature = "std")))]

use crate::errors::Error;
use core::convert::TryFrom;
use serde_json::Value;
use std::collections::HashMap;
use time::format_description::well_known::Rfc3339;
Expand Down Expand Up @@ -40,6 +41,30 @@ impl Claims {
Ok(claims)
}

/// Create a new `Claims` instance expiring in `duration`, setting:
/// - `iat`, `nbf` to current UTC time
/// - `iat + duration`
///
/// Errors:
/// - If adding current time with `duration` would overflow
/// - If `core::time::Duration` failed to convert to `time::Duration`
pub fn new_expires_in(duration: &core::time::Duration) -> Result<Self, Error> {
let iat = OffsetDateTime::now_utc();
let nbf = iat;
let mut exp = iat;
exp += Duration::try_from(*duration).map_err(|_| Error::InvalidClaim)?;

let mut claims = Self {
list_of: HashMap::new(),
};

claims.issued_at(&iat.format(&Rfc3339).map_err(|_| Error::InvalidClaim)?)?;
claims.not_before(&nbf.format(&Rfc3339).map_err(|_| Error::InvalidClaim)?)?;
claims.expiration(&exp.format(&Rfc3339).map_err(|_| Error::InvalidClaim)?)?;

Ok(claims)
}

/// Removes the `exp` claim, indicating a token that never expires.
pub fn non_expiring(&mut self) {
if self.contains_claim("exp") {
Expand Down Expand Up @@ -731,4 +756,24 @@ mod test {
claims.list_of.remove("exp");
assert!(claims_validation.validate_claims(&claims).is_err());
}

#[test]
fn test_custom_expiration_duration() {
// Duration of 3 hours instead of 1.
let duration = core::time::Duration::new(10800, 0);
let mut claims = Claims::new_expires_in(&duration).unwrap();

let claims_validation = ClaimsValidationRules::new();
assert!(claims_validation.validate_claims(&claims).is_ok());

claims
.list_of
.insert("exp".to_string(), "2019-01-01T00:00:00+00:00".into())
.unwrap();
// Expired
assert_eq!(
claims_validation.validate_claims(&claims).unwrap_err(),
Error::ClaimValidation
);
}
}

0 comments on commit 2add733

Please sign in to comment.