1
0
Fork 0
mirror of https://gitlab.com/msrd0/gotham-restful.git synced 2025-02-22 20:52:27 +00:00

update jsonwebtoken, futures, and hyper and co

This commit is contained in:
Dominic 2020-04-14 17:44:07 +02:00
parent fbcc626478
commit f425f21ff3
Signed by: msrd0
GPG key ID: DCC8C247452E98F9
11 changed files with 83 additions and 71 deletions

View file

@ -10,4 +10,4 @@ members = [
[patch.crates-io]
gotham_restful = { path = "./gotham_restful" }
gotham_restful_derive = { path = "./gotham_restful_derive" }
openapiv3 = { git = "https://github.com/glademiller/openapiv3", rev = "4c3bd95c966a3f9d59bb494c3d8e30c5c3068bdb" }
openapiv3 = { git = "https://github.com/glademiller/openapiv3", rev = "4c3bd95c966a3f9d59bb494c3d8e30c5c3068bdb" }

View file

@ -15,10 +15,9 @@ gitlab = { repository = "msrd0/gotham-restful", branch = "master" }
[dependencies]
fake = "2.2"
gotham = "0.4"
gotham_derive = "0.4"
gotham = { git = "https://github.com/gotham-rs/gotham", version = "0.5.0-dev", default-features = false }
gotham_derive = { git = "https://github.com/gotham-rs/gotham", version = "0.5.0-dev", default-features = false }
gotham_restful = { version = "0.0.3", features = ["auth", "openapi"] }
hyper = "0.12"
log = "0.4"
log4rs = { version = "0.8", features = ["console_appender"], default-features = false }
serde = "1"

View file

@ -15,17 +15,19 @@ repository = "https://gitlab.com/msrd0/gotham-restful"
gitlab = { repository = "msrd0/gotham-restful", branch = "master" }
[dependencies]
base64 = { version = ">=0.10.1, <0.12", optional = true }
base64 = { version = "0.12.0", optional = true }
chrono = { version = "0.4.10", optional = true }
cookie = { version = "0.12", optional = true }
futures = "0.1.29"
gotham = "0.4"
gotham_derive = "0.4"
gotham_middleware_diesel = { version = "0.1", optional = true }
cookie = { version = "0.13.3", optional = true }
futures = "0.3.4"
futures-core = "0.3.4"
futures-util = "0.3.4"
gotham = { git = "https://github.com/gotham-rs/gotham", version = "0.5.0-dev", default-features = false }
gotham_derive = { git = "https://github.com/gotham-rs/gotham", version = "0.5.0-dev" }
gotham_middleware_diesel = { git = "https://github.com/gotham-rs/gotham", version = "0.1.0", optional = true }
gotham_restful_derive = { version = "0.0.2" }
hyper = "0.12.35"
hyper = "0.13.4"
indexmap = { version = "1.3.0", optional = true }
jsonwebtoken = { version = "6.0.1", optional = true }
jsonwebtoken = { version = "7.1.0", optional = true }
log = { version = "0.4.8", optional = true }
mime = "0.3.16"
openapiv3 = { version = "0.3", optional = true }
@ -34,6 +36,7 @@ serde_json = "1.0.45"
uuid = { version = ">= 0.1, < 0.9", optional = true }
[dev-dependencies]
futures-executor = "0.3.4"
paste = "0.1.10"
thiserror = "1"

View file

@ -1,17 +1,21 @@
use crate::HeaderName;
use cookie::CookieJar;
use futures::{future, future::Future};
use futures_util::{future, future::{FutureExt, TryFutureExt}};
use gotham::{
handler::HandlerFuture,
middleware::{Middleware, NewMiddleware},
state::{FromState, State}
};
use hyper::header::{AUTHORIZATION, HeaderMap};
use jsonwebtoken::errors::ErrorKind;
use jsonwebtoken::{
errors::ErrorKind,
DecodingKey
};
use serde::de::DeserializeOwned;
use std::{
marker::PhantomData,
panic::RefUnwindSafe
panic::RefUnwindSafe,
pin::Pin
};
pub use jsonwebtoken::Validation as AuthValidation;
@ -248,7 +252,7 @@ where
};
// validate the token
let data : Data = match jsonwebtoken::decode(&token, &secret, &self.validation) {
let data : Data = match jsonwebtoken::decode(&token, &DecodingKey::from_secret(&secret), &self.validation) {
Ok(data) => data.claims,
Err(e) => match dbg!(e.into_kind()) {
ErrorKind::ExpiredSignature => return AuthStatus::Expired,
@ -266,9 +270,9 @@ where
Data : DeserializeOwned + Send + 'static,
Handler : AuthHandler<Data>
{
fn call<Chain>(self, mut state : State, chain : Chain) -> Box<HandlerFuture>
fn call<Chain>(self, mut state : State, chain : Chain) -> Pin<Box<HandlerFuture>>
where
Chain : FnOnce(State) -> Box<HandlerFuture>
Chain : FnOnce(State) -> Pin<Box<HandlerFuture>>
{
// put the source in our state, required for e.g. openapi
state.put(self.source.clone());
@ -278,7 +282,7 @@ where
state.put(status);
// call the rest of the chain
Box::new(chain(state).and_then(|(state, res)| future::ok((state, res))))
chain(state).and_then(|(state, res)| future::ok((state, res))).boxed()
}
}

View file

@ -105,7 +105,7 @@ extern crate self as gotham_restful;
#[macro_use] extern crate serde;
#[doc(no_inline)]
pub use hyper::{header::HeaderName, Chunk, StatusCode};
pub use gotham::hyper::{header::HeaderName, StatusCode};
#[doc(no_inline)]
pub use mime::Mime;
@ -115,8 +115,10 @@ pub use gotham_restful_derive::*;
#[doc(hidden)]
pub mod export
{
pub use futures::future::Future;
pub use gotham::state::{FromState, State};
pub use gotham::{
hyper::body::Bytes,
state::{FromState, State}
};
#[cfg(feature = "database")]
pub use gotham_middleware_diesel::Repo;

View file

@ -6,7 +6,7 @@ use crate::{
OpenapiType,
RequestBody
};
use futures::future::ok;
use futures_util::{future, future::FutureExt};
use gotham::{
handler::{Handler, HandlerFuture, NewHandler},
helpers::http::response::create_response,
@ -22,7 +22,10 @@ use openapiv3::{
ReferenceOr, ReferenceOr::Item, ReferenceOr::Reference, RequestBody as OARequestBody, Response, Responses, Schema,
SchemaKind, SecurityScheme, Server, StatusCode, Type
};
use std::panic::RefUnwindSafe;
use std::{
panic::RefUnwindSafe,
pin::Pin
};
/**
This type is required to build routes while adding them to the generated OpenAPI Spec at the
@ -175,7 +178,7 @@ fn get_security(state : &mut State) -> (Vec<SecurityRequirement>, IndexMap<Strin
impl Handler for OpenapiHandler
{
fn handle(self, mut state : State) -> Box<HandlerFuture>
fn handle(self, mut state : State) -> Pin<Box<HandlerFuture>>
{
let mut openapi = self.0;
let security_schemes = get_security(&mut state);
@ -186,12 +189,12 @@ impl Handler for OpenapiHandler
match serde_json::to_string(&openapi) {
Ok(body) => {
let res = create_response(&state, hyper::StatusCode::OK, APPLICATION_JSON, body);
Box::new(ok((state, res)))
future::ok((state, res)).boxed()
},
Err(e) => {
error!("Unable to handle OpenAPI request due to error: {}", e);
let res = create_response(&state, hyper::StatusCode::INTERNAL_SERVER_ERROR, TEXT_PLAIN, "");
Box::new(ok((state, res)))
future::ok((state, res)).boxed()
}
}
}

View file

@ -1,7 +1,7 @@
use crate::{ResponseBody, StatusCode};
#[cfg(feature = "openapi")]
use crate::{OpenapiSchema, OpenapiType};
use hyper::Body;
use gotham::hyper::Body;
#[cfg(feature = "errorlog")]
use log::error;
use mime::{Mime, APPLICATION_JSON, STAR_STAR};
@ -65,12 +65,13 @@ impl Response
}
#[cfg(test)]
fn full_body(self) -> Vec<u8>
fn full_body(mut self) -> Result<Vec<u8>, <Body as gotham::hyper::body::HttpBody>::Error>
{
use futures::{future::Future, stream::Stream};
use futures_executor::block_on;
use gotham::hyper::body::to_bytes;
let bytes : &[u8] = &self.body.concat2().wait().unwrap().into_bytes();
bytes.to_vec()
let bytes : &[u8] = &block_on(to_bytes(&mut self.body))?;
Ok(bytes.to_vec())
}
}
@ -532,7 +533,7 @@ mod test
let res = ok.into_response().expect("didn't expect error response");
assert_eq!(res.status, StatusCode::OK);
assert_eq!(res.mime, Some(APPLICATION_JSON));
assert_eq!(res.full_body(), r#"{"msg":""}"#.as_bytes());
assert_eq!(res.full_body().unwrap(), r#"{"msg":""}"#.as_bytes());
}
#[test]
@ -542,7 +543,7 @@ mod test
let res = err.into_response().expect("didn't expect error response");
assert_eq!(res.status, StatusCode::INTERNAL_SERVER_ERROR);
assert_eq!(res.mime, Some(APPLICATION_JSON));
assert_eq!(res.full_body(), format!(r#"{{"error":true,"message":"{}"}}"#, MsgError::default()).as_bytes());
assert_eq!(res.full_body().unwrap(), format!(r#"{{"error":true,"message":"{}"}}"#, MsgError::default()).as_bytes());
}
#[test]
@ -552,7 +553,7 @@ mod test
let res = success.into_response().expect("didn't expect error response");
assert_eq!(res.status, StatusCode::OK);
assert_eq!(res.mime, Some(APPLICATION_JSON));
assert_eq!(res.full_body(), r#"{"msg":""}"#.as_bytes());
assert_eq!(res.full_body().unwrap(), r#"{"msg":""}"#.as_bytes());
}
#[test]
@ -562,7 +563,7 @@ mod test
let res = no_content.into_response().expect("didn't expect error response");
assert_eq!(res.status, StatusCode::NO_CONTENT);
assert_eq!(res.mime, None);
assert_eq!(res.full_body(), &[] as &[u8]);
assert_eq!(res.full_body().unwrap(), &[] as &[u8]);
}
#[test]
@ -572,7 +573,7 @@ mod test
let res = no_content.into_response().expect("didn't expect error response");
assert_eq!(res.status, StatusCode::NO_CONTENT);
assert_eq!(res.mime, None);
assert_eq!(res.full_body(), &[] as &[u8]);
assert_eq!(res.full_body().unwrap(), &[] as &[u8]);
}
#[test]
@ -583,6 +584,6 @@ mod test
let res = raw.into_response().expect("didn't expect error response");
assert_eq!(res.status, StatusCode::OK);
assert_eq!(res.mime, Some(TEXT_PLAIN));
assert_eq!(res.full_body(), msg.as_bytes());
assert_eq!(res.full_body().unwrap(), msg.as_bytes());
}
}

View file

@ -7,12 +7,9 @@ use crate::{
#[cfg(feature = "openapi")]
use crate::OpenapiRouter;
use futures::{
future::{Future, err, ok},
stream::Stream
};
use futures_util::{future, future::FutureExt};
use gotham::{
handler::{HandlerFuture, IntoHandlerError},
handler::{HandlerFuture, IntoHandlerError, IntoHandlerFuture},
helpers::http::response::{create_empty_response, create_response},
pipeline::chain::PipelineHandleChain,
router::{
@ -26,14 +23,18 @@ use gotham::{
},
state::{FromState, State}
};
use hyper::{
use gotham::hyper::{
body::to_bytes,
header::CONTENT_TYPE,
Body,
HeaderMap,
Method
};
use mime::{Mime, APPLICATION_JSON};
use std::panic::RefUnwindSafe;
use std::{
panic::RefUnwindSafe,
pin::Pin
};
/// Allow us to extract an id from a path.
#[derive(Deserialize, StateData, StaticResponseExtender)]
@ -88,7 +89,7 @@ fn response_from(res : Response, state : &State) -> hyper::Response<Body>
r
}
fn to_handler_future<F, R>(mut state : State, get_result : F) -> Box<HandlerFuture>
fn to_handler_future<F, R>(mut state : State, get_result : F) -> Pin<Box<HandlerFuture>>
where
F : FnOnce(&mut State) -> R,
R : ResourceResult
@ -97,32 +98,31 @@ where
match res {
Ok(res) => {
let r = response_from(res, &state);
Box::new(ok((state, r)))
(state, r).into_handler_future()
},
Err(e) => Box::new(err((state, e.into_handler_error())))
Err(e) => future::err((state, e.into_handler_error())).boxed()
}
}
fn handle_with_body<Body, F, R>(mut state : State, get_result : F) -> Box<HandlerFuture>
fn handle_with_body<Body, F, R>(mut state : State, get_result : F) -> Pin<Box<HandlerFuture>>
where
Body : RequestBody,
F : FnOnce(&mut State, Body) -> R + Send + 'static,
R : ResourceResult
{
let f = hyper::Body::take_from(&mut state)
.concat2()
let f = to_bytes(gotham::hyper::Body::take_from(&mut state))
.then(|body| {
let body = match body {
Ok(body) => body,
Err(e) => return err((state, e.into_handler_error()))
Err(e) => return future::err((state, e.into_handler_error()))
};
let content_type : Mime = match HeaderMap::borrow_from(&state).get(CONTENT_TYPE) {
Some(content_type) => content_type.to_str().unwrap().parse().unwrap(),
None => {
let res = create_empty_response(&state, StatusCode::UNSUPPORTED_MEDIA_TYPE);
return ok((state, res))
return future::ok((state, res))
}
};
@ -133,9 +133,9 @@ where
match serde_json::to_string(&error) {
Ok(json) => {
let res = create_response(&state, StatusCode::BAD_REQUEST, APPLICATION_JSON, json);
ok((state, res))
future::ok((state, res))
},
Err(e) => err((state, e.into_handler_error()))
Err(e) => future::err((state, e.into_handler_error()))
}
}
};
@ -144,22 +144,22 @@ where
match res {
Ok(res) => {
let r = response_from(res, &state);
ok((state, r))
future::ok((state, r))
},
Err(e) => err((state, e.into_handler_error()))
Err(e) => future::err((state, e.into_handler_error()))
}
});
Box::new(f)
f.boxed()
}
fn read_all_handler<Handler : ResourceReadAll>(state : State) -> Box<HandlerFuture>
fn read_all_handler<Handler : ResourceReadAll>(state : State) -> Pin<Box<HandlerFuture>>
{
to_handler_future(state, |state| Handler::read_all(state))
}
fn read_handler<Handler : ResourceRead>(state : State) -> Box<HandlerFuture>
fn read_handler<Handler : ResourceRead>(state : State) -> Pin<Box<HandlerFuture>>
{
let id = {
let path : &PathExtractor<Handler::ID> = PathExtractor::borrow_from(&state);
@ -168,23 +168,23 @@ fn read_handler<Handler : ResourceRead>(state : State) -> Box<HandlerFuture>
to_handler_future(state, |state| Handler::read(state, id))
}
fn search_handler<Handler : ResourceSearch>(mut state : State) -> Box<HandlerFuture>
fn search_handler<Handler : ResourceSearch>(mut state : State) -> Pin<Box<HandlerFuture>>
{
let query = Handler::Query::take_from(&mut state);
to_handler_future(state, |state| Handler::search(state, query))
}
fn create_handler<Handler : ResourceCreate>(state : State) -> Box<HandlerFuture>
fn create_handler<Handler : ResourceCreate>(state : State) -> Pin<Box<HandlerFuture>>
{
handle_with_body::<Handler::Body, _, _>(state, |state, body| Handler::create(state, body))
}
fn update_all_handler<Handler : ResourceUpdateAll>(state : State) -> Box<HandlerFuture>
fn update_all_handler<Handler : ResourceUpdateAll>(state : State) -> Pin<Box<HandlerFuture>>
{
handle_with_body::<Handler::Body, _, _>(state, |state, body| Handler::update_all(state, body))
}
fn update_handler<Handler : ResourceUpdate>(state : State) -> Box<HandlerFuture>
fn update_handler<Handler : ResourceUpdate>(state : State) -> Pin<Box<HandlerFuture>>
{
let id = {
let path : &PathExtractor<Handler::ID> = PathExtractor::borrow_from(&state);
@ -193,12 +193,12 @@ fn update_handler<Handler : ResourceUpdate>(state : State) -> Box<HandlerFuture>
handle_with_body::<Handler::Body, _, _>(state, |state, body| Handler::update(state, id, body))
}
fn delete_all_handler<Handler : ResourceDeleteAll>(state : State) -> Box<HandlerFuture>
fn delete_all_handler<Handler : ResourceDeleteAll>(state : State) -> Pin<Box<HandlerFuture>>
{
to_handler_future(state, |state| Handler::delete_all(state))
}
fn delete_handler<Handler : ResourceDelete>(state : State) -> Box<HandlerFuture>
fn delete_handler<Handler : ResourceDelete>(state : State) -> Pin<Box<HandlerFuture>>
{
let id = {
let path : &PathExtractor<Handler::ID> = PathExtractor::borrow_from(&state);

View file

@ -2,7 +2,7 @@
use crate::OpenapiType;
use crate::result::ResourceError;
use hyper::Chunk;
use gotham::hyper::body::Bytes;
use mime::{Mime, APPLICATION_JSON};
use serde::{de::DeserializeOwned, Serialize};
@ -46,14 +46,14 @@ pub trait FromBody : Sized
type Err : Into<ResourceError>;
/// Create the request body from a raw body and the content type.
fn from_body(body : Chunk, content_type : Mime) -> Result<Self, Self::Err>;
fn from_body(body : Bytes, content_type : Mime) -> Result<Self, Self::Err>;
}
impl<T : DeserializeOwned> FromBody for T
{
type Err = serde_json::Error;
fn from_body(body : Chunk, _content_type : Mime) -> Result<Self, Self::Err>
fn from_body(body : Bytes, _content_type : Mime) -> Result<Self, Self::Err>
{
serde_json::from_slice(&body)
}

View file

@ -58,7 +58,7 @@ fn expand(tokens : TokenStream) -> Result<TokenStream2, Error>
{
type Err = String;
fn from_body(body : #krate::Chunk, _content_type : #krate::Mime) -> Result<Self, Self::Err>
fn from_body(body : #krate::export::Bytes, _content_type : #krate::Mime) -> Result<Self, Self::Err>
{
let body : &[u8] = &body;
Ok(#body)

View file

@ -435,7 +435,7 @@ fn expand(method : Method, attrs : TokenStream, item : TokenStream) -> Result<To
fn #method_ident(#(#args_def),*) -> #ret
{
#[allow(unused_imports)]
use #krate::export::{Future, FromState};
use #krate::export::FromState;
#block
}