diff --git a/src/api/fairings/cors.rs b/src/api/fairings/cors.rs new file mode 100644 index 0000000..2bd70d2 --- /dev/null +++ b/src/api/fairings/cors.rs @@ -0,0 +1,29 @@ +use rocket::{Request, Response}; +use rocket::fairing::{Fairing, Info, Kind}; +use rocket::http::{Header, ContentType, Method}; +use std::io::Cursor; + +pub struct CORS(); + +impl Fairing for CORS { + fn info(&self) -> Info { + Info { + name: "Add CORS headers to requests", + kind: Kind::Response + } + } + + fn on_response(&self, request: &Request, response: &mut Response) { + if request.method() == Method::Options || response.content_type() == Some(ContentType::JSON) { + response.set_header(Header::new("Access-Control-Allow-Origin", "*")); + response.set_header(Header::new("Access-Control-Allow-Methods", "POST, GET, OPTIONS")); + response.set_header(Header::new("Access-Control-Allow-Headers", "Content-Type")); + response.set_header(Header::new("Access-Control-Allow-Credentials", "true")); + } + + if request.method() == Method::Options { + response.set_header(ContentType::Plain); + response.set_sized_body(Cursor::new("")); + } + } +} \ No newline at end of file diff --git a/src/api/fairings/mod.rs b/src/api/fairings/mod.rs new file mode 100644 index 0000000..23b2775 --- /dev/null +++ b/src/api/fairings/mod.rs @@ -0,0 +1 @@ +pub mod cors; \ No newline at end of file diff --git a/src/api/mod.rs b/src/api/mod.rs index a9fc3cc..0cd0eba 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -1,5 +1,6 @@ pub mod catchers; pub mod routes; +pub mod fairings; mod guards; mod misc; diff --git a/src/api/routes/mod.rs b/src/api/routes/mod.rs index 5708a83..0ca44e2 100644 --- a/src/api/routes/mod.rs +++ b/src/api/routes/mod.rs @@ -1,4 +1,5 @@ use rocket::Rocket; +use crate::api::fairings::cors::CORS; pub mod health; pub mod paste; @@ -8,5 +9,5 @@ pub fn fuel(rocket: Rocket) -> Rocket { let mut rocket = rocket; rocket = health::fuel(rocket); rocket = paste::fuel(rocket); - rocket + rocket.attach(CORS()) }