diff --git a/Cargo.lock b/Cargo.lock index 7e9e20f..debef3f 100644 Binary files a/Cargo.lock and b/Cargo.lock differ diff --git a/emgauwa-core.toml b/emgauwa-core.toml index b103fba..4caa781 100644 --- a/emgauwa-core.toml +++ b/emgauwa-core.toml @@ -1,6 +1,9 @@ port = 4419 host = "127.0.0.1" +# Leave empty to allow all origins (will always respond with Origin and not "*") +#origins = ["http://localhost", "https://emgauwa.app"] + database = "sqlite://emgauwa-core.sqlite" [logging] diff --git a/emgauwa-core/Cargo.toml b/emgauwa-core/Cargo.toml index 074a0cb..c48d1b1 100644 --- a/emgauwa-core/Cargo.toml +++ b/emgauwa-core/Cargo.toml @@ -10,6 +10,7 @@ emgauwa-lib = { path = "../emgauwa-lib" } actix = "0.13" actix-web = "4.4" actix-web-actors = "4.2" +actix-cors = "0.6" simple_logger = "4.2" log = "0.4" diff --git a/emgauwa-core/src/main.rs b/emgauwa-core/src/main.rs index f0a6864..4efb3e8 100644 --- a/emgauwa-core/src/main.rs +++ b/emgauwa-core/src/main.rs @@ -1,4 +1,5 @@ use std::str::FromStr; +use actix_cors::Cors; use actix_web::middleware::TrailingSlash; use actix_web::{middleware, web, App, HttpServer}; @@ -12,7 +13,7 @@ mod settings; async fn main() -> std::io::Result<()> { let settings = settings::init(); - let log_level: LevelFilter = log::LevelFilter::from_str(&settings.logging.level) + let log_level: LevelFilter = LevelFilter::from_str(&settings.logging.level) .unwrap_or_else(|_| panic!("Error parsing log level.")); trace!("Log level set to {:?}", log_level); @@ -25,13 +26,22 @@ async fn main() -> std::io::Result<()> { log::info!("Starting server on {}:{}", settings.host, settings.port); HttpServer::new(move || { + + let cors = Cors::default() + .allow_any_method() + .allow_any_header() + .max_age(3600); + + let origins = settings.origins.clone(); + let cors = match settings.origins.is_empty() { + true => cors.allow_any_origin(), + false => cors.allowed_origin_fn(move |origin, _req_head| { + origins.contains(&origin.to_str().unwrap_or_default().to_string()) + }), + }; + App::new() - .wrap( - middleware::DefaultHeaders::new() - .add(("Access-Control-Allow-Origin", "*")) - .add(("Access-Control-Allow-Headers", "*")) - .add(("Access-Control-Allow-Methods", "*")), - ) + .wrap(cors) .wrap(middleware::Logger::default()) .wrap(middleware::NormalizePath::new(TrailingSlash::Trim)) .app_data(web::JsonConfig::default().error_handler(handlers::json_error_handler)) diff --git a/emgauwa-core/src/settings.rs b/emgauwa-core/src/settings.rs index 158909c..388d1d9 100644 --- a/emgauwa-core/src/settings.rs +++ b/emgauwa-core/src/settings.rs @@ -16,6 +16,7 @@ pub struct Settings { pub database: String, pub port: u16, pub host: String, + pub origins: Vec, pub logging: Logging, } @@ -25,6 +26,7 @@ impl Default for Settings { database: String::from("sqlite://emgauwa-core.sqlite"), port: constants::DEFAULT_PORT, host: String::from("127.0.0.1"), + origins: Vec::new(), logging: Logging::default(), } }