From cccc095de8829a312b9429d564748adcc0c246ca Mon Sep 17 00:00:00 2001 From: Kavin <20838718+FireMasterK@users.noreply.github.com> Date: Tue, 25 Oct 2022 10:13:34 +0100 Subject: [PATCH] Add cors for official instance. --- Rocket.toml | 1 + src/main.rs | 31 ++++++++++++++++++++++++++++--- 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/Rocket.toml b/Rocket.toml index 340a209..5f50ac0 100644 --- a/Rocket.toml +++ b/Rocket.toml @@ -1,5 +1,6 @@ [release] address = "0.0.0.0" +log_level = "off" [debug.databases] sponsorblock = { url = "postgresql://sponsorblock:password123@localhost" } diff --git a/src/main.rs b/src/main.rs index a0225f1..44ade8a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,8 +6,9 @@ use std::thread::sleep; use std::time::{Duration, Instant, SystemTime}; use diesel::connection::SimpleConnection; -use rocket::{Build, Rocket}; -use rocket::fairing::AdHoc; +use rocket::{Build, Request, Response, Rocket}; +use rocket::fairing::{AdHoc, Fairing, Info, Kind}; +use rocket::http::Header; use rocket_sync_db_pools::database; use tokio::time::interval; @@ -38,6 +39,29 @@ async fn run_migrations(rocket: Rocket) -> Rocket { rocket } +pub struct CORS; + +#[rocket::async_trait] +impl Fairing for CORS { + fn info(&self) -> Info { + Info { + name: "Add CORS headers to responses", + kind: Kind::Response, + } + } + + async fn on_response<'r>(&self, request: &'r Request<'_>, response: &mut Response<'r>) { + response.set_header(Header::new("Access-Control-Allow-Origin", "*")); + response.set_header(Header::new("Access-Control-Allow-Methods", "POST, GET, PATCH, OPTIONS")); + response.set_header(Header::new("Access-Control-Allow-Headers", "*")); + response.set_header(Header::new("Access-Control-Allow-Credentials", "true")); + if request.method() == rocket::http::Method::Options { + response.set_streamed_body(tokio::io::empty()); + response.set_status(rocket::http::Status::Ok); + } + } +} + static mut LAST_UPDATE: Option = None; #[launch] @@ -95,5 +119,6 @@ fn rocket() -> Rocket { }); }) }) - ).mount("/", routes![skip_segments]) + ).attach(CORS) + .mount("/", routes![skip_segments]) }