use actix_web::{
dev::{Service, ServiceRequest, ServiceResponse, Transform},
http::{header, Method},
Error,
};
use std::future::{ready, Ready};
use std::pin::Pin;
use std::task::{Context, Poll};
#[derive(Debug, Clone)]
pub struct CorsConfig {
pub allowed_origins: Vec<String>,
pub allowed_methods: Vec<Method>,
pub allowed_headers: Vec<String>,
pub max_age: u64,
pub allow_credentials: bool,
}
impl Default for CorsConfig {
fn default() -> Self {
Self {
allowed_origins: vec!["*".to_string()],
allowed_methods: vec![
Method::GET,
Method::POST,
Method::PUT,
Method::DELETE,
Method::PATCH,
Method::HEAD,
Method::OPTIONS,
],
allowed_headers: vec![
"Accept".to_string(),
"Content-Type".to_string(),
"Authorization".to_string(),
],
max_age: 3600,
allow_credentials: true,
}
}
}
pub struct Cors {
config: CorsConfig,
}
impl Cors {
pub fn new() -> Self {
Self {
config: CorsConfig::default(),
}
}
pub fn permissive() -> Self {
Self {
config: CorsConfig::default(),
}
}
pub fn allowed_origins(mut self, origins: Vec<&str>) -> Self {
self.config.allowed_origins = origins.into_iter().map(String::from).collect();
self
}
}
impl Default for Cors {
fn default() -> Self {
Self::new()
}
}
impl<S, B> Transform<S, ServiceRequest> for Cors
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
S::Future: 'static,
B: 'static,
{
type Response = ServiceResponse<B>;
type Error = Error;
type Transform = CorsMiddleware<S>;
type InitError = ();
type Future = Ready<Result<Self::Transform, Self::InitError>>;
fn new_transform(&self, service: S) -> Self::Future {
ready(Ok(CorsMiddleware {
service,
config: self.config.clone(),
}))
}
}
pub struct CorsMiddleware<S> {
service: S,
config: CorsConfig,
}
impl<S, B> Service<ServiceRequest> for CorsMiddleware<S>
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
S::Future: 'static,
B: 'static,
{
type Response = ServiceResponse<B>;
type Error = Error;
type Future = Pin<Box<dyn std::future::Future<Output = Result<Self::Response, Self::Error>>>>;
fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.service.poll_ready(cx)
}
fn call(&self, req: ServiceRequest) -> Self::Future {
let config = self.config.clone();
let origin = req
.headers()
.get(header::ORIGIN)
.and_then(|v| v.to_str().ok())
.map(String::from);
let fut = self.service.call(req);
Box::pin(async move {
let mut res = fut.await?;
if let Some(origin) = origin {
res.headers_mut().insert(
header::ACCESS_CONTROL_ALLOW_ORIGIN,
actix_web::http::header::HeaderValue::from_str(&origin).unwrap_or_else(|_| actix_web::http::header::HeaderValue::from_static("*")),
);
}
if config.allow_credentials {
res.headers_mut().insert(
header::ACCESS_CONTROL_ALLOW_CREDENTIALS,
actix_web::http::header::HeaderValue::from_static("true"),
);
}
Ok(res)
})
}
}