Skip to content

Commit b00e490

Browse files
committed
wip: move jwt to env
1 parent 74319ce commit b00e490

File tree

12 files changed

+42
-30
lines changed

12 files changed

+42
-30
lines changed

crates/cache/src/lib.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,11 @@ pub async fn set_ex(
6060
Ok(())
6161
}
6262

63+
pub async fn exists(key: impl Into<Key> + Send + Display) -> Result<bool, CacheError> {
64+
let result = get_client().exists(key).await?;
65+
Ok(result)
66+
}
67+
6368
pub async fn flush() -> Result<(), CacheError> {
6469
get_client().flushall::<()>(false).await?;
6570

crates/config/src/auth/jwt.rs

Lines changed: 0 additions & 7 deletions
This file was deleted.

crates/config/src/auth/mod.rs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
1-
pub mod jwt;
21
pub mod registration;
32

43
use sea_orm::FromJsonQueryResult;
54
use serde::{Deserialize, Serialize};
65

76
#[derive(Clone, Debug, Serialize, Deserialize, FromJsonQueryResult, PartialEq, Eq, Default)]
87
pub struct Config {
9-
pub jwt: jwt::Config,
108
pub registration: registration::Config,
119
}

crates/config/src/lib.rs

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,6 @@ impl From<cds_db::entity::config::Model> for Config {
2020
}
2121
}
2222

23-
impl Config {
24-
pub fn desensitize(&mut self) {
25-
self.auth.jwt.secret_key.clear();
26-
}
27-
}
28-
2923
pub async fn init() {
3024
let config = cds_cache::get::<Config>("config").await.unwrap();
3125
if config.is_none() {

crates/env/src/axum/jwt.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
use serde::{Deserialize, Serialize};
2+
3+
#[derive(Clone, Debug, Serialize, Deserialize)]
4+
pub struct Env {
5+
pub secret: String,
6+
pub expiration: i64,
7+
}

crates/env/src/axum/mod.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
1+
pub mod jwt;
2+
13
use serde::{Deserialize, Serialize};
24

35
#[derive(Clone, Debug, Serialize, Deserialize)]
46
pub struct Env {
57
pub host: String,
68
pub port: u16,
9+
pub jwt: jwt::Env,
710
}

crates/server/src/migrator.rs

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -77,10 +77,6 @@ pub async fn init_config() {
7777
let config = entity::config::ActiveModel {
7878
value: Set(serde_json::to_value(cds_config::Config {
7979
auth: cds_config::auth::Config {
80-
jwt: cds_config::auth::jwt::Config {
81-
secret_key: String::from(uuid::Uuid::new_v4()),
82-
expiration: 1800,
83-
},
8480
registration: cds_config::auth::registration::Config {
8581
enabled: true,
8682
captcha: false,

crates/web/Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ resolver = "2"
99
cds-db = { workspace = true }
1010
cds-config = { workspace = true }
1111
cds-cluster = { workspace = true }
12+
cds-cache = { workspace = true }
13+
cds-env = { workspace = true }
1214
cds-media = { workspace = true }
1315
cds-metric = { workspace = true }
1416
cds-queue = { workspace = true }

crates/web/src/middleware/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ pub async fn auth(mut req: Request<Body>, next: Next) -> Result<Response, WebErr
3838

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

41-
let decoding_key = DecodingKey::from_secret(crate::util::jwt::get_secret().await.as_bytes());
41+
let decoding_key = DecodingKey::from_secret(crate::util::jwt::get_jwt_config().await.secret.as_bytes());
4242
let validation = Validation::default();
4343

4444
let mut user: Option<cds_db::transfer::User> = None;

crates/web/src/router/api/config/mod.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,7 @@ pub async fn get(
4848
})
4949
}
5050
_ => {
51-
let mut config = get_config().await;
52-
config.desensitize();
51+
let config = get_config().await;
5352

5453
Ok(WebResponse {
5554
code: StatusCode::OK.as_u16(),

crates/web/src/router/api/user/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -270,7 +270,7 @@ pub async fn login(Json(mut body): Json<LoginRequest>) -> Result<impl IntoRespon
270270
format!(
271271
"token={}; Max-Age={}; Path=/; HttpOnly; SameSite=Strict",
272272
token,
273-
chrono::Duration::minutes(cds_config::get_config().await.auth.jwt.expiration)
273+
chrono::Duration::minutes(jwt::get_jwt_config().await.expiration)
274274
.num_seconds()
275275
)
276276
.parse()

crates/web/src/util/jwt.rs

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,44 @@
11
use jsonwebtoken::{EncodingKey, Header, encode};
2+
use regex::Regex;
23
use serde::{Deserialize, Serialize};
4+
use uuid::Uuid;
35

46
#[derive(Debug, Deserialize, Serialize)]
57
pub struct Claims {
68
pub id: i64,
79
pub exp: usize,
810
}
911

10-
pub async fn get_secret() -> String {
11-
cds_config::get_config().await.auth.jwt.secret_key
12+
pub async fn get_jwt_config() -> cds_env::axum::jwt::Env {
13+
if let Some(jwt) = cds_cache::get::<cds_env::axum::jwt::Env>("jwt")
14+
.await
15+
.unwrap()
16+
{
17+
return jwt;
18+
}
19+
20+
let mut jwt = cds_env::get_env().axum.jwt.clone();
21+
let re = Regex::new(r"\[([Uu][Uu][Ii][Dd])]").unwrap();
22+
jwt.secret = re
23+
.replace_all(&jwt.secret, Uuid::new_v4().simple().to_string())
24+
.to_string();
25+
let _ = cds_cache::set("jwt", jwt.clone()).await;
26+
27+
jwt
1228
}
1329

1430
pub async fn generate_jwt_token(user_id: i64) -> String {
15-
let secret = get_secret().await;
31+
let jwt_config = get_jwt_config().await;
1632
let claims = Claims {
1733
id: user_id,
18-
exp: (chrono::Utc::now()
19-
+ chrono::Duration::minutes(cds_config::get_config().await.auth.jwt.expiration))
20-
.timestamp() as usize,
34+
exp: (chrono::Utc::now() + chrono::Duration::minutes(jwt_config.expiration)).timestamp()
35+
as usize,
2136
};
2237

2338
encode(
2439
&Header::default(),
2540
&claims,
26-
&EncodingKey::from_secret(secret.as_bytes()),
41+
&EncodingKey::from_secret(jwt_config.secret.as_bytes()),
2742
)
2843
.unwrap()
2944
}

0 commit comments

Comments
 (0)