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

38 lines
1.2 KiB
Rust
Raw Normal View History

2019-03-10 06:08:08 +01:00
use actix_web::middleware::identity::Identity;
2018-07-21 11:03:02 +02:00
use actix_web::middleware::identity::{CookieIdentityPolicy, IdentityService};
2019-03-10 06:08:08 +01:00
use actix_web::{middleware, web, App, HttpResponse, HttpServer};
2018-04-19 01:46:35 +02:00
2019-03-10 06:08:08 +01:00
fn index(id: Identity) -> String {
format!("Hello {}", id.identity().unwrap_or("Anonymous".to_owned()))
2018-04-19 01:46:35 +02:00
}
2019-03-10 06:08:08 +01:00
fn login(id: Identity) -> HttpResponse {
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-03-10 06:08:08 +01:00
fn logout(id: Identity) -> HttpResponse {
id.forget();
2018-05-08 20:08:43 +02:00
HttpResponse::Found().header("location", "/").finish()
2018-04-19 01:46:35 +02:00
}
2019-03-10 06:08:08 +01:00
fn main() -> std::io::Result<()> {
std::env::set_var("RUST_LOG", "actix_web=info");
2018-04-19 01:46:35 +02:00
env_logger::init();
2019-03-10 06:08:08 +01:00
HttpServer::new(|| {
2018-05-08 20:08:43 +02:00
App::new()
2018-04-19 01:46:35 +02:00
.middleware(middleware::Logger::default())
.middleware(IdentityService::new(
CookieIdentityPolicy::new(&[0; 32])
.name("auth-example")
2018-05-08 20:08:43 +02:00
.secure(false),
))
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")?
.run()
2018-04-19 01:46:35 +02:00
}