1
0
mirror of https://github.com/actix/examples synced 2024-12-03 18:22:14 +01:00
examples/auth/cookie-session/src/main.rs

60 lines
1.8 KiB
Rust
Raw Normal View History

2018-05-03 00:11:57 +02:00
//! Example of cookie based session
//! Session data is stored in cookie, it is limited to 4kb
//!
//! [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> {
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")? {
log::info!("SESSION value: {count}");
2018-05-03 00:11:57 +02:00
counter = count + 1;
session.insert("counter", counter)?;
2018-05-03 00:11:57 +02:00
} else {
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<()> {
std::env::set_var("RUST_LOG", "info");
2018-05-03 00:11:57 +02:00
env_logger::init();
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
.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)),
)
.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
}