- add: session_id to the validate token response

- add: session_id to the jwt generated token
This commit is contained in:
2024-12-20 17:46:04 -05:00
parent e0114fd832
commit 9d9e2bef05
4 changed files with 19 additions and 12 deletions

View File

@@ -5,11 +5,12 @@ use std::env;
#[derive(Debug, Serialize, Deserialize)]
struct Claims {
sub: String, // Subject (user ID)
session_id: String, // Session ID
roles: Vec<String>, // Roles/permissions
exp: usize, // Expiration time
}
pub fn generate_token(user_id: &str, roles: Vec<String>) -> Result<String, jsonwebtoken::errors::Error> {
pub fn generate_token(user_id: &str, session_id: &str, roles: Vec<String>) -> Result<String, jsonwebtoken::errors::Error> {
let secret = env::var("JWT_SECRET").expect("JWT_SECRET must be set");
let expiration = chrono::Utc::now()
.checked_add_signed(chrono::Duration::days(1))
@@ -18,6 +19,7 @@ pub fn generate_token(user_id: &str, roles: Vec<String>) -> Result<String, jsonw
let claims = Claims {
sub: user_id.to_owned(),
session_id: session_id.to_owned(),
roles,
exp: expiration,
};
@@ -25,12 +27,12 @@ pub fn generate_token(user_id: &str, roles: Vec<String>) -> Result<String, jsonw
encode(&Header::default(), &claims, &EncodingKey::from_secret(secret.as_ref()))
}
pub fn validate_token(token: &str) -> Result<String, jsonwebtoken::errors::Error> {
pub fn validate_token(token: &str) -> Result<(String, String), jsonwebtoken::errors::Error> {
let secret = env::var("JWT_SECRET").expect("JWT_SECRET must be set");
let token_data = decode::<Claims>(
token,
&DecodingKey::from_secret(secret.as_ref()),
&Validation::default(),
)?;
Ok(token_data.claims.sub)
Ok((token_data.claims.sub, token_data.claims.session_id))
}