Skip to content

Commit

Permalink
Merge pull request #21 from traP-jp/cors-credentials
Browse files Browse the repository at this point in the history
Access-Control-Allow-Credentials
  • Loading branch information
H1rono authored Dec 16, 2023
2 parents aa13375 + 7115846 commit fd7550f
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
8 changes: 3 additions & 5 deletions entrypoint/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{env, process::exit};
use std::env;

use anyhow::{Context, Result};
use once_cell::sync::Lazy;
Expand All @@ -13,10 +13,7 @@ use repository::card::{
use handler::cors::{options, CorsConfig};

static CORS_CONFIG: Lazy<CorsConfig> = Lazy::new(|| {
let Ok(origins) = env::var("ALLOWED_ORIGINS") else {
eprintln!("env_var ALLOWED_ORIGIN is unset");
exit(1);
};
let origins = env::var("ALLOWED_ORIGINS").expect("env_var ALLOWED_ORIGIN is unset");
CorsConfig::new(origins.split(' '))
});

Expand Down Expand Up @@ -74,6 +71,7 @@ async fn main() -> Result<()> {
return;
};
res.set_header(origin_header);
res.set_header(CORS_CONFIG.render_credentials());
if req.method() != Method::Options {
println!("CORS wrapper: method is not OPTION");
return;
Expand Down
19 changes: 18 additions & 1 deletion handler/src/cors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ use itertools::Itertools;
use rocket::http::{hyper, Header, Method, Status};

use hyper::header::{
ACCESS_CONTROL_ALLOW_HEADERS, ACCESS_CONTROL_ALLOW_METHODS, ACCESS_CONTROL_ALLOW_ORIGIN,
ACCESS_CONTROL_ALLOW_CREDENTIALS, ACCESS_CONTROL_ALLOW_HEADERS, ACCESS_CONTROL_ALLOW_METHODS,
ACCESS_CONTROL_ALLOW_ORIGIN,
};

#[derive(Debug, Clone)]
pub struct CorsConfig {
pub origins: Vec<String>,
pub allow_credentials: bool,
pub methods: Vec<Method>,
pub headers: Vec<String>,
}
Expand All @@ -16,11 +18,19 @@ impl CorsConfig {
pub fn new<'s>(origins: impl Iterator<Item = &'s str>) -> Self {
Self {
origins: origins.map(|s| s.to_string()).collect(),
allow_credentials: true,
methods: vec![],
headers: vec![],
}
}

pub fn credentials(self, value: bool) -> Self {
Self {
allow_credentials: value,
..self
}
}

pub fn add_method(mut self, method: Method) -> Self {
self.methods.push(method);
self
Expand All @@ -38,6 +48,13 @@ impl CorsConfig {
.then(|| Header::new(ACCESS_CONTROL_ALLOW_ORIGIN.as_str(), origin))
}

pub fn render_credentials(&self) -> Header<'_> {
Header::new(
ACCESS_CONTROL_ALLOW_CREDENTIALS.as_str(),
self.allow_credentials.to_string(),
)
}

pub fn render_methods(&self) -> Header<'_> {
if !self.methods.is_empty() {
Header::new(
Expand Down

0 comments on commit fd7550f

Please sign in to comment.