use http::{HeaderValue, Method, StatusCode, header};
use crate::context::Context;
use crate::handler::BoxFuture;
use crate::middleware::{Middleware, Next};
use crate::response::Response;
#[derive(Debug, Clone)]
pub struct Cors {
origins: Option<Vec<String>>,
methods: Vec<String>,
expose: Vec<String>,
credentials: bool,
max_age: u64,
}
impl Cors {
pub fn any_origin() -> Self {
Self {
origins: None,
methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"]
.map(String::from)
.to_vec(),
expose: Vec::new(),
credentials: false,
max_age: 7200,
}
}
pub fn origins<S: Into<String>>(origins: impl IntoIterator<Item = S>) -> Self {
Self {
origins: Some(origins.into_iter().map(Into::into).collect()),
..Self::any_origin()
}
}
#[must_use]
pub fn methods<S: Into<String>>(mut self, methods: impl IntoIterator<Item = S>) -> Self {
self.methods = methods
.into_iter()
.map(|m| m.into().to_uppercase())
.collect();
self
}
#[must_use]
pub fn expose<S: Into<String>>(mut self, headers: impl IntoIterator<Item = S>) -> Self {
self.expose = headers.into_iter().map(Into::into).collect();
self
}
#[must_use]
pub fn credentials(mut self) -> Self {
self.credentials = true;
self
}
#[must_use]
pub fn max_age(mut self, seconds: u64) -> Self {
self.max_age = seconds;
self
}
fn allow_origin(&self, origin: &str) -> Option<String> {
match &self.origins {
None if !self.credentials => Some("*".to_owned()),
None => Some(origin.to_owned()),
Some(list) => list.iter().any(|o| o == origin).then(|| origin.to_owned()),
}
}
fn add_headers(&self, response: &mut Response, allow_origin: &str) {
let mut set = |name: &str, value: String| {
if let (Ok(name), Ok(value)) = (
header::HeaderName::try_from(name),
HeaderValue::try_from(value),
) {
response.headers_mut().insert(name, value);
}
};
set("access-control-allow-origin", allow_origin.to_owned());
set("access-control-allow-methods", self.methods.join(", "));
if !self.expose.is_empty() {
set("access-control-expose-headers", self.expose.join(", "));
}
set("access-control-max-age", self.max_age.to_string());
if self.credentials {
set("access-control-allow-credentials", "true".to_owned());
}
}
}
impl Middleware for Cors {
fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
let cors = self.clone();
Box::pin(async move {
let origin = ctx.header(header::ORIGIN).map(str::to_owned);
let requested = ctx
.header(header::ACCESS_CONTROL_REQUEST_METHOD)
.map(str::to_uppercase);
if *ctx.method() == Method::OPTIONS
&& let (Some(origin), Some(requested)) = (&origin, &requested)
{
let mut response = Response::head(StatusCode::OK);
let allowed = cors.methods.iter().any(|m| m == requested);
if let Some(allow) = cors.allow_origin(origin).filter(|_| allowed) {
cors.add_headers(&mut response, &allow);
if let Some(headers) = ctx.header(header::ACCESS_CONTROL_REQUEST_HEADERS)
&& let Ok(value) = HeaderValue::try_from(headers)
{
response
.headers_mut()
.insert(header::ACCESS_CONTROL_ALLOW_HEADERS, value);
}
}
return response;
}
let mut response = next.run(ctx).await;
if let Some(allow) = origin.as_deref().and_then(|o| cors.allow_origin(o)) {
cors.add_headers(&mut response, &allow);
}
let vary = match response
.headers()
.get(header::VARY)
.and_then(|v| v.to_str().ok())
{
Some(existing)
if existing
.split(',')
.any(|v| v.trim().eq_ignore_ascii_case("origin")) =>
{
None
}
Some(existing) => Some(format!("{existing}, Origin")),
None => Some("Origin".to_owned()),
};
if let Some(vary) = vary.and_then(|v| HeaderValue::try_from(v).ok()) {
response.headers_mut().insert(header::VARY, vary);
}
response
})
}
}