Skip to content

Commit 0ffa532

Browse files
committed
add cors filter
1 parent 35f7365 commit 0ffa532

2 files changed

Lines changed: 26 additions & 2 deletions

File tree

src/server/guild/ws.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use mongodb::bson::oid::ObjectId;
66
use serde::{Deserialize, Serialize};
77
use tokio::sync::mpsc::UnboundedSender;
88
use tokio_stream::wrappers::UnboundedReceiverStream;
9-
use tracing::{error, info, warn};
9+
use tracing::{error, info};
1010
use twilight_model::id::Id;
1111
use twilight_model::id::marker::UserMarker;
1212
use twilight_model::user::CurrentUserGuild;

src/server/mod.rs

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,10 +31,14 @@ pub mod guild {
3131

3232
#[cfg(any(feature = "api", feature = "http-interactions"))]
3333
mod http_server {
34+
use std::env;
3435
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
36+
use std::str::FromStr;
3537
use std::sync::Arc;
38+
use tracing::warn;
3639
use twilight_http::Client;
3740
use warp::Filter;
41+
use warp::http::{HeaderName, Method};
3842
use crate::context::Context;
3943

4044
#[macro_export]
@@ -57,9 +61,29 @@ mod http_server {
5761
discord_http: Arc<Client>,
5862
#[cfg(feature = "http-interactions")] public_key: ed25519_dalek::VerifyingKey
5963
) {
64+
let cors_allow = if let Ok(origin) = env::var("ALLOWED_ORIGIN") {
65+
warp::cors()
66+
.allow_origin(origin.as_str())
67+
} else {
68+
warn!(
69+
"There is no ALLOWED_ORIGIN environment variable, CORS Headers are set to accept all requests"
70+
);
71+
warp::cors().allow_any_origin()
72+
};
73+
let cors_allow = cors_allow
74+
.allow_headers([
75+
HeaderName::from_str("Authorization").unwrap(),
76+
HeaderName::from_str("User-Id").unwrap()
77+
])
78+
.allow_methods([Method::GET, Method::POST])
79+
.allow_credentials(true)
80+
.build();
81+
6082
let routes = crate::server::routes::get_all_routes(
6183
discord_http, context, #[cfg(feature = "http-interactions")] public_key
62-
).recover(crate::server::error::handle_rejection);
84+
)
85+
.recover(crate::server::error::handle_rejection)
86+
.with(cors_allow);
6387

6488
const ALL_SOCKETS: IpAddr = IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0));
6589
warp::serve(routes).run(SocketAddr::new(ALL_SOCKETS, port)).await;

0 commit comments

Comments
 (0)