use std::time::Duration;
use topcoat_core::context::{Cx, app_context};
use crate::TokenStore;
pub struct SessionConfig {
pub(crate) token_store: Box<dyn TokenStore>,
pub(crate) lifetime: Duration,
#[cfg(feature = "router")]
pub(crate) verify_origin: bool,
#[cfg(feature = "router")]
pub(crate) trusted_origins: Vec<String>,
}
pub const DEFAULT_LIFETIME: Duration = Duration::from_hours(24 * 30);
impl SessionConfig {
#[must_use]
pub fn builder() -> SessionConfigBuilder {
SessionConfigBuilder::default()
}
}
#[cfg(feature = "cookie")]
impl Default for SessionConfig {
fn default() -> Self {
Self::builder().build()
}
}
pub struct SessionConfigBuilder {
token_store: Option<Box<dyn TokenStore>>,
lifetime: Duration,
#[cfg(feature = "router")]
verify_origin: bool,
#[cfg(feature = "router")]
trusted_origins: Vec<String>,
}
impl SessionConfigBuilder {
#[must_use]
pub fn token_store(mut self, token_store: impl TokenStore + 'static) -> Self {
self.token_store = Some(Box::new(token_store));
self
}
#[must_use]
pub fn lifetime(mut self, lifetime: Duration) -> Self {
self.lifetime = lifetime;
self
}
#[cfg(feature = "router")]
#[must_use]
pub fn trust_origin(mut self, origin: impl Into<String>) -> Self {
self.trusted_origins.push(origin.into());
self
}
#[cfg(feature = "router")]
#[must_use]
pub fn dangerous_disable_origin_verification(mut self) -> Self {
self.verify_origin = false;
self
}
#[must_use]
pub fn build(self) -> SessionConfig {
SessionConfig {
token_store: self.token_store.unwrap_or_else(default_token_store),
lifetime: self.lifetime,
#[cfg(feature = "router")]
verify_origin: self.verify_origin,
#[cfg(feature = "router")]
trusted_origins: self.trusted_origins,
}
}
}
impl Default for SessionConfigBuilder {
fn default() -> Self {
Self {
token_store: None,
lifetime: DEFAULT_LIFETIME,
#[cfg(feature = "router")]
verify_origin: true,
#[cfg(feature = "router")]
trusted_origins: Vec::new(),
}
}
}
#[cfg(feature = "cookie")]
fn default_token_store() -> Box<dyn TokenStore> {
Box::new(crate::cookie::CookieTokenStore::new())
}
#[cfg(not(feature = "cookie"))]
fn default_token_store() -> Box<dyn TokenStore> {
panic!(
"no token store configured: set one with `SessionConfigBuilder::token_store` or enable the `cookie` feature for the default cookie store"
)
}
pub(crate) fn config(cx: &Cx) -> &SessionConfig {
app_context(cx)
}