rustream/squire/
middleware.rs

1use actix_cors::Cors;
2use actix_web::http::header;
3
4/// Configures and returns a CORS middleware based on provided website origins.
5///
6/// # Arguments
7///
8/// * `websites` - A vector of allowed website origins for CORS.
9///
10/// # Returns
11///
12/// A configured `Cors` middleware instance.
13pub fn get_cors(websites: Vec<String>) -> Cors {
14    let mut origins = vec!["http://localhost.com".to_string(), "https://localhost.com".to_string()];
15    if !websites.is_empty() {
16        origins.extend_from_slice(&websites);
17    }
18    // Create a clone to append /* to each endpoint, and further extend the same vector
19    let cloned = origins.clone().into_iter().map(|x| format!("{}/{}", x, "*"));
20    origins.extend(cloned);
21    let mut cors = Cors::default()
22        .allowed_methods(vec!["GET", "POST"])
23        .allowed_headers(vec![header::AUTHORIZATION, header::ACCEPT, header::CONTENT_TYPE])
24        .allowed_header("secure-flag")
25        .max_age(3600);  // Maximum time (in seconds) for which this CORS request may be cached
26    for origin in origins {
27        cors = cors.allowed_origin(&origin);
28    }
29    cors
30}