Skip to content

Commit 90497b7

Browse files
committed
Add CORS policy allowing cross origin requests
1 parent 0220f36 commit 90497b7

File tree

3 files changed

+54
-2
lines changed

3 files changed

+54
-2
lines changed

Cargo.lock

Lines changed: 37 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,3 +30,4 @@ flate2 = "1.0.24"
3030
enum_dispatch = "0.3.8"
3131
async-trait = "0.1.66"
3232
reqwest = { version = "0.11.17", features = ["json"] }
33+
rocket_cors = "0.6.0"

src/main.rs

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@ use std::{marker::PhantomData, sync::Arc, env, net::{Ipv4Addr, IpAddr}};
55
use anyhow::anyhow;
66
use config::{deserialize_mars_config, MarsConfig};
77
use database::{Database, cache::{Cache, get_redis_pool, RedisAdapter}, models::{player::Player, r#match::Match}};
8-
use rocket::{Build, Rocket, Shutdown, Config, figment::Figment};
8+
use rocket::{figment::Figment, http::Method, Build, Config, Rocket, Shutdown};
9+
use rocket_cors::{AllowedOrigins, CorsOptions};
910
use socket::leaderboard::MarsLeaderboards;
1011
use crate::database::migrations::MigrationExecutor;
1112

@@ -82,8 +83,21 @@ fn rocket(state: MarsAPIState) -> Rocket<Build> {
8283
rocket_build
8384
}
8485

86+
fn get_cors_configuration() -> CorsOptions {
87+
CorsOptions::default()
88+
.allowed_origins(AllowedOrigins::all())
89+
.allowed_methods(
90+
vec![Method::Get, Method::Post]
91+
.into_iter()
92+
.map(From::from)
93+
.collect(),
94+
)
95+
.allow_credentials(true)
96+
}
97+
8598
async fn spawn_rocket(state: MarsAPIState) -> Result<Shutdown, String> {
86-
let rocket = match rocket(state).ignite().await {
99+
let cors = get_cors_configuration().to_cors().unwrap();
100+
let rocket = match rocket(state).attach(cors).ignite().await {
87101
Ok(rocket) => rocket,
88102
Err(rocket_err) => return Err(format!("{}", rocket_err))
89103
};

0 commit comments

Comments
 (0)