Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: update to gotham 0.4 #3

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@ description = "A small crate to add basic CORS functionality to Gotham apps"
repository = "https://github.com/simpleweb/gotham-cors-middleware"
readme = "./README.md"
license = "MIT OR Apache-2.0"
edition = "2018"

[dependencies]
futures = "0.1"
gotham = "0.2"
gotham_derive = "0.2"
hyper = "0.11"
unicase = "2.1"
gotham = "0.4"
gotham_derive = "0.4"
hyper = "0.12"

[dev-dependencies]
mime = "0.3"
150 changes: 91 additions & 59 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,17 @@
#[macro_use]
extern crate gotham_derive;

extern crate futures;
extern crate gotham;
extern crate hyper;
extern crate unicase;

use futures::Future;
use gotham::handler::HandlerFuture;
use gotham::middleware::Middleware;
use gotham::state::{FromState, State};
use hyper::header::{
AccessControlAllowCredentials, AccessControlAllowHeaders, AccessControlAllowMethods,
AccessControlAllowOrigin, AccessControlMaxAge, Headers, Origin,
HeaderMap, HeaderValue, ACCESS_CONTROL_ALLOW_CREDENTIALS, ACCESS_CONTROL_ALLOW_HEADERS,
ACCESS_CONTROL_ALLOW_METHODS, ACCESS_CONTROL_ALLOW_ORIGIN, ACCESS_CONTROL_MAX_AGE,
AUTHORIZATION, CONTENT_TYPE, ORIGIN,
};
use hyper::Method;
use std::option::Option;
use unicase::Ascii;

