use actix_web::{ body::{EitherBody, MessageBody}, dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform}, Error, }; use futures::prelude::future::LocalBoxFuture; use std::future::{ready, Ready}; #[derive(Clone)] pub struct AuthService { pub token: String, } impl<S, B> Transform<S, ServiceRequest> for AuthService where S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static, B: MessageBody + 'static, { type Response = ServiceResponse<EitherBody<B>>; type Error = Error; type InitError = (); type Transform = AuthenticatedMiddleware<S>; type Future = Ready<Result<Self::Transform, Self::InitError>>; fn new_transform(&self, service: S) -> Self::Future { ready(Ok(AuthenticatedMiddleware { service: std::rc::Rc::new(service), auth: self.clone(), })) } } pub struct AuthenticatedMiddleware<S> { service: std::rc::Rc<S>, auth: AuthService, } async fn authenticate(req: &mut ServiceRequest, token: String) -> bool { let cookie = req.cookie("auth"); match cookie { Some(cookie) => return cookie.value().to_string().eq(&token), None => false, } } impl<S, B> Service<ServiceRequest> for AuthenticatedMiddleware<S> where S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static, B: MessageBody + 'static, { type Response = ServiceResponse<EitherBody<B>>; type Error = Error; type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; forward_ready!(service); fn call(&self, req: ServiceRequest) -> Self::Future { let service = self.service.clone(); let token = self.auth.token.to_owned(); Box::pin(async move { let mut req = req; if let false = authenticate(&mut req, token).await { return Ok(req.into_response( actix_web::HttpResponse::Unauthorized() .finish() .map_into_right_body(), )); } Ok(service.call(req).await?.map_into_left_body()) }) } }