Skip to content

Commit

Permalink
wip: move jwt to env
Browse files Browse the repository at this point in the history
  • Loading branch information
ElaBosak233 committed Jan 24, 2025
1 parent 74319ce commit b00e490
Show file tree
Hide file tree
Showing 12 changed files with 42 additions and 30 deletions.
5 changes: 5 additions & 0 deletions crates/cache/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,11 @@ pub async fn set_ex(
Ok(())
}

pub async fn exists(key: impl Into<Key> + Send + Display) -> Result<bool, CacheError> {
let result = get_client().exists(key).await?;
Ok(result)
}

pub async fn flush() -> Result<(), CacheError> {
get_client().flushall::<()>(false).await?;

Expand Down
7 changes: 0 additions & 7 deletions crates/config/src/auth/jwt.rs

This file was deleted.

2 changes: 0 additions & 2 deletions crates/config/src/auth/mod.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
pub mod jwt;
pub mod registration;

use sea_orm::FromJsonQueryResult;
use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, Serialize, Deserialize, FromJsonQueryResult, PartialEq, Eq, Default)]
pub struct Config {
pub jwt: jwt::Config,
pub registration: registration::Config,
}
6 changes: 0 additions & 6 deletions crates/config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,6 @@ impl From<cds_db::entity::config::Model> for Config {
}
}

impl Config {
pub fn desensitize(&mut self) {
self.auth.jwt.secret_key.clear();
}
}

pub async fn init() {
let config = cds_cache::get::<Config>("config").await.unwrap();
if config.is_none() {
Expand Down
7 changes: 7 additions & 0 deletions crates/env/src/axum/jwt.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Env {
pub secret: String,
pub expiration: i64,
}
3 changes: 3 additions & 0 deletions crates/env/src/axum/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
pub mod jwt;

use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Env {
pub host: String,
pub port: u16,
pub jwt: jwt::Env,
}
4 changes: 0 additions & 4 deletions crates/server/src/migrator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,6 @@ pub async fn init_config() {
let config = entity::config::ActiveModel {
value: Set(serde_json::to_value(cds_config::Config {
auth: cds_config::auth::Config {
jwt: cds_config::auth::jwt::Config {
secret_key: String::from(uuid::Uuid::new_v4()),
expiration: 1800,
},
registration: cds_config::auth::registration::Config {
enabled: true,
captcha: false,
Expand Down
2 changes: 2 additions & 0 deletions crates/web/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ resolver = "2"
cds-db = { workspace = true }
cds-config = { workspace = true }
cds-cluster = { workspace = true }
cds-cache = { workspace = true }
cds-env = { workspace = true }
cds-media = { workspace = true }
cds-metric = { workspace = true }
cds-queue = { workspace = true }
Expand Down
2 changes: 1 addition & 1 deletion crates/web/src/middleware/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +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_secret().await.as_bytes());
let decoding_key = DecodingKey::from_secret(crate::util::jwt::get_jwt_config().await.secret.as_bytes());
let validation = Validation::default();

let mut user: Option<cds_db::transfer::User> = None;
Expand Down
3 changes: 1 addition & 2 deletions crates/web/src/router/api/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,7 @@ pub async fn get(
})
}
_ => {
let mut config = get_config().await;
config.desensitize();
let config = get_config().await;

Ok(WebResponse {
code: StatusCode::OK.as_u16(),
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 @@ -270,7 +270,7 @@ pub async fn login(Json(mut body): Json<LoginRequest>) -> Result<impl IntoRespon
format!(
"token={}; Max-Age={}; Path=/; HttpOnly; SameSite=Strict",
token,
chrono::Duration::minutes(cds_config::get_config().await.auth.jwt.expiration)
chrono::Duration::minutes(jwt::get_jwt_config().await.expiration)
.num_seconds()
)
.parse()
Expand Down
29 changes: 22 additions & 7 deletions crates/web/src/util/jwt.rs
Original file line number Diff line number Diff line change
@@ -1,29 +1,44 @@
use jsonwebtoken::{EncodingKey, Header, encode};
use regex::Regex;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

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

pub async fn get_secret() -> String {
cds_config::get_config().await.auth.jwt.secret_key
pub async fn get_jwt_config() -> cds_env::axum::jwt::Env {
if let Some(jwt) = cds_cache::get::<cds_env::axum::jwt::Env>("jwt")
.await
.unwrap()
{
return jwt;
}

let mut jwt = cds_env::get_env().axum.jwt.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 secret = get_secret().await;
let jwt_config = get_jwt_config().await;
let claims = Claims {
id: user_id,
exp: (chrono::Utc::now()
+ chrono::Duration::minutes(cds_config::get_config().await.auth.jwt.expiration))
.timestamp() as usize,
exp: (chrono::Utc::now() + chrono::Duration::minutes(jwt_config.expiration)).timestamp()
as usize,
};

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

0 comments on commit b00e490

Please sign in to comment.