|
extern crate actix; |
|
extern crate actix_web; |
|
extern crate env_logger; |
|
extern crate futures; |
|
extern crate serde; |
|
#[macro_use] |
|
extern crate serde_derive; |
|
|
|
use actix_web::middleware::identity::RequestIdentity; |
|
use actix_web::middleware::identity::{CookieIdentityPolicy, IdentityService}; |
|
use actix_web::{middleware, server, App, FutureResponse, HttpMessage, HttpRequest, HttpResponse}; |
|
use futures::Future; |
|
|
|
fn index(req: &HttpRequest) -> HttpResponse { |
|
let html = match req.identity() { |
|
Some(name) => format!( |
|
r#"Hello {}<br> |
|
<form action="/logout" method="POST"> |
|
<input type="submit" value="Logout"/> |
|
</form>"#, |
|
name |
|
), |
|
None => r#"<form action="/login" method="POST"> |
|
User Name: <input name="name" type="text"/> <br> |
|
Password: <input name="password" type="text"/> <br> |
|
<input type="submit" value="Login"/> |
|
</form>"# |
|
.to_string(), |
|
}; |
|
HttpResponse::Ok().content_type("text/html").body(html) |
|
} |
|
|
|
#[derive(Deserialize)] |
|
struct LoginParameters { |
|
name: String, |
|
password: String, |
|
} |
|
|
|
fn login(req: &HttpRequest) -> FutureResponse<HttpResponse> { |
|
// https://actix.rs/api/actix-web/stable/actix_web/trait.HttpMessage.html#method.urlencoded |
|
Box::new( |
|
req.urlencoded::<LoginParameters>() |
|
.from_err() |
|
.and_then(move |params| { |
|
// Checks the password here, always successes in this example |
|
req.remember(params.name); |
|
Ok(HttpResponse::Found().header("location", "/").finish()) |
|
}), |
|
) |
|
} |
|
|
|
fn logout(req: &HttpRequest) -> HttpResponse { |
|
req.forget(); |
|
HttpResponse::Found().header("location", "/").finish() |
|
} |
|
|
|
fn main() { |
|
::std::env::set_var("RUST_LOG", "actix_web=info"); |
|
env_logger::init(); |
|
let sys = actix::System::new("cookie-auth"); |
|
|
|
server::new(|| { |
|
App::new() |
|
.middleware(middleware::Logger::default()) |
|
.middleware(IdentityService::new( |
|
CookieIdentityPolicy::new(&[0; 32]) |
|
.name("auth-example") |
|
.secure(false), |
|
)).resource("/", |r| r.f(index)) |
|
.resource("/login", |r| r.post().f(login)) |
|
.resource("/logout", |r| r.post().f(logout)) |
|
}).bind("127.0.0.1:8080") |
|
.unwrap() |
|
.start(); |
|
|
|
println!("Started http server: 127.0.0.1:8080"); |
|
let _ = sys.run(); |
|
} |