Cors support (#62)
Reviewed-on: #62 Co-authored-by: phoenix <kundeng00@pm.me> Co-committed-by: phoenix <kundeng00@pm.me>
This commit is contained in:
@@ -6,5 +6,5 @@ fn get_address() -> String {
|
||||
}
|
||||
|
||||
fn get_port() -> String {
|
||||
String::from("3000")
|
||||
String::from("8001")
|
||||
}
|
||||
|
@@ -1,3 +1,4 @@
|
||||
// TODO: Get rid of this file and place the code in more appropriate places
|
||||
pub mod callers;
|
||||
pub mod config;
|
||||
pub mod hashing;
|
||||
|
41
src/main.rs
41
src/main.rs
@@ -8,7 +8,7 @@ async fn main() {
|
||||
|
||||
let app = init::app().await;
|
||||
|
||||
// run our app with hyper, listening globally on port 3000
|
||||
// run our app with hyper, listening globally on port 8001
|
||||
let url = config::get_full();
|
||||
let listener = tokio::net::TcpListener::bind(url).await.unwrap();
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
@@ -45,6 +45,44 @@ mod init {
|
||||
)]
|
||||
struct ApiDoc;
|
||||
|
||||
mod cors {
|
||||
pub async fn configure_cors() -> tower_http::cors::CorsLayer {
|
||||
// Start building the CORS layer with common settings
|
||||
let cors = tower_http::cors::CorsLayer::new()
|
||||
.allow_methods([
|
||||
axum::http::Method::GET,
|
||||
axum::http::Method::POST,
|
||||
axum::http::Method::PUT,
|
||||
axum::http::Method::DELETE,
|
||||
]) // Specify allowed methods:cite[2]
|
||||
.allow_headers([
|
||||
axum::http::header::CONTENT_TYPE,
|
||||
axum::http::header::AUTHORIZATION,
|
||||
]) // Specify allowed headers:cite[2]
|
||||
.allow_credentials(true) // If you need to send cookies or authentication headers:cite[2]
|
||||
.max_age(std::time::Duration::from_secs(3600)); // Cache the preflight response for 1 hour:cite[2]
|
||||
|
||||
// Dynamically set the allowed origin based on the environment
|
||||
match std::env::var(icarus_envy::keys::APP_ENV).as_deref() {
|
||||
Ok("production") => {
|
||||
let allowed_origins_env = icarus_envy::environment::get_allowed_origins().await;
|
||||
let allowed_origins: Vec<axum::http::HeaderValue> = allowed_origins_env
|
||||
.split(",")
|
||||
.map(|s| s.parse::<axum::http::HeaderValue>().unwrap())
|
||||
.collect();
|
||||
cors.allow_origin(allowed_origins)
|
||||
}
|
||||
_ => {
|
||||
// Development (default): Allow localhost origins
|
||||
cors.allow_origin(vec![
|
||||
"http://localhost:4200".parse().unwrap(),
|
||||
"http://127.0.0.1:4200".parse().unwrap(),
|
||||
])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn routes() -> Router {
|
||||
// build our application with a route
|
||||
Router::new()
|
||||
@@ -72,6 +110,7 @@ mod init {
|
||||
callers::endpoints::REFRESH_TOKEN,
|
||||
post(callers::login::endpoint::refresh_token),
|
||||
)
|
||||
.layer(cors::configure_cors().await)
|
||||
}
|
||||
|
||||
pub async fn app() -> Router {
|
||||
|
Reference in New Issue
Block a user