Last active
June 14, 2023 18:43
-
-
Save hasanparasteh/42b8c6b30fe3b0fbedf29feff44cb669 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::future::{ready, Ready}; | |
use actix_web::{ | |
body::EitherBody, | |
dev::{self, Service, ServiceRequest, ServiceResponse, Transform}, | |
web, Error, HttpResponse, | |
}; | |
use futures_util::future::LocalBoxFuture; | |
use crate::{types::GenericResponse, utils::is_request_length_valid}; | |
pub struct SarafLength; | |
impl<S: 'static, B> Transform<S, ServiceRequest> for SarafLength | |
where | |
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>, | |
S::Future: 'static, | |
B: 'static, | |
{ | |
type Response = ServiceResponse<EitherBody<B>>; | |
type Error = Error; | |
type InitError = (); | |
type Transform = SarafLengthMiddleware<S>; | |
type Future = Ready<Result<Self::Transform, Self::InitError>>; | |
fn new_transform(&self, service: S) -> Self::Future { | |
ready(Ok(SarafLengthMiddleware { service })) | |
} | |
} | |
pub struct SarafLengthMiddleware<S> { | |
service: S, | |
} | |
impl<S, B> Service<ServiceRequest> for SarafLengthMiddleware<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>>; | |
dev::forward_ready!(service); | |
fn call(&self, mut request: ServiceRequest) -> Self::Future { | |
Box::pin(async move { | |
let saraf_length = request.headers().get("saraf-length"); | |
if saraf_length.is_none() { | |
let (request, _pl) = request.into_parts(); | |
let response = HttpResponse::Unauthorized() | |
.json(GenericResponse { | |
result: false, | |
message: "saraf-length header is missing".to_string(), | |
}) | |
.map_into_right_body(); | |
return Ok(ServiceResponse::new(request, response)); | |
} | |
let saraf_length: u32 = saraf_length.unwrap().to_str().unwrap().parse().unwrap(); | |
let body = request.extract::<web::Bytes>(); | |
// TODO: How to await here? | |
if !is_request_length_valid(body.await.unwrap(), saraf_length) { | |
let (request, _pl) = request.into_parts(); | |
let response = HttpResponse::Unauthorized() | |
.json(GenericResponse { | |
result: false, | |
message: "saraf-length header is missing".to_string(), | |
}) | |
.map_into_right_body(); | |
return Ok(ServiceResponse::new(request, response)); | |
} | |
let res = self.service.call(request); | |
res.await.map(ServiceResponse::map_into_left_body) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment