use crate::Api; use futures::Future; use hyper; use hyper::header::HeaderName; use hyper::{body::Payload, service::Service, Error, Request, Response, StatusCode}; use std::default::Default; use std::io; use std::marker::PhantomData; use swagger::auth::{AuthData, Authorization, Bearer, Scopes}; use swagger::context::ContextualPayload; use swagger::{EmptyContext, Has, Pop, Push, XSpanIdString}; use url::form_urlencoded; pub struct MakeAddContext { inner: T, marker: PhantomData, } impl MakeAddContext where A: Default + Push, B: Push, Result = C>, C: Push, Result = D>, { pub fn new(inner: T) -> MakeAddContext { MakeAddContext { inner, marker: PhantomData, } } } // Make a service that adds context. impl<'a, T, SC, A, B, C, D, E, ME, S, OB, F> hyper::service::MakeService<&'a SC> for MakeAddContext where A: Default + Push, B: Push, Result = C>, C: Push, Result = D>, D: Send + 'static, T: hyper::service::MakeService< &'a SC, Error = E, MakeError = ME, Service = S, ReqBody = ContextualPayload, ResBody = OB, Future = F, >, S: Service, ResBody = OB> + 'static, ME: swagger::ErrorBound, E: swagger::ErrorBound, F: Future + Send + 'static, S::Future: Send, OB: Payload, { type ReqBody = hyper::Body; type ResBody = OB; type Error = E; type MakeError = ME; type Service = AddContext; type Future = Box + Send + 'static>; fn make_service(&mut self, ctx: &'a SC) -> Self::Future { Box::new(self.inner.make_service(ctx).map(|s| AddContext::new(s))) } } /// Middleware to extract authentication data from request pub struct AddContext { inner: T, marker: PhantomData, } impl AddContext where A: Default + Push, B: Push, Result = C>, C: Push, Result = D>, T: Service, { pub fn new(inner: T) -> AddContext { AddContext { inner, marker: PhantomData, } } } impl Service for AddContext where A: Default + Push, B: Push, Result = C>, C: Push, Result = D>, D: Send + 'static, T: Service>, T::Future: Future, Error = T::Error> + Send + 'static, { type ReqBody = hyper::Body; type ResBody = T::ResBody; type Error = T::Error; type Future = Box, Error = T::Error> + Send + 'static>; fn call(&mut self, req: Request) -> Self::Future { let context = A::default().push(XSpanIdString::get_or_generate(&req)); let (head, body) = req.into_parts(); let headers = head.headers.clone(); { use std::ops::Deref; use swagger::auth::Basic; if let Some(basic) = swagger::auth::from_headers::(&headers) { let auth_data = AuthData::Basic(basic); let context = context.push(Some(auth_data)); let context = context.push(None::); let body = ContextualPayload { inner: body, context: context, }; return Box::new(self.inner.call(hyper::Request::from_parts(head, body))); } } let context = context.push(None::); let context = context.push(None::); let body = ContextualPayload { inner: body, context: context, }; Box::new(self.inner.call(hyper::Request::from_parts(head, body))) } }