1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//! [`Key`] and functions to encode & decode expiring claims.

use time::OffsetDateTime;

pub use crate::signed::Key;

/// Join a string and an expiry date together into a string.
pub fn encode_expiring_claim(claim: &str, expiry_date: OffsetDateTime) -> String {
    format!("{}:{}", claim, expiry_date.unix_timestamp())
}

/// Extract the string, failing if the expiry date is in the past.
pub fn decode_expiring_claim(value: String) -> Result<String,&'static str> {
    let mut parts = value.splitn(2, ':');
    let claim = parts.next().ok_or("expected colon")?;
    let expiry_date = parts.next().ok_or("expected colon")?;
    let expiry_date: i64 = expiry_date.parse().map_err(|_| "failed to parse timestamp")?;

    if expiry_date > OffsetDateTime::now_utc().unix_timestamp() {
        Ok(claim.to_string())
    } else {
        Err("token is expired")
    }
}