use std::time::Duration;
#[derive(Clone, Debug)]
pub struct SessionConfig {
pub idle_lifetime: Duration,
pub absolute_lifetime: Duration,
pub cookie_name: String,
pub cookie_path: String,
pub cookie_secure: bool,
pub cookie_http_only: bool,
pub cookie_same_site: String,
pub table_name: String,
}
impl Default for SessionConfig {
fn default() -> Self {
Self {
idle_lifetime: Duration::from_secs(120 * 60), absolute_lifetime: Duration::from_secs(43200 * 60), cookie_name: "ferro_session".to_string(),
cookie_path: "/".to_string(),
cookie_secure: true,
cookie_http_only: true,
cookie_same_site: "Lax".to_string(),
table_name: "sessions".to_string(),
}
}
}
impl SessionConfig {
pub fn new() -> Self {
Self::default()
}
pub fn from_env() -> Self {
let idle_lifetime_minutes: u64 = crate::env_optional("SESSION_LIFETIME")
.and_then(|s: String| s.parse().ok())
.unwrap_or(120);
let absolute_lifetime_minutes: u64 = crate::env_optional("SESSION_ABSOLUTE_LIFETIME")
.and_then(|s: String| s.parse().ok())
.unwrap_or(43200);
let cookie_secure = crate::env_optional("SESSION_SECURE")
.map(|s: String| s.to_lowercase() == "true" || s == "1")
.unwrap_or(true);
Self {
idle_lifetime: Duration::from_secs(idle_lifetime_minutes * 60),
absolute_lifetime: Duration::from_secs(absolute_lifetime_minutes * 60),
cookie_name: crate::env_optional("SESSION_COOKIE")
.unwrap_or_else(|| "ferro_session".to_string()),
cookie_path: crate::env_optional("SESSION_PATH").unwrap_or_else(|| "/".to_string()),
cookie_secure,
cookie_http_only: true, cookie_same_site: crate::env_optional("SESSION_SAME_SITE")
.unwrap_or_else(|| "Lax".to_string()),
table_name: "sessions".to_string(),
}
}
pub fn idle_lifetime(mut self, duration: Duration) -> Self {
self.idle_lifetime = duration;
self
}
pub fn absolute_lifetime(mut self, duration: Duration) -> Self {
self.absolute_lifetime = duration;
self
}
pub fn cookie_name(mut self, name: impl Into<String>) -> Self {
self.cookie_name = name.into();
self
}
pub fn secure(mut self, secure: bool) -> Self {
self.cookie_secure = secure;
self
}
}