nullnet_libtoken/
lib.rs

1mod models;
2
3use base64::Engine as _;
4use serde::Deserialize;
5
6pub use models::{Account, Device, Organization};
7
8/// Represents a decoded JWT payload containing account information and metadata.
9/// Includes issue and expiration times for the token.
10#[derive(Debug, Deserialize)]
11pub struct Token {
12    pub account: Account,
13    pub iat: u64,
14    pub exp: u64,
15}
16
17impl Token {
18    /// Decodes a JWT and parses its payload into a `Token` struct.
19    ///
20    /// # Arguments
21    /// * `jwt` - A JWT string consisting of three parts separated by periods (`.`).
22    ///
23    /// # Returns
24    /// * `Ok(Token)` if the token is successfully decoded and parsed.
25    /// * `Err(Error)` if the token is malformed, Base64 decoding fails, or payload deserialization fails.
26    #[allow(clippy::missing_errors_doc)]
27    pub fn from_jwt(jwt: &str) -> Result<Self, String> {
28        let parts: Vec<&str> = jwt.split('.').collect();
29
30        if parts.len() != 3 {
31            return Err(String::from("Malformed JWT"));
32        }
33
34        let decoded_payload = base64::engine::general_purpose::URL_SAFE_NO_PAD
35            .decode(parts[1])
36            .map_err(|e| e.to_string())?;
37
38        let token: Token = serde_json::from_slice(&decoded_payload).map_err(|e| e.to_string())?;
39
40        Ok(token)
41    }
42}