use crate::error::{GarrisonError, GarrisonResult};
use jsonwebtoken::{decode, encode, Algorithm, DecodingKey, EncodingKey, Header, Validation};
use std::time::{SystemTime, UNIX_EPOCH};
use super::{GarrisonJwtClaims, JwtHandler};
impl JwtHandler {
pub fn new(secret: impl Into<String>) -> Self {
Self {
secret: secret.into(),
algorithm: Algorithm::HS256,
device: None,
}
}
pub fn with_algorithm(mut self, algorithm: Algorithm) -> Self {
self.algorithm = algorithm;
self
}
pub fn with_device(mut self, device: impl Into<String>) -> Self {
self.device = Some(device.into());
self
}
pub fn sign(&self, login_id: impl Into<String>, timeout: i64) -> GarrisonResult<String> {
let login_id: String = login_id.into();
if self.secret.is_empty() {
return Err(GarrisonError::Config("jwt-secret-empty".to_string()));
}
if timeout < 0 {
return Err(GarrisonError::Config(format!(
"timeout 不能为负数: {}",
timeout
)));
}
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|e| GarrisonError::Internal(format!("system-clock-error::{}", e)))?
.as_secs() as i64;
let claims = GarrisonJwtClaims {
sub: login_id.clone(),
iat: now,
exp: now + timeout,
login_id,
device: self.device.clone(),
jti: Some(uuid::Uuid::new_v4().to_string()),
nbf: Some(now), };
let header = Header::new(self.algorithm);
let key = EncodingKey::from_secret(self.secret.as_bytes());
encode(&header, &claims, &key)
.map_err(|e| GarrisonError::Internal(format!("jwt-sign::{}", e)))
}
pub fn verify(&self, token: &str) -> GarrisonResult<GarrisonJwtClaims> {
if self.secret.is_empty() {
return Err(GarrisonError::Config("jwt-secret-empty".to_string()));
}
let key = DecodingKey::from_secret(self.secret.as_bytes());
let mut validation = Validation::new(self.algorithm);
validation.validate_exp = true;
validation.validate_nbf = true; validation.leeway = 0;
decode::<GarrisonJwtClaims>(token, &key, &validation)
.map(|data| data.claims)
.map_err(|e| {
let msg = e.to_string();
if msg.contains("ExpiredSignature") {
GarrisonError::ExpiredToken(format!("jwt-expired::{}", e))
} else if msg.contains("ImmatureSignature") || msg.contains("nbf") {
GarrisonError::InvalidToken(format!("jwt-not-yet-valid::{}", e))
} else {
GarrisonError::InvalidToken(format!("jwt-invalid::{}", e))
}
})
}
pub fn refresh(&self, token: &str, new_timeout: i64) -> GarrisonResult<String> {
let claims = self.verify(token)?;
self.sign(claims.login_id, new_timeout)
}
}
#[cfg(feature = "protocol-zeroize")]
impl Drop for JwtHandler {
fn drop(&mut self) {
use zeroize::Zeroize;
self.secret.zeroize();
}
}