Skip to main content

sunday_slate/
sessions.rs

1use std::{str::FromStr, time::Duration};
2
3use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions, SqliteSynchronous};
4use tower_sessions::{
5    Expiry, SessionManagerLayer,
6    cookie::{SameSite, time::Duration as CookieDuration},
7};
8use tower_sessions_sqlx_store::SqliteStore;
9
10use crate::Config;
11
12pub type Layer = SessionManagerLayer<SqliteStore>;
13
14pub async fn layer(config: &Config) -> anyhow::Result<(Layer, SqliteStore)> {
15    build_layer(&config.session_database_url()).await
16}
17
18/// Build a session layer backed by an in-memory SQLite database, for tests.
19/// The pool below uses a single connection, so the in-memory database lives
20/// exactly as long as the returned `SqliteStore` (i.e. the whole test).
21pub async fn layer_in_memory() -> anyhow::Result<(Layer, SqliteStore)> {
22    build_layer("sqlite::memory:").await
23}
24
25async fn build_layer(database_url: &str) -> anyhow::Result<(Layer, SqliteStore)> {
26    let options = SqliteConnectOptions::from_str(database_url)?
27        .create_if_missing(true)
28        .journal_mode(SqliteJournalMode::Wal)
29        .synchronous(SqliteSynchronous::Normal)
30        .foreign_keys(true)
31        .busy_timeout(Duration::from_secs(10));
32
33    let pool = SqlitePoolOptions::new()
34        .max_connections(1)
35        .acquire_timeout(Duration::from_secs(30))
36        .connect_with(options)
37        .await?;
38
39    let store = SqliteStore::new(pool);
40    store.migrate().await?;
41
42    let session_layer = SessionManagerLayer::new(store.clone())
43        .with_secure(false)
44        .with_http_only(true)
45        .with_same_site(SameSite::Lax)
46        .with_expiry(Expiry::OnInactivity(CookieDuration::days(14)));
47
48    Ok((session_layer, store))
49}