api: Add a CORS fairing
Signed-off-by: ATechnoHazard <amolele@gmail.com>
This commit is contained in:
parent
62df3f239a
commit
3f5f052a7f
29
src/api/fairings/cors.rs
Normal file
29
src/api/fairings/cors.rs
Normal 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
1
src/api/fairings/mod.rs
Normal file
@ -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())
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user