async-sqlx-session icon indicating copy to clipboard operation
async-sqlx-session copied to clipboard

Persisting PostgresSessionStore between server restarts

Open abcd-ca opened this issue 1 year ago • 0 comments

Hi, I have an Axum server and was using MemoryStore. I just swapped that for PostgresSessionStore. I can see that between browser page reloads that my session is persisting but when I quit my server and restart it then reload the browser again, it seems the session is lost. I can see the async_sessions table in my db has been created.

Here is how I'm configuring it,

// session cookie ------ start
    let store = PostgresSessionStore::new(&db_url)
        .await
        .map_err(|e| {
            eprintln!("Database error: {:?}", e);
            RestAPIError::InternalServerError
        })
        .unwrap();
    store.migrate().await.unwrap();
    store.spawn_cleanup_task(Duration::from_secs(60 * 60));
    
    // I couldn't see how three lines from the async-sqlx-sesssion example were needed with Axum. 
    // let mut session = Session::new();
    // let cookie_value = store.store_session(session).await.unwrap().unwrap();
    // let session = store.load_session(cookie_value).await.unwrap();

    let secret = random::<[u8; 128]>();
    let session_layer = SessionLayer::new(store, &secret)
        .with_secure(true)
        .with_same_site_policy(SameSite::Strict);
    // session cookie ------ end
    
    ...
    
    let routes_all = Router::new()
        ...
        .layer(session_layer)
        .layer(Extension(app_state))
        .fallback_service(routes_static());

In my login route I just update the session like this:

async fn api_login(
    mut session: WritableSession,
    Extension(app_state): Extension<Arc<AppState>>,
    payload: Json<LoginRequestPostPayload>,
) -> RestAPIResult<Json<StandardSuccessResponseData>> {
          
           ...

           session
                .insert("token", payload.token.to_string())
                .map_err(|_| RestAPIError::UpdateSessionFail)?;

            Ok(Json(StandardSuccessResponseData::new()))
}

Would you please help me identify the gap?

abcd-ca avatar Oct 11 '23 14:10 abcd-ca