diff --git a/src/bootstrap/config.rs b/src/bootstrap/config.rs index f8acdc73..d07c3202 100644 --- a/src/bootstrap/config.rs +++ b/src/bootstrap/config.rs @@ -12,6 +12,9 @@ pub const ENV_VAR_CONFIG: &str = "TORRUST_IDX_BACK_CONFIG"; /// The `config.toml` file location. pub const ENV_VAR_CONFIG_PATH: &str = "TORRUST_IDX_BACK_CONFIG_PATH"; +/// If present, CORS will be permissive. +pub const ENV_VAR_CORS_PERMISSIVE: &str = "TORRUST_IDX_BACK_CORS_PERMISSIVE"; + // Default values pub const ENV_VAR_DEFAULT_CONFIG_PATH: &str = "./config.toml"; diff --git a/src/web/api/v1/routes.rs b/src/web/api/v1/routes.rs index 586ec2d7..996d3a6c 100644 --- a/src/web/api/v1/routes.rs +++ b/src/web/api/v1/routes.rs @@ -1,13 +1,14 @@ //! Route initialization for the v1 API. +use std::env; use std::sync::Arc; use axum::routing::get; use axum::Router; +use tower_http::cors::CorsLayer; use super::contexts::about::handlers::about_page_handler; -//use tower_http::cors::CorsLayer; -use super::contexts::{about, proxy, settings, tag, torrent}; -use super::contexts::{category, user}; +use super::contexts::{about, category, proxy, settings, tag, torrent, user}; +use crate::bootstrap::config::ENV_VAR_CORS_PERMISSIVE; use crate::common::AppData; pub const API_VERSION_URL_PREFIX: &str = "v1"; @@ -30,14 +31,13 @@ pub fn router(app_data: Arc) -> Router { .nest("/torrents", torrent::routes::router_for_multiple_resources(app_data.clone())) .nest("/proxy", proxy::routes::router(app_data.clone())); - Router::new() + let router = Router::new() .route("/", get(about_page_handler).with_state(app_data)) - .nest(&format!("/{API_VERSION_URL_PREFIX}"), v1_api_routes) - // For development purposes only. - // - //.layer(CorsLayer::permissive()) // Uncomment this line and the `use` import. - // - // It allows calling the API on a different port. For example - // API: http://localhost:3000/v1 - // Webapp: http://localhost:8080 + .nest(&format!("/{API_VERSION_URL_PREFIX}"), v1_api_routes); + + if env::var(ENV_VAR_CORS_PERMISSIVE).is_ok() { + router.layer(CorsLayer::permissive()) + } else { + router + } }