use super::{AuthZ, Context};
use crate::auth::{UserInformation, ANONYMOUS};
use actix_http::body::EitherBody;
use actix_service::{Service, Transform};
use actix_web::{
dev::{ServiceRequest, ServiceResponse},
Error, HttpMessage,
};
use futures_util::future::{ok, LocalBoxFuture, Ready};
use std::rc::Rc;
pub struct AuthMiddleware<S> {
service: Rc<S>,
authorizer: AuthZ,
}
impl<S, B> Transform<S, ServiceRequest> for AuthZ
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
S::Future: 'static,
B: 'static,
{
type Response = ServiceResponse<EitherBody<B>>;
type Error = S::Error;
type Transform = AuthMiddleware<S>;
type InitError = ();
type Future = Ready<Result<Self::Transform, Self::InitError>>;
fn new_transform(&self, service: S) -> Self::Future {
ok(AuthMiddleware {
service: Rc::new(service),
authorizer: self.clone(),
})
}
}
impl<S, B> Service<ServiceRequest> for AuthMiddleware<S>
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
S::Future: 'static,
B: 'static,
{
type Response = ServiceResponse<EitherBody<B>>;
type Error = Error;
type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
actix_service::forward_ready!(service);
fn call(&self, req: ServiceRequest) -> Self::Future {
let srv = Rc::clone(&self.service);
let auth = self.authorizer.clone();
Box::pin(async move {
let result = {
let ext = req.extensions();
let identity = ext.get::<UserInformation>().unwrap_or(&ANONYMOUS);
let context = Context {
identity,
request: &req,
};
auth.authorize(context).await
};
match result {
Ok(()) => {
srv.call(req).await.map(|res| res.map_into_left_body())
}
Err(err) => {
log::debug!("Authorization error: {err}");
Ok(req.error_response(err).map_into_right_body())
}
}
})
}
}