2018-05-02 15:11:57 -07:00
|
|
|
//! Example of cookie based session
|
|
|
|
//! Session data is stored in cookie, it is limited to 4kb
|
|
|
|
//!
|
2022-06-08 06:01:44 -04:00
|
|
|
//! [Redis session example](https://github.com/actix/examples/tree/HEAD/auth/redis-session)
|
2018-05-02 15:11:57 -07:00
|
|
|
//!
|
2019-07-11 10:47:41 +02:00
|
|
|
//! [User guide](https://actix.rs/docs/middleware/#user-sessions)
|
2018-05-02 15:11:57 -07:00
|
|
|
|
2022-08-28 18:39:28 +01:00
|
|
|
use actix_session::{
|
|
|
|
config::PersistentSession, storage::CookieSessionStore, Session, SessionMiddleware,
|
|
|
|
};
|
|
|
|
use actix_web::{
|
|
|
|
cookie::{self, Key},
|
|
|
|
middleware::Logger,
|
|
|
|
web, App, HttpRequest, HttpServer, Result,
|
|
|
|
};
|
2018-05-02 15:11:57 -07:00
|
|
|
|
|
|
|
/// simple index handler with session
|
2019-12-07 23:59:24 +06:00
|
|
|
async fn index(session: Session, req: HttpRequest) -> Result<&'static str> {
|
2022-06-07 22:53:38 -04:00
|
|
|
log::info!("{req:?}");
|
2018-05-02 15:11:57 -07:00
|
|
|
|
|
|
|
// RequestSession trait is used for session access
|
|
|
|
let mut counter = 1;
|
2019-03-09 18:03:09 -08:00
|
|
|
if let Some(count) = session.get::<i32>("counter")? {
|
2022-06-07 22:53:38 -04:00
|
|
|
log::info!("SESSION value: {count}");
|
2018-05-02 15:11:57 -07:00
|
|
|
counter = count + 1;
|
2022-02-02 15:22:50 +00:00
|
|
|
session.insert("counter", counter)?;
|
2018-05-02 15:11:57 -07:00
|
|
|
} else {
|
2022-02-02 15:22:50 +00:00
|
|
|
session.insert("counter", counter)?;
|
2018-05-02 15:11:57 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
Ok("welcome!")
|
|
|
|
}
|
|
|
|
|
2020-09-12 16:49:45 +01:00
|
|
|
#[actix_web::main]
|
2019-12-07 23:59:24 +06:00
|
|
|
async fn main() -> std::io::Result<()> {
|
2022-06-20 17:32:08 -05:00
|
|
|
std::env::set_var("RUST_LOG", "info");
|
2018-05-02 15:11:57 -07:00
|
|
|
env_logger::init();
|
2022-02-02 15:22:50 +00:00
|
|
|
log::info!("Starting http server: 127.0.0.1:8080");
|
2018-05-02 15:11:57 -07:00
|
|
|
|
2019-03-09 18:03:09 -08:00
|
|
|
HttpServer::new(|| {
|
2018-05-02 15:11:57 -07:00
|
|
|
App::new()
|
|
|
|
// enable logger
|
2019-03-26 04:29:00 +01:00
|
|
|
.wrap(Logger::default())
|
2018-05-02 15:11:57 -07:00
|
|
|
// cookie session middleware
|
2022-06-20 17:32:08 -05:00
|
|
|
.wrap(
|
|
|
|
SessionMiddleware::builder(CookieSessionStore::default(), Key::from(&[0; 64]))
|
|
|
|
.cookie_secure(false)
|
2022-08-28 18:39:28 +01:00
|
|
|
// customize session and cookie expiration
|
|
|
|
.session_lifecycle(
|
|
|
|
PersistentSession::default().session_ttl(cookie::time::Duration::hours(2)),
|
|
|
|
)
|
2022-06-20 17:32:08 -05:00
|
|
|
.build(),
|
|
|
|
)
|
2019-03-09 18:03:09 -08:00
|
|
|
.service(web::resource("/").to(index))
|
|
|
|
})
|
2022-02-17 20:22:36 +00:00
|
|
|
.bind(("127.0.0.1", 8080))?
|
2019-12-25 20:48:33 +04:00
|
|
|
.run()
|
2019-12-07 23:59:24 +06:00
|
|
|
.await
|
2018-05-02 15:11:57 -07:00
|
|
|
}
|