Skip to content

Commit

Permalink
feat: add cors headers
Browse files Browse the repository at this point in the history
  • Loading branch information
JacobLinCool committed Sep 10, 2023
1 parent 06cc3c7 commit b2cf587
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,12 @@ pub fn no_cache() -> bool {
Err(_) => false,
}
}

/// Disable CORS by setting the environment variable "NO_CORS" to "1" or "true".
/// If the variable is not set, a default value of false is returned.
pub fn no_cors() -> bool {
match env::var("NO_CORS") {
Ok(val) => val == "1" || val == "true",
Err(_) => false,
}
}
7 changes: 7 additions & 0 deletions src/server/core.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use super::compress;
use super::cors;
use super::routes;
use super::version;
use crate::compile;
Expand Down Expand Up @@ -43,6 +44,12 @@ pub fn rocket() -> Rocket<Build> {

let server = server.attach(version::fairing());

let server = if !no_cors() {
server.attach(cors::CORS)
} else {
server
};

if cfg!(debug_assertions) {
server
} else {
Expand Down
25 changes: 25 additions & 0 deletions src/server/cors.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
use rocket::fairing::{Fairing, Info, Kind};
use rocket::http::Header;
use rocket::{Request, Response};

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, _req: &'r Request<'_>, res: &mut Response<'r>) {
res.set_header(Header::new("Access-Control-Allow-Origin", "*"));
res.set_header(Header::new(
"Access-Control-Allow-Methods",
"POST, GET, PATCH, OPTIONS",
));
res.set_header(Header::new("Access-Control-Allow-Headers", "*"));
res.set_header(Header::new("Access-Control-Allow-Credentials", "true"));
}
}
1 change: 1 addition & 0 deletions src/server/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
pub mod compress;
pub mod core;
pub mod cors;
pub mod jwt;
pub mod routes;
pub mod system;
Expand Down

0 comments on commit b2cf587

Please sign in to comment.