feat: add refresh cookie reader

This commit is contained in:
2026-04-21 13:34:54 +08:00
parent adaf514a1a
commit 39eb7a513c
12 changed files with 653 additions and 11 deletions

View File

@@ -9,6 +9,11 @@ pub struct AppConfig {
pub jwt_issuer: String,
pub jwt_secret: String,
pub jwt_access_token_ttl_seconds: u64,
pub refresh_cookie_name: String,
pub refresh_cookie_path: String,
pub refresh_cookie_secure: bool,
pub refresh_cookie_same_site: String,
pub refresh_session_ttl_days: u32,
}
impl Default for AppConfig {
@@ -20,6 +25,11 @@ impl Default for AppConfig {
jwt_issuer: "https://auth.genarrative.local".to_string(),
jwt_secret: "genarrative-dev-secret".to_string(),
jwt_access_token_ttl_seconds: 2 * 60 * 60,
refresh_cookie_name: "genarrative_refresh_session".to_string(),
refresh_cookie_path: "/api/auth".to_string(),
refresh_cookie_secure: false,
refresh_cookie_same_site: "Lax".to_string(),
refresh_session_ttl_days: 30,
}
}
}
@@ -65,6 +75,30 @@ impl AppConfig {
config.jwt_access_token_ttl_seconds = ttl_seconds;
}
if let Some(refresh_cookie_name) = read_first_non_empty_env(&["AUTH_REFRESH_COOKIE_NAME"]) {
config.refresh_cookie_name = refresh_cookie_name;
}
if let Some(refresh_cookie_path) = read_first_non_empty_env(&["AUTH_REFRESH_COOKIE_PATH"]) {
config.refresh_cookie_path = refresh_cookie_path;
}
if let Some(refresh_cookie_same_site) =
read_first_non_empty_env(&["AUTH_REFRESH_COOKIE_SAME_SITE"])
{
config.refresh_cookie_same_site = refresh_cookie_same_site;
}
if let Some(refresh_cookie_secure) = read_first_bool_env(&["AUTH_REFRESH_COOKIE_SECURE"]) {
config.refresh_cookie_secure = refresh_cookie_secure;
}
if let Some(refresh_session_ttl_days) =
read_first_positive_u32_env(&["AUTH_REFRESH_SESSION_TTL_DAYS"])
{
config.refresh_session_ttl_days = refresh_session_ttl_days;
}
config
}
@@ -97,6 +131,19 @@ fn read_first_duration_seconds_env(keys: &[&str]) -> Option<u64> {
})
}
fn read_first_bool_env(keys: &[&str]) -> Option<bool> {
keys.iter()
.find_map(|key| env::var(key).ok().and_then(|value| parse_bool(&value)))
}
fn read_first_positive_u32_env(keys: &[&str]) -> Option<u32> {
keys.iter().find_map(|key| {
env::var(key)
.ok()
.and_then(|value| parse_positive_u32(&value))
})
}
fn parse_duration_seconds(raw: &str) -> Option<u64> {
let raw = raw.trim();
if raw.is_empty() {
@@ -121,3 +168,20 @@ fn parse_duration_seconds(raw: &str) -> Option<u64> {
number.checked_mul(multiplier)
}
fn parse_bool(raw: &str) -> Option<bool> {
match raw.trim().to_ascii_lowercase().as_str() {
"1" | "true" | "yes" | "on" => Some(true),
"0" | "false" | "no" | "off" => Some(false),
_ => None,
}
}
fn parse_positive_u32(raw: &str) -> Option<u32> {
let value = raw.trim().parse::<u32>().ok()?;
if value == 0 {
return None;
}
Some(value)
}