fix: cors
This commit is contained in:
parent
844677cc27
commit
fcad49bf7a
1 changed files with 29 additions and 6 deletions
|
|
@ -1,7 +1,7 @@
|
||||||
use axum::{
|
use axum::{
|
||||||
Json, RequestPartsExt, Router,
|
Json, RequestPartsExt, Router,
|
||||||
extract::{FromRef, FromRequestParts, Path, Query, State},
|
extract::{FromRef, FromRequestParts, Path, Query, State},
|
||||||
http::{StatusCode, request::Parts},
|
http::{HeaderValue, StatusCode, request::Parts},
|
||||||
routing::{get, post},
|
routing::{get, post},
|
||||||
};
|
};
|
||||||
use axum_extra::{
|
use axum_extra::{
|
||||||
|
|
@ -14,7 +14,7 @@ use sea_orm::{
|
||||||
};
|
};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use tower_http::cors::{Any, CorsLayer};
|
use tower_http::cors::{AllowOrigin, Any, CorsLayer};
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::agent::Agent;
|
use crate::agent::Agent;
|
||||||
|
|
@ -119,10 +119,7 @@ pub async fn start(db_url: &str) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
authenticator,
|
authenticator,
|
||||||
});
|
});
|
||||||
|
|
||||||
let cors = CorsLayer::new()
|
let cors = build_cors_layer();
|
||||||
.allow_origin(Any)
|
|
||||||
.allow_methods(Any)
|
|
||||||
.allow_headers(Any);
|
|
||||||
|
|
||||||
let app = Router::new()
|
let app = Router::new()
|
||||||
.route("/api/tasks", post(create_task).get(list_tasks))
|
.route("/api/tasks", post(create_task).get(list_tasks))
|
||||||
|
|
@ -143,6 +140,32 @@ pub async fn start(db_url: &str) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn build_cors_layer() -> CorsLayer {
|
||||||
|
let origins = std::env::var("CORS_ALLOWED_ORIGINS").ok();
|
||||||
|
|
||||||
|
let allow_origin = if let Some(origins) = origins {
|
||||||
|
let values: Vec<HeaderValue> = origins
|
||||||
|
.split(',')
|
||||||
|
.map(|origin| origin.trim())
|
||||||
|
.filter(|origin| !origin.is_empty())
|
||||||
|
.filter_map(|origin| HeaderValue::from_str(origin).ok())
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
if values.is_empty() {
|
||||||
|
AllowOrigin::any()
|
||||||
|
} else {
|
||||||
|
AllowOrigin::list(values)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
AllowOrigin::any()
|
||||||
|
};
|
||||||
|
|
||||||
|
CorsLayer::new()
|
||||||
|
.allow_origin(allow_origin)
|
||||||
|
.allow_methods(Any)
|
||||||
|
.allow_headers(Any)
|
||||||
|
}
|
||||||
|
|
||||||
async fn list_tasks(
|
async fn list_tasks(
|
||||||
_user: AuthenticatedUser,
|
_user: AuthenticatedUser,
|
||||||
State(state): State<Arc<AppState>>,
|
State(state): State<Arc<AppState>>,
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue