use crate::{
configuration::Configuration,
error::CorsError,
model::{
cors::CorsResourceFactory, request::request_processor::RequestProcessor,
resource::protected_resource::ResponseType as InnerResponseType,
},
};
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
pub enum ResponseType {
Preflight,
Main,
}
#[derive(Debug, Clone)]
pub struct Check {
response_type: ResponseType,
headers: Vec<(String, String)>,
}
impl Check {
fn from_response_type(response_type: InnerResponseType) -> Self {
match response_type {
InnerResponseType::Main(headers) => Self {
response_type: ResponseType::Main,
headers,
},
InnerResponseType::Preflight(headers) => Self {
response_type: ResponseType::Preflight,
headers,
},
}
}
pub fn response_type(&self) -> ResponseType {
self.response_type
}
pub fn headers(&self) -> &[(String, String)] {
&self.headers
}
pub fn into_headers(self) -> Vec<(String, String)> {
self.headers
}
}
pub struct Cors<'a> {
processor: RequestProcessor<'a>,
}
impl<'a> Cors<'a> {
pub fn new(config: &'a Configuration<'a>) -> Self {
Cors {
processor: RequestProcessor::new(CorsResourceFactory::from_configuration(config)),
}
}
pub fn check_headers(&self, headers: &[(String, String)]) -> Result<Check, CorsError> {
let header_map: Vec<_> = headers
.iter()
.map(|(n, v)| (n.as_str(), v.as_str()))
.collect();
self.processor
.process_request(header_map.as_slice())
.map(Check::from_response_type)
}
}