stynx_code_bridge/infrastructure/
jwt_auth.rs1use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
2use stynx_code_errors::{AppError, AppResult};
3use serde::{Deserialize, Serialize};
4
5#[derive(Debug, Clone, Serialize, Deserialize)]
6pub struct JwtClaims {
7 pub sub: String,
8 pub exp: u64,
9 pub iat: u64,
10}
11
12pub struct JwtValidator;
13
14impl JwtValidator {
15 pub fn new() -> Self {
16 Self
17 }
18
19 pub fn validate_token(&self, token: &str) -> AppResult<JwtClaims> {
20 let parts: Vec<&str> = token.splitn(3, '.').collect();
21 if parts.len() != 3 {
22 return Err(AppError::Unauthorized);
23 }
24
25 let payload_bytes = URL_SAFE_NO_PAD
26 .decode(parts[1])
27 .map_err(|_| AppError::Unauthorized)?;
28
29 let claims: JwtClaims = serde_json::from_slice(&payload_bytes)
30 .map_err(|_| AppError::Unauthorized)?;
31
32 Ok(claims)
33 }
34}
35
36impl Default for JwtValidator {
37 fn default() -> Self {
38 Self::new()
39 }
40}