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