Skip to main content

teaql_tool_extra/
jwt.rs

1use jsonwebtoken::{encode, decode, Header, Validation, EncodingKey, DecodingKey};
2use serde::{Deserialize, Serialize};
3use teaql_tool_core::{Result, TeaQLToolError};
4
5pub struct JwtTool;
6
7impl JwtTool {
8    pub fn new() -> Self {
9        Self
10    }
11
12    pub fn sign<T: Serialize>(&self, claims: &T, secret: &str) -> Result<String> {
13        encode(&Header::default(), claims, &EncodingKey::from_secret(secret.as_ref()))
14            .map_err(|e| TeaQLToolError::ExecutionError(format!("JWT sign failed: {}", e)))
15    }
16
17    pub fn verify<T: for<'de> Deserialize<'de>>(&self, token: &str, secret: &str) -> Result<T> {
18        let mut validation = Validation::default();
19        validation.required_spec_claims.clear(); // for generic struct tests
20        
21        let token_data = decode::<T>(
22            token,
23            &DecodingKey::from_secret(secret.as_ref()),
24            &validation
25        ).map_err(|e| TeaQLToolError::ExecutionError(format!("JWT verify failed: {}", e)))?;
26        
27        Ok(token_data.claims)
28    }
29}
30
31impl Default for JwtTool {
32    fn default() -> Self {
33        Self::new()
34    }
35}