forked from Txio-labs/txio-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth_jwt.rs
More file actions
108 lines (91 loc) · 3.53 KB
/
Copy pathauth_jwt.rs
File metadata and controls
108 lines (91 loc) · 3.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
use crate::utils::error::AppError;
use chrono::{Duration, Utc};
use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Debug, Serialize, Deserialize)]
pub struct Claims {
pub sub: String, // user_id
pub email: String,
pub exp: i64, // expiration timestamp
pub iat: i64, // issued at
/// JWT ID — a UUID v4 that uniquely identifies this token and is used
/// as the session identifier in the sessions collection.
/// `Option` keeps backward-compatibility with tokens issued before this
/// field was added.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub jti: Option<String>,
}
#[derive(Clone)]
pub struct JwtHelper {
secret: String,
}
impl JwtHelper {
pub fn new(secret: String) -> Self {
Self { secret }
}
/// Generate a signed JWT. A fresh UUID v4 is embedded as `jti` so every
/// issued token has a unique, stable session identifier. Returns
/// `(token_string, jti)` so callers can persist the session.
pub fn generate_token(&self, user_id: &str, email: &str) -> Result<(String, String), AppError> {
let now = Utc::now();
let expiration = now + Duration::hours(24);
// Ensure expiration is valid
if expiration.timestamp() < now.timestamp() {
return Err(AppError::InternalError("Invalid token expiration".into()));
}
let jti = Uuid::new_v4().to_string();
let claims = Claims {
sub: user_id.to_string(),
email: email.to_string(),
exp: expiration.timestamp(),
iat: now.timestamp(),
jti: Some(jti.clone()),
};
let token = encode(
&Header::default(),
&claims,
&EncodingKey::from_secret(self.secret.as_bytes()),
)
.map_err(|e| AppError::InternalError(format!("Failed to generate token: {e}")))?;
Ok((token, jti))
}
pub fn verify_token(&self, token: &str) -> Result<Claims, AppError> {
decode::<Claims>(
token,
&DecodingKey::from_secret(self.secret.as_bytes()),
&Validation::default(),
)
.map(|data| data.claims)
.map_err(|_| AppError::Unauthorized("Invalid token".to_string()))
}
}
use axum::{extract::FromRequestParts, http::request::Parts, Extension};
#[axum::async_trait]
impl<S> FromRequestParts<S> for Claims
where
S: Send + Sync,
{
type Rejection = AppError;
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
// Extract the token from the authorization header
let auth_header = parts
.headers
.get(axum::http::header::AUTHORIZATION)
.and_then(|value| value.to_str().ok())
.ok_or_else(|| AppError::Unauthorized("Missing authorization header".to_string()))?;
if !auth_header.starts_with("Bearer ") {
return Err(AppError::Unauthorized(
"Invalid authorization header format".to_string(),
));
}
let token = auth_header[7..].to_string();
// JwtHelper is built once in main.rs and shared via an Extension
// layer on the whole app, so this no longer reloads Config/env
// on every request.
let Extension(helper) = Extension::<JwtHelper>::from_request_parts(parts, state)
.await
.map_err(|_| AppError::InternalError("JWT helper not configured".into()))?;
helper.verify_token(&token)
}
}