api: Add a CORS fairing
Signed-off-by: ATechnoHazard <amolele@gmail.com>
This commit is contained in:
4 files changed
+33
-1
No files matched your search
@@ -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(""));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
pub mod cors;
|
||||
@@ -1,5 +1,6 @@
|
||||
pub mod catchers;
|
||||
pub mod routes;
|
||||
pub mod fairings;
|
||||
|
||||
mod guards;
|
||||
mod misc;
|
||||
@@ -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())
|
||||
}
|
||||
Reference in new issue
Block a user