Reduce number of unwwaps in api crate (#2681)

* Reduce number of unwwaps in api crate

* Format use section
This commit is contained in:
hashmap
2019-03-18 19:34:35 +01:00
committed by GitHub
parent 2b218f2dc3
commit 7fad5b040f
17 changed files with 165 additions and 123 deletions
+16 -9
View File
@@ -13,19 +13,25 @@
// limitations under the License.
use crate::router::{Handler, HandlerObj, ResponseFuture};
use crate::web::response;
use futures::future::ok;
use hyper::header::{HeaderValue, AUTHORIZATION, WWW_AUTHENTICATE};
use hyper::{Body, Request, Response, StatusCode};
use ring::constant_time::verify_slices_are_equal;
lazy_static! {
pub static ref GRIN_BASIC_REALM: HeaderValue =
HeaderValue::from_str("Basic realm=GrinAPI").unwrap();
}
// Basic Authentication Middleware
pub struct BasicAuthMiddleware {
api_basic_auth: String,
basic_realm: String,
basic_realm: &'static HeaderValue,
}
impl BasicAuthMiddleware {
pub fn new(api_basic_auth: String, basic_realm: String) -> BasicAuthMiddleware {
pub fn new(api_basic_auth: String, basic_realm: &'static HeaderValue) -> BasicAuthMiddleware {
BasicAuthMiddleware {
api_basic_auth,
basic_realm,
@@ -39,8 +45,12 @@ impl Handler for BasicAuthMiddleware {
req: Request<Body>,
mut handlers: Box<dyn Iterator<Item = HandlerObj>>,
) -> ResponseFuture {
let next_handler = match handlers.next() {
Some(h) => h,
None => return response(StatusCode::INTERNAL_SERVER_ERROR, "no handler found"),
};
if req.method().as_str() == "OPTIONS" {
return handlers.next().unwrap().call(req, handlers);
return next_handler.call(req, handlers);
}
if req.headers().contains_key(AUTHORIZATION)
&& verify_slices_are_equal(
@@ -49,7 +59,7 @@ impl Handler for BasicAuthMiddleware {
)
.is_ok()
{
handlers.next().unwrap().call(req, handlers)
next_handler.call(req, handlers)
} else {
// Unauthorized 401
unauthorized_response(&self.basic_realm)
@@ -57,13 +67,10 @@ impl Handler for BasicAuthMiddleware {
}
}
fn unauthorized_response(basic_realm: &str) -> ResponseFuture {
fn unauthorized_response(basic_realm: &HeaderValue) -> ResponseFuture {
let response = Response::builder()
.status(StatusCode::UNAUTHORIZED)
.header(
WWW_AUTHENTICATE,
HeaderValue::from_str(basic_realm).unwrap(),
)
.header(WWW_AUTHENTICATE, basic_realm)
.body(Body::empty())
.unwrap();
Box::new(ok(response))