From 96e2f42cfe13e432eca4a802026a335e769a27f9 Mon Sep 17 00:00:00 2001 From: Ruidy Date: Wed, 30 Dec 2020 16:23:33 +0100 Subject: [PATCH] cors --- .env | 3 ++- .env.example | 3 ++- Cargo.lock | 15 +++++++++++++++ Cargo.toml | 1 + src/main.rs | 16 ++++++++++++++++ 5 files changed, 36 insertions(+), 2 deletions(-) diff --git a/.env b/.env index 0f4dc0e..98062d5 100644 --- a/.env +++ b/.env @@ -1 +1,2 @@ -BASE_URL=127.0.0.1:8000 \ No newline at end of file +BASE_URL=127.0.0.1:8000 +CLIENT_URL=http://localhost:63342 \ No newline at end of file diff --git a/.env.example b/.env.example index 0f4dc0e..9954e2d 100644 --- a/.env.example +++ b/.env.example @@ -1 +1,2 @@ -BASE_URL=127.0.0.1:8000 \ No newline at end of file +BASE_URL=127.0.0.1:8000 +CLIENT_URL=localhost:63342 \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock index cb7bb48..89c46fe 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -35,6 +35,20 @@ dependencies = [ "trust-dns-resolver", ] +[[package]] +name = "actix-cors" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f3a3d5493dbc9b8769fe88c030d057ef8d2edc5728e5e26267780e8fc5db0be" +dependencies = [ + "actix-web", + "derive_more", + "futures-util", + "log", + "once_cell", + "tinyvec", +] + [[package]] name = "actix-http" version = "2.2.0" @@ -1762,6 +1776,7 @@ checksum = "7e7811dd7f9398f14cc76efd356f98f03aa30419dea46aa810d71e819fc97158" name = "web" version = "0.1.0" dependencies = [ + "actix-cors", "actix-web", "dotenv", "env_logger", diff --git a/Cargo.toml b/Cargo.toml index 266f62a..326bd2a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,6 +7,7 @@ edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +actix-cors = "0.5.3" actix-web = "3" dotenv = "0.15.0" env_logger = "0.8.2" diff --git a/src/main.rs b/src/main.rs index 3e8420a..885563c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,8 @@ use std::env; use std::sync::Mutex; +use actix_cors::Cors; +use actix_web::http::header::{AUTHORIZATION, CONTENT_TYPE}; use actix_web::{middleware, web, App, HttpServer}; use env_logger::Env; @@ -13,6 +15,7 @@ async fn main() -> std::io::Result<()> { dotenv::dotenv().ok(); let addr = env::var("BASE_URL").unwrap(); + let client_addr = env::var("CLIENT_URL").ok(); let tasks = web::Data::new(task::TaskList { tasks: Mutex::new(vec![ @@ -30,8 +33,21 @@ async fn main() -> std::io::Result<()> { }); HttpServer::new(move || { + let cors = match &client_addr { + Some(ref origin) => Cors::default() + .allowed_origin(origin) + .allowed_methods(vec!["GET", "POST"]) + .allowed_headers(vec![AUTHORIZATION, CONTENT_TYPE]) + .max_age(3600), + None => Cors::default() + .allowed_origin("*") + .allowed_methods(vec!["GET", "POST"]) + .allowed_headers(vec![AUTHORIZATION, CONTENT_TYPE]) + .max_age(3600), + }; App::new() .wrap(middleware::Logger::default()) + .wrap(cors) .app_data(tasks.clone()) .configure(task::init) })