//! # Authentication middleware use std::future::{Future, ready, Ready}; use std::pin::Pin; use std::rc::Rc; use actix_identity::RequestIdentity; use actix_web::{dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform}, Error, HttpResponse}; use actix_web::body::EitherBody; // There are two steps in middleware processing. // 1. Middleware initialization, middleware factory gets called with // next service in chain as parameter. // 2. Middleware's call method gets called with normal request. pub struct AuthMiddleware; // Middleware factory is `Transform` trait // `S` - type of the next service // `B` - type of response's body impl Transform for AuthMiddleware where S: Service, Error=Error> + 'static, S::Future: 'static, B: 'static, { type Response = ServiceResponse>; type Error = Error; type Transform = AuthInnerMiddleware; type InitError = (); type Future = Ready>; fn new_transform(&self, service: S) -> Self::Future { ready(Ok(AuthInnerMiddleware { service: Rc::new(service) })) } } #[derive(Debug)] enum SessionStatus { SignedOut, RegularUser, Admin, } pub struct AuthInnerMiddleware { service: Rc, } impl Service for AuthInnerMiddleware where S: Service, Error=Error> + 'static, S::Future: 'static, B: 'static, { type Response = ServiceResponse>; type Error = Error; #[allow(clippy::type_complexity)] type Future = Pin>>>; forward_ready!(service); fn call(&self, req: ServiceRequest) -> Self::Future { println!("Hi from start. You requested: {}", req.path()); let service = Rc::clone(&self.service); // Forward request Box::pin(async move { if req.path().starts_with("/.git") { return Ok(req.into_response( HttpResponse::Unauthorized() .body("Hey don't touch this!") .map_into_right_body() )); } let identity = req.get_identity(); println!("identity: {:?}", identity); service .call(req) .await .map(ServiceResponse::map_into_left_body) }) } }