Skip to content

Commit

Permalink
feat: add env var to set permissive CORS policy
Browse files Browse the repository at this point in the history
Running the backend with:

```
TORRUST_IDX_BACK_CORS_PERMISSIVE=true cargo run
```

will make the CORS policy to be permissive, which means you can use a
different port for the API and serving the frontend app. It's intented
for development purposes.
  • Loading branch information
josecelano committed Jun 26, 2023
1 parent 910a419 commit f998d9d
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 12 deletions.
3 changes: 3 additions & 0 deletions src/bootstrap/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
24 changes: 12 additions & 12 deletions src/web/api/v1/routes.rs
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -30,14 +31,13 @@ pub fn router(app_data: Arc<AppData>) -> 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
}
}

0 comments on commit f998d9d

Please sign in to comment.