1
0
mirror of https://github.com/actix/examples synced 2024-11-30 17:14:35 +01:00
examples/auth/cookie-auth/src/main.rs

76 lines
2.6 KiB
Rust
Raw Normal View History

2022-10-26 17:51:27 +02:00
use actix_identity::{Identity, IdentityMiddleware};
2023-01-03 15:04:10 +01:00
use actix_session::{config::PersistentSession, storage::CookieSessionStore, SessionMiddleware};
2022-10-26 17:51:27 +02:00
use actix_web::{
2023-01-03 15:04:10 +01:00
cookie::{time::Duration, Key},
error,
http::StatusCode,
middleware, web, App, HttpMessage as _, HttpRequest, HttpServer, Responder,
2022-10-26 17:51:27 +02:00
};
2023-01-03 15:04:10 +01:00
const ONE_MINUTE: Duration = Duration::minutes(1);
async fn index(identity: Option<Identity>) -> actix_web::Result<impl Responder> {
let id = match identity.map(|id| id.id()) {
None => "anonymous".to_owned(),
Some(Ok(id)) => id,
Some(Err(err)) => return Err(error::ErrorInternalServerError(err)),
};
Ok(format!("Hello {id}"))
2018-04-19 01:46:35 +02:00
}
2023-01-03 15:04:10 +01:00
async fn login(req: HttpRequest) -> impl Responder {
2022-10-26 17:51:27 +02:00
Identity::login(&req.extensions(), "user1".to_owned()).unwrap();
2023-03-14 03:40:02 +01:00
web::Redirect::to("/").using_status_code(StatusCode::FOUND)
2018-04-19 01:46:35 +02:00
}
2023-01-03 15:04:10 +01:00
async fn logout(id: Identity) -> impl Responder {
2022-10-26 17:51:27 +02:00
id.logout();
2023-03-14 03:40:02 +01:00
web::Redirect::to("/").using_status_code(StatusCode::FOUND)
2018-04-19 01:46:35 +02:00
}
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<()> {
2023-01-03 15:04:10 +01:00
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
2018-04-19 01:46:35 +02:00
// Generate a random secret key. Note that it is important to use a unique
// secret key for every project. Anyone with access to the key can generate
// authentication cookies for any user!
2023-01-03 15:04:10 +01:00
//
// If the secret key is read from a file or the environment, make sure it is generated securely.
// For example, a secure random key (in base64 format) can be generated with the OpenSSL CLI:
// ```
// openssl rand -base64 64
// ```
//
// Then decoded and used converted to a Key:
// ```
// let secret_key = Key::from(base64::decode(&private_key_base64).unwrap());
// ```
let secret_key = Key::generate();
2022-10-26 17:51:27 +02:00
2023-01-03 15:04:10 +01:00
log::info!("starting HTTP server at http://localhost:8080");
HttpServer::new(move || {
2018-05-08 20:08:43 +02:00
App::new()
2023-01-03 15:04:10 +01:00
.service(web::resource("/login").route(web::post().to(login)))
.service(web::resource("/logout").route(web::post().to(logout)))
.service(web::resource("/").route(web::get().to(index)))
2022-10-26 17:51:27 +02:00
.wrap(IdentityMiddleware::default())
.wrap(
SessionMiddleware::builder(CookieSessionStore::default(), secret_key.clone())
2022-10-26 17:51:27 +02:00
.cookie_name("auth-example".to_owned())
.cookie_secure(false)
2023-01-03 15:04:10 +01:00
.session_lifecycle(PersistentSession::default().session_ttl(ONE_MINUTE))
2022-10-26 17:51:27 +02:00
.build(),
)
2023-01-03 15:04:10 +01:00
.wrap(middleware::NormalizePath::trim())
.wrap(middleware::Logger::default())
2019-03-10 03:03:09 +01:00
})
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-04-19 01:46:35 +02:00
}