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

47 lines
1.3 KiB
Rust
Raw Normal View History

2018-04-19 01:46:35 +02:00
extern crate actix;
extern crate actix_web;
extern crate env_logger;
2018-07-21 11:03:02 +02:00
use actix_web::middleware::identity::RequestIdentity;
use actix_web::middleware::identity::{CookieIdentityPolicy, IdentityService};
2019-03-10 03:03:09 +01:00
use actix_web::{middleware, server, App, HttpRequest, HttpResponse};
2018-04-19 01:46:35 +02:00
2018-07-16 08:36:53 +02:00
fn index(req: &HttpRequest) -> String {
format!("Hello {}", req.identity().unwrap_or("Anonymous".to_owned()))
2018-04-19 01:46:35 +02:00
}
2018-07-16 08:36:53 +02:00
fn login(req: &HttpRequest) -> HttpResponse {
2018-04-19 01:46:35 +02:00
req.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
}
2018-07-16 08:36:53 +02:00
fn logout(req: &HttpRequest) -> HttpResponse {
2018-04-19 01:46:35 +02:00
req.forget();
2018-05-08 20:08:43 +02:00
HttpResponse::Found().header("location", "/").finish()
2018-04-19 01:46:35 +02:00
}
fn main() {
::std::env::set_var("RUST_LOG", "actix_web=info");
env_logger::init();
let sys = actix::System::new("cookie-auth");
2018-05-08 20:08:43 +02:00
server::new(|| {
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),
))
2018-04-19 01:46:35 +02:00
.resource("/login", |r| r.f(login))
.resource("/logout", |r| r.f(logout))
2018-05-08 20:08:43 +02:00
.resource("/", |r| r.f(index))
2019-03-10 03:03:09 +01:00
})
.bind("127.0.0.1:8080")
.unwrap()
.start();
2018-04-19 01:46:35 +02:00
println!("Started http server: 127.0.0.1:8080");
let _ = sys.run();
}