use jsonwebtoken::{DecodingKey, EncodingKey, TokenData}; use once_cell::sync::Lazy; use serde::{de::DeserializeOwned, Serialize}; use super::Error; pub static JWT: Lazy = Lazy::new(|| { let secret = std::env::var("JWT_SECRET").expect("JWT_SECRET must be set"); Jwt::new(secret.as_bytes()) }); pub struct Jwt { encoding: EncodingKey, decoding: DecodingKey, header: jsonwebtoken::Header, validation: jsonwebtoken::Validation, } impl Jwt { fn new(secret: &[u8]) -> Self { Self { encoding: EncodingKey::from_secret(secret), decoding: DecodingKey::from_secret(secret), header: Default::default(), validation: Default::default(), } } pub fn encode(&self, claims: &T) -> Result where T: Serialize, { jsonwebtoken::encode(&self.header, claims, &self.encoding).map_err(Into::into) } pub fn decode(&self, token: &str) -> Result, Error> where T: DeserializeOwned, { jsonwebtoken::decode(token, &self.decoding, &self.validation).map_err(Into::into) } }