1pub use tower_sessions::{Session, SessionManagerLayer, MemoryStore};
4pub use tower_sessions::cookie::SameSite;
5
6use crate::config::SessionConfig;
7
8pub fn build_layer(config: &SessionConfig) -> SessionManagerLayer<MemoryStore> {
9 let store = MemoryStore::default();
10 SessionManagerLayer::new(store)
11 .with_name(config.cookie_name.clone())
12 .with_secure(config.secure)
13 .with_same_site(match config.same_site.as_str() {
14 "strict" => SameSite::Strict,
15 "none" => SameSite::None,
16 _ => SameSite::Lax,
17 })
18 .with_expiry(tower_sessions::Expiry::OnInactivity(
19 tower_sessions::cookie::time::Duration::seconds(config.lifetime_minutes * 60),
20 ))
21}
22
23pub const FLASH_KEY: &str = "_flash";
24pub const ERRORS_KEY: &str = "_errors";
25
26pub async fn flash(session: &Session, key: &str, value: serde_json::Value) -> Result<(), crate::Error> {
28 let mut flashes: std::collections::HashMap<String, serde_json::Value> = session
29 .get(FLASH_KEY)
30 .await
31 .map_err(|e| crate::Error::Internal(e.to_string()))?
32 .unwrap_or_default();
33 flashes.insert(key.to_string(), value);
34 session
35 .insert(FLASH_KEY, flashes)
36 .await
37 .map_err(|e| crate::Error::Internal(e.to_string()))?;
38 Ok(())
39}
40
41pub async fn take_flash(session: &Session, key: &str) -> Result<Option<serde_json::Value>, crate::Error> {
42 let mut flashes: std::collections::HashMap<String, serde_json::Value> = session
43 .get(FLASH_KEY)
44 .await
45 .map_err(|e| crate::Error::Internal(e.to_string()))?
46 .unwrap_or_default();
47 let value = flashes.remove(key);
48 session
49 .insert(FLASH_KEY, flashes)
50 .await
51 .map_err(|e| crate::Error::Internal(e.to_string()))?;
52 Ok(value)
53}