Skip to main content

fr_rust/jwt/
jwt.rs

1use jsonwebtoken::{encode, decode, Header, Algorithm, Validation, EncodingKey, DecodingKey};
2use serde::{Serialize, Deserialize};
3
4#[derive(Debug, Serialize, Deserialize)]
5pub struct Claims {
6    pub sub: String,
7    #[serde(skip_serializing_if = "Option::is_none")]
8    pub exp: Option<usize>,
9}
10
11#[derive(Clone)]
12pub struct Jwt {
13    secret: String,
14}
15
16impl Jwt {
17    // Create a new instance
18    pub fn new(secret: String) -> Self {
19        Jwt { secret }
20    }
21
22    // 1. Modified: Removed 'secret' from params, uses self.secret instead
23    pub fn generate_token(&self, key: &str) -> Result<String, jsonwebtoken::errors::Error> {
24        let claims = Claims {
25            sub: key.to_owned(),
26            exp: None,
27        };
28        encode(
29            &Header::default(),
30            &claims,
31            &EncodingKey::from_secret(self.secret.as_bytes()),
32        )
33    }
34
35    // Generate a token with a custom expiration timestamp
36    pub fn generate_exp_token(&self, key: &str, exp: usize) -> Result<String, jsonwebtoken::errors::Error> {
37        let claims = Claims {
38            sub: key.to_owned(),
39            exp: Some(exp),
40        };
41
42        encode(
43            &Header::default(),
44            &claims,
45            &EncodingKey::from_secret(self.secret.as_bytes()),
46        )
47    }
48
49    // Verify the token and return a boolean (true/false)
50    // Modified: Fixed 'secret' variable error, now uses self.secret
51    pub fn verify_token(&self, token: &str) -> bool {
52        let mut validation = Validation::new(Algorithm::HS256);
53        validation.validate_exp = false; 
54
55        let result = decode::<Claims>(
56            token,
57            &DecodingKey::from_secret(self.secret.as_bytes()),
58            &validation,
59        );
60
61        result.is_ok()
62    }
63
64    // 2. Added: parse_token to convert tokens back to the real Claims content
65    pub fn parse_token(&self, token: &str) -> Result<Claims, jsonwebtoken::errors::Error> {
66        let mut validation = Validation::new(Algorithm::HS256);
67        // Turn off expiration check here as well, matching your verify_token logic. 
68        // If you want expiration to trigger an error, change this to true.
69        validation.validate_exp = false; 
70
71        let token_data = decode::<Claims>(
72            token,
73            &DecodingKey::from_secret(self.secret.as_bytes()),
74            &validation,
75        )?;
76
77        Ok(token_data.claims)
78    }
79}