Skip to content

Commit

Permalink
fix: jwt
Browse files Browse the repository at this point in the history
  • Loading branch information
ElaBosak233 committed Feb 3, 2025
1 parent bd2f637 commit 619c5c7
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 28 deletions.
3 changes: 1 addition & 2 deletions crates/web/src/middleware/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,7 @@ pub async fn auth(mut req: Request<Body>, next: Next) -> Result<Response, WebErr

let token = jar.get("token").map(|cookie| cookie.value()).unwrap_or("");

let decoding_key =
DecodingKey::from_secret(crate::util::jwt::get_jwt_config().await.secret.as_bytes());
let decoding_key = DecodingKey::from_secret(cds_config::get_config().auth.secret.as_bytes());
let validation = Validation::default();

let mut user: Option<cds_db::transfer::User> = None;
Expand Down
2 changes: 1 addition & 1 deletion crates/web/src/router/api/user/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,7 @@ pub async fn user_login(
format!(
"token={}; Max-Age={}; Path=/; HttpOnly; SameSite=Strict",
token,
chrono::Duration::minutes(jwt::get_jwt_config().await.expiration).num_seconds()
chrono::Duration::minutes(cds_config::get_config().auth.expiration).num_seconds()
)
.parse()
.unwrap(),
Expand Down
30 changes: 5 additions & 25 deletions crates/web/src/util/jwt.rs
Original file line number Diff line number Diff line change
@@ -1,44 +1,24 @@
use jsonwebtoken::{EncodingKey, Header, encode};
use regex::Regex;
use jsonwebtoken::{encode, EncodingKey, Header};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

#[derive(Debug, Deserialize, Serialize)]
pub struct Claims {
pub id: i64,
pub exp: usize,
}

pub async fn get_jwt_config() -> cds_config::auth::Config {
if let Some(jwt) = cds_cache::get::<cds_config::auth::Config>("jwt")
.await
.unwrap()
{
return jwt;
}

let mut jwt = cds_config::get_config().auth.clone();
let re = Regex::new(r"\[([Uu][Uu][Ii][Dd])]").unwrap();
jwt.secret = re
.replace_all(&jwt.secret, Uuid::new_v4().simple().to_string())
.to_string();
let _ = cds_cache::set("jwt", jwt.clone()).await;

jwt
}

pub async fn generate_jwt_token(user_id: i64) -> String {
let jwt_config = get_jwt_config().await;
let claims = Claims {
id: user_id,
exp: (chrono::Utc::now() + chrono::Duration::minutes(jwt_config.expiration)).timestamp()
as usize,
exp: (chrono::Utc::now()
+ chrono::Duration::minutes(cds_config::get_config().auth.expiration))
.timestamp() as usize,
};

encode(
&Header::default(),
&claims,
&EncodingKey::from_secret(jwt_config.secret.as_bytes()),
&EncodingKey::from_secret(cds_config::get_config().auth.secret.as_bytes()),
)
.unwrap()
}

0 comments on commit 619c5c7

Please sign in to comment.