//! # 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; use crate::constants::{ADMIN_ROUTES, AUTHENTICATED_ROUTES, LOGIN_ROUTE}; use crate::controllers::base_controller::redirect_user; use crate::data::session_identity::{SessionIdentity, SessionIdentityData}; // 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, } impl SessionStatus { pub fn is_auth(&self) -> bool { !matches!(self, SessionStatus::SignedOut) } pub fn is_admin(&self) -> bool { matches!(self, SessionStatus::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 { 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 = match SessionIdentity::deserialize_session_data(req.get_identity()) { None => SessionStatus::SignedOut, Some(SessionIdentityData { is_admin: true, .. }) => SessionStatus::Admin, _ => SessionStatus::RegularUser, }; // Redirect user to login page if !identity.is_auth() && (req.path().starts_with(ADMIN_ROUTES) || req.path().starts_with(AUTHENTICATED_ROUTES)) { return Ok(req.into_response(redirect_user(LOGIN_ROUTE)) .map_into_right_body()); } // TODO : restrict access to admin pages service .call(req) .await .map(ServiceResponse::map_into_left_body) }) } }