Skip to main content

fr_rust/linkv/
linkv.rs

1use crate::prelude::*;
2use std::time::{SystemTime, UNIX_EPOCH};
3
4// --- ERROR HANDLING ---
5
6#[derive(thiserror::Error, Debug)]
7pub enum LinkVError {
8    #[error("JWT error: {0}")]
9    JwtError(String),
10    #[error("Invalid Token!")]
11    InvalidToken
12}
13
14pub type Result<T> = std::result::Result<T, LinkVError>;
15
16// --- SERVICE IMPLEMENTATION ---
17
18#[derive(Clone)]
19pub struct LinkVConfig {
20    pub secret: String,
21    pub crypto: CryptoService,
22    pub redis: RedisManager,
23    pub jwt: JwtService,
24}
25
26#[derive(Clone)]
27pub struct LinkV {
28    config: LinkVConfig,
29}
30
31impl LinkV {
32    pub fn new(config: LinkVConfig) -> Self {
33        Self { config }
34    }
35
36    /// Generates a token using JWT. And, It sets an expiration timestamp.
37    pub fn generate_token(&self, key: &str, expiry_time: u32) -> Result<String> {
38        // 1. Calculate the absolute timestamp using the provided expiry_time (in seconds)
39        let current_time = SystemTime::now()
40            .duration_since(UNIX_EPOCH)
41            .map_err(|e| LinkVError::JwtError(e.to_string()))?
42            .as_secs() as usize;
43        
44        let expiry_timestamp = current_time + expiry_time as usize;
45        
46        // 2. Generate the token using your JWT service
47        let token = self.config.jwt.generate_exp_token(key, expiry_timestamp)
48            .map_err(|e| LinkVError::JwtError(format!("{:?}", e)))?;
49        
50        Ok(token)
51    }
52
53    /// Verifies the token. If valid, deletes it from Redis (one-time use) and returns the token itself.
54    /// If invalid, returns false.
55    pub fn verify_token(&self, token: &str) -> Result<bool> {
56            // Verify structural/signature integrity via JWT first
57            if !self.config.jwt.verify_token(token) {
58                return Err(LinkVError::InvalidToken);
59            } else {
60                return Ok(true);
61            }
62        }
63}