Add middleware to check authentication

This commit is contained in:
2023-09-02 19:15:11 +02:00
parent 849bf0cdfb
commit caaf3d703f
7 changed files with 126 additions and 8 deletions

View File

@ -0,0 +1,95 @@
use std::future::{ready, Ready};
use std::rc::Rc;
use crate::constants;
use crate::extractors::auth_extractor::AuthExtractor;
use actix_web::body::EitherBody;
use actix_web::dev::Payload;
use actix_web::{
dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform},
Error, FromRequest, HttpResponse,
};
use futures_util::future::LocalBoxFuture;
// 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.
#[derive(Default)]
pub struct AuthChecker;
// Middleware factory is `Transform` trait
// `S` - type of the next service
// `B` - type of response's body
impl<S, B> Transform<S, ServiceRequest> for AuthChecker
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
S::Future: 'static,
B: 'static,
{
type Response = ServiceResponse<EitherBody<B>>;
type Error = Error;
type InitError = ();
type Transform = AuthMiddleware<S>;
type Future = Ready<Result<Self::Transform, Self::InitError>>;
fn new_transform(&self, service: S) -> Self::Future {
ready(Ok(AuthMiddleware {
service: Rc::new(service),
}))
}
}
pub struct AuthMiddleware<S> {
service: Rc<S>,
}
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>>;
forward_ready!(service);
fn call(&self, req: ServiceRequest) -> Self::Future {
let service = Rc::clone(&self.service);
Box::pin(async move {
// Check authentication, if required
if !constants::ROUTES_WITHOUT_AUTH.contains(&req.path()) {
let auth = match AuthExtractor::from_request(req.request(), &mut Payload::None)
.into_inner()
{
Ok(auth) => auth,
Err(e) => {
log::error!(
"Failed to extract authentication information from request! {e}"
);
return Ok(req
.into_response(HttpResponse::InternalServerError().finish())
.map_into_right_body());
}
};
if !auth.is_authenticated() {
log::error!(
"User attempted to access privileged route without authentication!"
);
return Ok(req
.into_response(HttpResponse::Unauthorized().json("Please authenticate!"))
.map_into_right_body());
}
}
service
.call(req)
.await
.map(ServiceResponse::map_into_left_body)
})
}
}