From 1ee9c932301da533037085f5eaba5a25d104791a Mon Sep 17 00:00:00 2001
From: Rasmus Moorats <xx@nns.ee>
Date: Tue, 16 Jul 2024 17:16:06 +0300
Subject: [PATCH] add CORS

---
 api/.idea/vcs.xml |  1 +
 api/src/main.rs   | 26 +++++++++++++++++++++++---
 2 files changed, 24 insertions(+), 3 deletions(-)

diff --git a/api/.idea/vcs.xml b/api/.idea/vcs.xml
index 35eb1dd..62bd7a0 100644
--- a/api/.idea/vcs.xml
+++ b/api/.idea/vcs.xml
@@ -2,5 +2,6 @@
 <project version="4">
   <component name="VcsDirectoryMappings">
     <mapping directory="" vcs="Git" />
+    <mapping directory="$PROJECT_DIR$/.." vcs="Git" />
   </component>
 </project>
\ No newline at end of file
diff --git a/api/src/main.rs b/api/src/main.rs
index dd4ba21..4d1d743 100644
--- a/api/src/main.rs
+++ b/api/src/main.rs
@@ -3,13 +3,32 @@ extern crate rocket;
 
 use std::process::Command;
 use std::sync::{Arc, Mutex};
-
-use rocket::http::Status;
+use rocket::fairing::{Fairing, Info, Kind};
+use rocket::http::{Header, Status};
 use rocket::response::status;
-use rocket::State;
+use rocket::{Request, Response, State};
 
 struct Rebooting(bool);
 
+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"));
+    }
+}
+
 #[get("/online")]
 fn online(is_rebooting: &State<Arc<Mutex<Rebooting>>>) -> Result<&'static str, status::Custom<String>> {
     let rebooting = is_rebooting.lock().map_err(|e| status::Custom(
@@ -93,6 +112,7 @@ fn restart_pipewire() -> Result<status::NoContent, status::Custom<String>> {
 fn rocket() -> _ {
     rocket::build()
         .manage(Arc::new(Mutex::new(Rebooting(false))))
+        .attach(CORS)
         .mount("/api", routes![
             restart_kodi, restart_pipewire, reboot, online
         ])