diff options
Diffstat (limited to 'src/security.rs')
-rw-r--r-- | src/security.rs | 33 |
1 files changed, 24 insertions, 9 deletions
diff --git a/src/security.rs b/src/security.rs index cd9d7bd..bc3b381 100644 --- a/src/security.rs +++ b/src/security.rs @@ -7,17 +7,30 @@ mod signed; /// Join a string and an expiry date together into a string. pub fn encode_expiring_claim(claim: &str, expiry_date: SystemTime) -> String { - format!("{}:{}", claim, expiry_date.duration_since(UNIX_EPOCH).unwrap().as_secs()) + format!( + "{}:{}", + claim, + expiry_date.duration_since(UNIX_EPOCH).unwrap().as_secs() + ) } /// Extract the string, failing if the expiry date is in the past. pub fn decode_expiring_claim(value: &str) -> Result<&str, &'static str> { let mut parts = value.rsplitn(2, ':'); - let expiry_date = parts.next().expect("first .rsplitn().next() is expected to return Some"); + let expiry_date = parts + .next() + .expect("first .rsplitn().next() is expected to return Some"); let claim = parts.next().ok_or("expected colon")?; - let expiry_date: u64 = expiry_date.parse().map_err(|_| "failed to parse timestamp")?; - - if expiry_date > SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() { + let expiry_date: u64 = expiry_date + .parse() + .map_err(|_| "failed to parse timestamp")?; + + if expiry_date + > SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_secs() + { Ok(claim) } else { Err("token is expired") @@ -26,17 +39,19 @@ pub fn decode_expiring_claim(value: &str) -> Result<&str, &'static str> { #[cfg(test)] mod tests { - use std::time::{SystemTime, Duration}; + use std::time::{Duration, SystemTime}; #[test] fn test_expiring_claim() { for claim in vec!["test", "", "foo:bar"] { - let encoded_claim = super::encode_expiring_claim(claim, SystemTime::now() + Duration::from_secs(60)); + let encoded_claim = + super::encode_expiring_claim(claim, SystemTime::now() + Duration::from_secs(60)); assert_eq!(super::decode_expiring_claim(&encoded_claim).unwrap(), claim); - let encoded_claim = super::encode_expiring_claim(claim, SystemTime::now() - Duration::from_secs(60)); + let encoded_claim = + super::encode_expiring_claim(claim, SystemTime::now() - Duration::from_secs(60)); assert!(super::decode_expiring_claim(&encoded_claim).is_err()); } assert!(super::decode_expiring_claim("test".into()).is_err()); } -}
\ No newline at end of file +} |