Add better cors for core

This commit is contained in:
Tobias Reisinger 2023-11-24 01:10:33 +01:00
parent 32c75ad73a
commit 9f64075f5a
Signed by: serguzim
GPG key ID: 13AD60C237A28DFE
5 changed files with 23 additions and 7 deletions

BIN
Cargo.lock generated

Binary file not shown.

View file

@ -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]

View file

@ -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"

View file

@ -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))

View file

@ -16,6 +16,7 @@ pub struct Settings {
pub database: String,
pub port: u16,
pub host: String,
pub origins: Vec<String>,
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(),
}
}