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};
|
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();
|
|
|
|
|
2019-03-10 06:08:08 +01:00
|
|
|
HttpServer::new(|| {
|
2018-05-08 20:08:43 +02:00
|
|
|
App::new()
|
2019-03-26 04:29:00 +01:00
|
|
|
.wrap(IdentityService::new(
|
2018-04-19 01:46:35 +02:00
|
|
|
CookieIdentityPolicy::new(&[0; 32])
|
|
|
|
.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
|
2019-06-01 15:24:54 +02:00
|
|
|
.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-07 18:59:24 +01:00
|
|
|
.start()
|
|
|
|
.await
|
2018-04-19 01:46:35 +02:00
|
|
|
}
|