1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
use rocket::fairing::{Fairing, Info, Kind};
use rocket::http::Header;
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: &rocket::Request, response: &mut rocket::Response) {
if request.method() == rocket::http::Method::Options
|| response.content_type() == Some(rocket::http::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"));
response.set_header(Header::new(
"Content-Security-Policy-Report-Only",
"default-src https:; report-uri /csp-violation-report-endpoint/",
));
}
if request.method() == rocket::http::Method::Options {
response.set_header(rocket::http::ContentType::Plain);
response.set_sized_body(Cursor::new(""));
}
}
}