api: Add a CORS fairing

Signed-off-by: ATechnoHazard <amolele@gmail.com>
This commit is contained in:
Amogh Lele 2020-06-26 16:52:00 +05:30
parent 62df3f239a
commit 3f5f052a7f
No known key found for this signature in database
GPG Key ID: F475143EDEDEBA3C
4 changed files with 33 additions and 1 deletions

29
src/api/fairings/cors.rs Normal file
View File

@ -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(""));
}
}
}

1
src/api/fairings/mod.rs Normal file
View File

@ -0,0 +1 @@
pub mod cors;

View File

@ -1,5 +1,6 @@
pub mod catchers; pub mod catchers;
pub mod routes; pub mod routes;
pub mod fairings;
mod guards; mod guards;
mod misc; mod misc;

View File

@ -1,4 +1,5 @@
use rocket::Rocket; use rocket::Rocket;
use crate::api::fairings::cors::CORS;
pub mod health; pub mod health;
pub mod paste; pub mod paste;
@ -8,5 +9,5 @@ pub fn fuel(rocket: Rocket) -> Rocket {
let mut rocket = rocket; let mut rocket = rocket;
rocket = health::fuel(rocket); rocket = health::fuel(rocket);
rocket = paste::fuel(rocket); rocket = paste::fuel(rocket);
rocket rocket.attach(CORS())
} }