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

74 lines
2.5 KiB
Rust
Raw Normal View History

#[macro_use]
extern crate diesel;
2019-06-17 08:48:03 +02:00
use actix_identity::{CookieIdentityPolicy, IdentityService};
use actix_web::{middleware, web, App, HttpServer};
use diesel::prelude::*;
use diesel::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()))
// enable logger
.wrap(middleware::Logger::default())
2019-03-29 21:43:03 +01:00
.wrap(IdentityService::new(
CookieIdentityPolicy::new(utils::SECRET_KEY.as_bytes())
2019-03-29 21:43:03 +01:00
.name("auth")
.path("/")
.domain(domain.as_str())
.max_age(Duration::days(1))
2019-03-29 21:43:03 +01:00
.secure(false), // this can only be true if you have https
))
.app_data(web::JsonConfig::default().limit(4096))
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
),
)
})
.bind("127.0.0.1:3000")?
2019-12-25 17:48:33 +01:00
.run()
2019-12-07 18:59:24 +01:00
.await
}