1
0
mirror of https://github.com/actix/examples synced 2024-12-02 18:02:22 +01:00
examples/auth/simple-auth-server/src/main.rs

81 lines
2.7 KiB
Rust
Raw Normal View History

#[macro_use]
extern crate diesel;
2022-10-26 17:51:27 +02:00
use actix_identity::IdentityMiddleware;
use actix_session::{config::PersistentSession, storage::CookieSessionStore, SessionMiddleware};
use actix_web::{cookie::Key, middleware, web, App, HttpServer};
2022-08-28 19:39:28 +02:00
use diesel::{
prelude::*,
r2d2::{self, ConnectionManager},
};
2020-09-12 17:49:45 +02:00
use time::Duration;
2019-03-29 21:43:03 +01:00
mod auth_handler;
2019-03-10 03:03:09 +01:00
mod email_service;
mod errors;
mod invitation_handler;
2019-03-10 03:03:09 +01:00
mod models;
mod register_handler;
2019-03-10 03:03:09 +01:00
mod schema;
mod utils;
2020-09-12 17:49:45 +02:00
#[actix_web::main]
2019-12-07 18:59:24 +01:00
async fn main() -> std::io::Result<()> {
dotenv::dotenv().ok();
2019-03-29 21:43:03 +01:00
std::env::set_var(
"RUST_LOG",
"simple-auth-server=debug,actix_web=info,actix_server=info",
);
env_logger::init();
2019-03-29 21:43:03 +01:00
let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
// create db connection pool
let manager = ConnectionManager::<PgConnection>::new(database_url);
let pool: models::Pool = r2d2::Pool::builder()
.build(manager)
.expect("Failed to create pool.");
2022-02-18 03:44:02 +01:00
let domain: String = std::env::var("DOMAIN").unwrap_or_else(|_| "localhost".to_string());
// Start http server
2019-03-29 21:43:03 +01:00
HttpServer::new(move || {
App::new()
.app_data(web::Data::new(pool.clone()))
2022-10-26 17:51:27 +02:00
.wrap(IdentityMiddleware::default())
.wrap(
SessionMiddleware::builder(
CookieSessionStore::default(),
Key::from(utils::SECRET_KEY.as_bytes()),
)
.session_lifecycle(PersistentSession::default().session_ttl(Duration::days(1)))
.cookie_name("auth-example".to_owned())
.cookie_secure(false)
.cookie_domain(Some(domain.clone()))
.cookie_path("/".to_owned())
.build(),
)
// enable logger
.wrap(middleware::Logger::default())
2019-03-29 21:43:03 +01:00
// everything under '/api/' route
.service(
web::scope("/api")
.service(
2019-12-07 18:59:24 +01:00
web::resource("/invitation")
.route(web::post().to(invitation_handler::post_invitation)),
)
.service(
web::resource("/register/{invitation_id}")
.route(web::post().to(register_handler::register_user)),
2019-03-29 21:43:03 +01:00
)
.service(
web::resource("/auth")
2019-12-07 18:59:24 +01:00
.route(web::post().to(auth_handler::login))
.route(web::delete().to(auth_handler::logout))
.route(web::get().to(auth_handler::get_me)),
2019-03-29 21:43:03 +01:00
),
)
})
2022-03-06 01:41:32 +01:00
.bind(("127.0.0.1", 8080))?
2019-12-25 17:48:33 +01:00
.run()
2019-12-07 18:59:24 +01:00
.await
}