/// Struct to perform the necessary CORS
/// functionality needed. Allows some
Expand Down Expand Up @@ -83,7 +78,7 @@ impl CORSMiddleware {
/// use hyper::Method;
///
/// fn create_custom_middleware() -> CORSMiddleware {
/// let methods = vec![Method::Delete, Method::Get, Method::Head, Method::Options];
/// let methods = vec![Method::DELETE, Method::GET, Method::HEAD, Method::OPTIONS];
///
/// let max_age = 1000;
///
Expand Down Expand Up @@ -120,13 +115,13 @@ impl CORSMiddleware {
/// values, use the new() function.
pub fn default() -> CORSMiddleware {
let methods = vec![
Method::Delete,
Method::Get,
Method::Head,
Method::Options,
Method::Patch,
Method::Post,
Method::Put,
Method::DELETE,
Method::GET,
Method::HEAD,
Method::OPTIONS,
Method::PATCH,
Method::POST,
Method::PUT,
];

let origin = None;
Expand All @@ -139,15 +134,15 @@ impl CORSMiddleware {
impl Middleware for CORSMiddleware {
fn call<Chain>(self, state: State, chain: Chain) -> Box<HandlerFuture>
where
Chain: FnOnce(State) -> Box<HandlerFuture>,
Chain: FnOnce(State) -> Box<HandlerFuture> + Send + 'static,
{
let settings = self.clone();
let f = chain(state).map(|(state, response)| {
let f = chain(state).map(|(state, mut response)| {
let origin: String;
if settings.origin.is_none() {
let origin_raw = Headers::borrow_from(&state).get::<Origin>().clone();
let origin_raw = HeaderMap::borrow_from(&state).get(ORIGIN).clone();
let ori = match origin_raw {
Some(o) => o.to_string(),
Some(o) => o.to_str().unwrap().to_string(),
None => "*".to_string(),
};

Expand All @@ -156,20 +151,44 @@ impl Middleware for CORSMiddleware {
origin = settings.origin.unwrap();
};

let mut headers = Headers::new();

headers.set(AccessControlAllowCredentials);
headers.set(AccessControlAllowHeaders(vec![
Ascii::new("Authorization".to_string()),
Ascii::new("Content-Type".to_string()),
]));
headers.set(AccessControlAllowOrigin::Value(origin));
headers.set(AccessControlAllowMethods(settings.methods));
headers.set(AccessControlMaxAge(settings.max_age));

let res = response.with_headers(headers);

(state, res)
let methods = settings
.methods
.iter()
.map(|m| String::from(m.as_str()))
.collect::<Vec<String>>()
.join(", ");

let headers = vec![AUTHORIZATION, CONTENT_TYPE]
.iter()
.map(|m| String::from(m.as_str()))
.collect::<Vec<String>>()
.join(", ");

response.headers_mut().insert(
ACCESS_CONTROL_ALLOW_CREDENTIALS,
HeaderValue::from_str("true").unwrap(),
);

response.headers_mut().insert(
ACCESS_CONTROL_ALLOW_ORIGIN,
HeaderValue::from_str(&origin).unwrap(),
);

response.headers_mut().insert(
ACCESS_CONTROL_ALLOW_HEADERS,
HeaderValue::from_str(&headers).unwrap(),
);

response.headers_mut().insert(
ACCESS_CONTROL_ALLOW_METHODS,
HeaderValue::from_str(&methods).unwrap(),
);

response
.headers_mut()
.insert(ACCESS_CONTROL_MAX_AGE, HeaderValue::from(settings.max_age));

(state, response)
});

Box::new(f)
Expand All @@ -183,25 +202,20 @@ mod tests {
use super::*;

use futures::future;
use gotham::http::response::create_response;
use gotham::helpers::http::response::create_response;
use gotham::pipeline::new_pipeline;
use gotham::pipeline::single::single_pipeline;
use gotham::router::builder::*;
use gotham::router::Router;
use gotham::test::TestServer;
use hyper::Method::Options;
use hyper::Method;
use hyper::StatusCode;
use hyper::{Get, Head};

// Since we cannot construct 'State' ourselves, we need to test via an 'actual' app
fn handler(state: State) -> Box<HandlerFuture> {
let body = "Hello World".to_string();

let response = create_response(
&state,
StatusCode::Ok,
Some((body.into_bytes(), mime::TEXT_PLAIN)),
);
let response = create_response(&state, StatusCode::OK, mime::TEXT_PLAIN, body.into_bytes());

Box::new(future::ok((state, response)))
}
Expand All @@ -211,12 +225,14 @@ mod tests {
single_pipeline(new_pipeline().add(CORSMiddleware::default()).build());

build_router(chain, pipeline, |route| {
route.request(vec![Get, Head, Options], "/").to(handler);
route
.request(vec![Method::GET, Method::HEAD, Method::OPTIONS], "/")
.to(handler);
})
}

fn custom_router() -> Router {
let methods = vec![Method::Delete, Method::Get, Method::Head, Method::Options];
let methods = vec![Method::DELETE, Method::GET, Method::HEAD, Method::OPTIONS];

let max_age = 1000;

Expand All @@ -229,7 +245,9 @@ mod tests {
);

build_router(chain, pipeline, |route| {
route.request(vec![Get, Head, Options], "/").to(handler);
route
.request(vec![Method::GET, Method::HEAD, Method::OPTIONS], "/")
.to(handler);
})
}

Expand All @@ -243,17 +261,24 @@ mod tests {
.perform()
.unwrap();

assert_eq!(response.status(), StatusCode::Ok);
assert_eq!(response.status(), StatusCode::OK);
let headers = response.headers();
assert_eq!(
headers
.get::<AccessControlAllowOrigin>()
.get(ACCESS_CONTROL_ALLOW_ORIGIN)
.unwrap()
.to_str()
.unwrap()
.to_string(),
"*".to_string()
);
assert_eq!(
headers.get::<AccessControlMaxAge>().unwrap().to_string(),
headers
.get(ACCESS_CONTROL_MAX_AGE)
.unwrap()
.to_str()
.unwrap()
.to_string(),
"86400".to_string()
);
}
Expand All @@ -268,24 +293,31 @@ mod tests {
.perform()
.unwrap();

assert_eq!(response.status(), StatusCode::Ok);
assert_eq!(response.status(), StatusCode::OK);
let headers = response.headers();
assert_eq!(
headers
.get::<AccessControlAllowOrigin>()
.get(ACCESS_CONTROL_ALLOW_ORIGIN)
.unwrap()
.to_str()
.unwrap()
.to_string(),
"http://www.example.com".to_string()
);
assert_eq!(
headers.get::<AccessControlMaxAge>().unwrap().to_string(),
headers
.get(ACCESS_CONTROL_MAX_AGE)
.unwrap()
.to_str()
.unwrap()
.to_string(),
"1000".to_string()
);
}

#[test]
fn test_new_cors_middleware() {
let methods = vec![Method::Delete, Method::Get, Method::Head, Method::Options];
let methods = vec![Method::DELETE, Method::GET, Method::HEAD, Method::OPTIONS];

let max_age = 1000;

Expand All @@ -306,13 +338,13 @@ mod tests {
fn test_default_cors_middleware() {
let test = CORSMiddleware::default();
let methods = vec![
Method::Delete,
Method::Get,
Method::Head,
Method::Options,
Method::Patch,
Method::Post,
Method::Put,
Method::DELETE,
Method::GET,
Method::HEAD,
Method::OPTIONS,
Method::PATCH,
Method::POST,
Method::PUT,
];

assert_eq!(test.methods, methods);
Expand Down