kegani 0.1.1

A developer-friendly, ergonomic, production-ready Rust web framework
Documentation
//! CORS (Cross-Origin Resource Sharing) middleware
//!
//! Configurable CORS handling for API endpoints.

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};

/// CORS configuration
#[derive(Debug, Clone)]
pub struct CorsConfig {
    /// Allowed origins
    pub allowed_origins: Vec<String>,
    /// Allowed methods
    pub allowed_methods: Vec<Method>,
    /// Allowed headers
    pub allowed_headers: Vec<String>,
    /// Max age in seconds
    pub max_age: u64,
    /// Allow credentials
    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,
        }
    }
}

/// CORS middleware
pub struct Cors {
    config: CorsConfig,
}

impl Cors {
    /// Create a new Cors middleware
    pub fn new() -> Self {
        Self {
            config: CorsConfig::default(),
        }
    }

    /// Create a permissive CORS middleware (allows all origins, all methods)
    pub fn permissive() -> Self {
        Self {
            config: CorsConfig::default(),
        }
    }

    /// Set allowed origins
    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();

        // Extract origin before consuming req
        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?;

            // Add CORS headers
            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)
        })
    }
}