2022-10-26 16:51:27 +01:00
|
|
|
use actix_identity::{Identity, IdentityMiddleware};
|
|
|
|
use actix_session::{storage::CookieSessionStore, SessionMiddleware};
|
|
|
|
use actix_web::{
|
|
|
|
cookie::Key, middleware, web, App, HttpMessage as _, HttpRequest, HttpResponse, HttpServer,
|
|
|
|
};
|
2019-12-07 23:59:24 +06:00
|
|
|
async fn index(id: Identity) -> String {
|
2019-09-05 00:04:57 +09:00
|
|
|
format!(
|
|
|
|
"Hello {}",
|
2022-10-26 16:51:27 +01:00
|
|
|
id.id().unwrap_or_else(|_| "Anonymous".to_owned())
|
2019-09-05 00:04:57 +09:00
|
|
|
)
|
2018-04-18 16:46:35 -07:00
|
|
|
}
|
|
|
|
|
2022-10-26 16:51:27 +01:00
|
|
|
async fn login(req: HttpRequest) -> HttpResponse {
|
|
|
|
Identity::login(&req.extensions(), "user1".to_owned()).unwrap();
|
|
|
|
|
2022-02-02 15:21:09 +00:00
|
|
|
HttpResponse::Found()
|
|
|
|
.insert_header(("location", "/"))
|
|
|
|
.finish()
|
2018-04-18 16:46:35 -07:00
|
|
|
}
|
|
|
|
|
2019-12-07 23:59:24 +06:00
|
|
|
async fn logout(id: Identity) -> HttpResponse {
|
2022-10-26 16:51:27 +01:00
|
|
|
id.logout();
|
|
|
|
|
2022-02-02 15:21:09 +00:00
|
|
|
HttpResponse::Found()
|
|
|
|
.insert_header(("location", "/"))
|
|
|
|
.finish()
|
2018-04-18 16:46:35 -07:00
|
|
|
}
|
|
|
|
|
2020-09-12 16:49:45 +01:00
|
|
|
#[actix_web::main]
|
2019-12-07 23:59:24 +06:00
|
|
|
async fn main() -> std::io::Result<()> {
|
2019-03-09 21:08:08 -08:00
|
|
|
std::env::set_var("RUST_LOG", "actix_web=info");
|
2018-04-18 16:46:35 -07:00
|
|
|
env_logger::init();
|
|
|
|
|
2022-11-15 02:02:36 -06:00
|
|
|
// Generate a random secret key. Note that it is important to use a unique
|
|
|
|
// secret key for every project. Anyone with access to the key can generate
|
2020-04-13 12:36:49 +03:00
|
|
|
// authentication cookies for any user!
|
2022-11-15 02:02:36 -06:00
|
|
|
let secret_key = Key::generate();
|
2022-10-26 16:51:27 +01:00
|
|
|
|
2020-04-13 12:36:49 +03:00
|
|
|
HttpServer::new(move || {
|
2018-05-08 11:08:43 -07:00
|
|
|
App::new()
|
2022-10-26 16:51:27 +01:00
|
|
|
.wrap(IdentityMiddleware::default())
|
|
|
|
.wrap(
|
2022-11-23 18:31:10 -03:00
|
|
|
SessionMiddleware::builder(CookieSessionStore::default(), secret_key.clone())
|
2022-10-26 16:51:27 +01:00
|
|
|
.cookie_name("auth-example".to_owned())
|
|
|
|
.cookie_secure(false)
|
|
|
|
.build(),
|
|
|
|
)
|
2022-02-06 08:13:24 +00:00
|
|
|
// enable logger - always register Actix Web Logger middleware last
|
2019-06-01 09:24:54 -04:00
|
|
|
.wrap(middleware::Logger::default())
|
2019-03-09 21:08:08 -08: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-09 18:03:09 -08:00
|
|
|
})
|
2022-02-17 20:22:36 +00:00
|
|
|
.bind(("127.0.0.1", 8080))?
|
2019-12-25 20:48:33 +04:00
|
|
|
.run()
|
2019-12-07 23:59:24 +06:00
|
|
|
.await
|
2018-04-18 16:46:35 -07:00
|
|
|
}
|