use serde::{Deserialize, Serialize};
use std::time;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Token {
pub token_type: String,
pub expires_in: u64,
pub access_token: String,
pub refresh_token: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TokenWrapper {
pub token: Token,
pub generate_time: u64,
}
impl TokenWrapper {
fn sec_since_epoch() -> u64 {
time::SystemTime::now()
.duration_since(time::UNIX_EPOCH)
.unwrap()
.as_secs()
}
pub fn new(token: Token) -> Self {
TokenWrapper {
token,
generate_time: Self::sec_since_epoch(),
}
}
pub fn expired(&self) -> bool {
let now = Self::sec_since_epoch();
now >= self.generate_time + self.token.expires_in
}
pub fn expires_in_secs(&self) -> Option<u64> {
let now = Self::sec_since_epoch();
let expires_in = self.generate_time + self.token.expires_in;
if now >= expires_in {
None
} else {
Some(expires_in - now)
}
}
pub fn expire_time(&self) -> Option<time::SystemTime> {
self.expires_in_secs()
.map(|secs| time::SystemTime::now() + time::Duration::from_secs(secs))
}
}