feat: add token expiry check in token

This commit is contained in:
Zack Fu Zi Xiang 2024-01-26 13:45:57 +08:00
parent f8f1e885f5
commit e690a775fd
No known key found for this signature in database
GPG Key ID: 39DE600AFEEED522
3 changed files with 16 additions and 4 deletions

7
Cargo.lock generated
View File

@ -1133,9 +1133,9 @@ checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e"
[[package]]
name = "chrono"
version = "0.4.31"
version = "0.4.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f2c685bad3eb3d45a01354cedb7d5faa66194d1d58ba6e267a8de788f79db38"
checksum = "9f13690e35a5e4ace198e7beea2895d29f3a9cc55015fcebe6336bd2010af9eb"
dependencies = [
"android-tzdata",
"iana-time-zone",
@ -1143,7 +1143,7 @@ dependencies = [
"num-traits",
"serde",
"wasm-bindgen",
"windows-targets 0.48.5",
"windows-targets 0.52.0",
]
[[package]]
@ -2249,6 +2249,7 @@ version = "0.1.0"
dependencies = [
"anyhow",
"app-error",
"chrono",
"jsonwebtoken",
"lazy_static",
"serde",

View File

@ -12,3 +12,4 @@ anyhow = "1.0.79"
lazy_static = "1.4.0"
jsonwebtoken = "8.3.0"
app-error = { workspace = true, features = ["gotrue_error"] }
chrono = "0.4.33"

View File

@ -35,6 +35,16 @@ lazy_static::lazy_static! {
impl GoTrueJWTClaims {
pub fn verify(token: &str, secret: &[u8]) -> Result<Self, jsonwebtoken::errors::Error> {
Ok(decode(token, &DecodingKey::from_secret(secret), &VALIDATION)?.claims)
let claims = decode::<Self>(token, &DecodingKey::from_secret(secret), &VALIDATION)?.claims;
let ts_expiry = claims.exp.ok_or_else(|| {
jsonwebtoken::errors::ErrorKind::MissingRequiredClaim("expect exp but not found".to_owned())
})?;
let ts_now = chrono::Utc::now().timestamp();
match ts_now > ts_expiry {
true => Err(jsonwebtoken::errors::ErrorKind::ExpiredSignature.into()),
false => Ok(claims),
}
}
}