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

49 lines
1.6 KiB
Rust
Raw Normal View History

2019-06-17 08:48:03 +02:00
use actix_identity::Identity;
use actix_identity::{CookieIdentityPolicy, IdentityService};
2019-03-10 06:08:08 +01:00
use actix_web::{middleware, web, App, HttpResponse, HttpServer};
use rand::Rng;
2018-04-19 01:46:35 +02:00
2019-12-07 18:59:24 +01:00
async fn index(id: Identity) -> String {
2019-09-04 17:04:57 +02:00
format!(
"Hello {}",
id.identity().unwrap_or_else(|| "Anonymous".to_owned())
)
2018-04-19 01:46:35 +02:00
}
2019-12-07 18:59:24 +01:00
async fn login(id: Identity) -> HttpResponse {
2019-03-10 06:08:08 +01:00
id.remember("user1".to_owned());
2018-05-08 20:08:43 +02:00
HttpResponse::Found().header("location", "/").finish()
2018-04-19 01:46:35 +02:00
}
2019-12-07 18:59:24 +01:00
async fn logout(id: Identity) -> HttpResponse {
2019-03-10 06:08:08 +01:00
id.forget();
2018-05-08 20:08:43 +02:00
HttpResponse::Found().header("location", "/").finish()
2018-04-19 01:46:35 +02:00
}
2019-12-07 18:59:24 +01:00
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
2019-03-10 06:08:08 +01:00
std::env::set_var("RUST_LOG", "actix_web=info");
2018-04-19 01:46:35 +02:00
env_logger::init();
// Generate a random 32 byte key. Note that it is important to use a unique
// private key for every project. Anyone with access to the key can generate
// authentication cookies for any user!
let private_key = rand::thread_rng().gen::<[u8; 32]>();
HttpServer::new(move || {
2018-05-08 20:08:43 +02:00
App::new()
2019-03-26 04:29:00 +01:00
.wrap(IdentityService::new(
CookieIdentityPolicy::new(&private_key)
2018-04-19 01:46:35 +02:00
.name("auth-example")
2018-05-08 20:08:43 +02:00
.secure(false),
))
2019-07-11 11:02:25 +02:00
// enable logger - always register actix-web Logger middleware last
.wrap(middleware::Logger::default())
2019-03-10 06:08:08 +01:00
.service(web::resource("/login").route(web::post().to(login)))
.service(web::resource("/logout").to(logout))
.service(web::resource("/").route(web::get().to(index)))
2019-03-10 03:03:09 +01:00
})
2019-03-10 06:08:08 +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
}