Skip to content
This repository has been archived by the owner on Jul 17, 2023. It is now read-only.

Commit

Permalink
Add limited raw payload
Browse files Browse the repository at this point in the history
  • Loading branch information
untoldwind committed Dec 4, 2018
1 parent af1c937 commit 639b7ce
Showing 1 changed file with 52 additions and 5 deletions.
57 changes: 52 additions & 5 deletions src/parse_request.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,22 @@
use super::AsyncBusinessResult;
use actix_web::dev::JsonBody;
use actix_web::dev::{JsonBody, MessageBody};
use actix_web::{FromRequest, HttpMessage, HttpRequest};
use bytes::Bytes;
use futures::{Future, IntoFuture};
use problem::Problem;
use serde::de::DeserializeOwned;
use std::fmt;
use std::ops::Deref;

const JSON_REQUEST_LIMIT: usize = 1024 * 1024;
pub struct ValidatedJsonConfig {
limit: usize,
}

impl Default for ValidatedJsonConfig {
fn default() -> Self {
ValidatedJsonConfig { limit: 1024 * 1024 }
}
}

pub struct ValidatedJson<T>(pub T);

Expand Down Expand Up @@ -49,14 +58,14 @@ where
T: DeserializeOwned + 'static,
S: 'static,
{
type Config = ();
type Config = ValidatedJsonConfig;
type Result = Result<AsyncBusinessResult<Self>, Problem>;

#[inline]
fn from_request(req: &HttpRequest<S>, _cfg: &Self::Config) -> Self::Result {
fn from_request(req: &HttpRequest<S>, cfg: &Self::Config) -> Self::Result {
Ok(Box::new(
JsonBody::new(req)
.limit(JSON_REQUEST_LIMIT)
.limit(cfg.limit)
.map_err(|error| Problem::bad_request().with_details(format!("Invalid json: {}", error)))
.map(ValidatedJson),
))
Expand Down Expand Up @@ -89,3 +98,41 @@ macro_rules! request_parameter {
}
};
}

pub struct LimitedRawConfig {
limit: usize,
}

impl Default for LimitedRawConfig {
fn default() -> Self {
LimitedRawConfig { limit: 1024 * 1024 }
}
}

pub struct LimitedRaw(pub Bytes);

impl Deref for LimitedRaw {
type Target = Bytes;

fn deref(&self) -> &Bytes {
&self.0
}
}

impl<S> FromRequest<S> for LimitedRaw
where
S: 'static,
{
type Config = LimitedRawConfig;
type Result = Result<AsyncBusinessResult<Self>, Problem>;

#[inline]
fn from_request(req: &HttpRequest<S>, cfg: &Self::Config) -> Self::Result {
Ok(Box::new(
MessageBody::new(req)
.limit(cfg.limit)
.map_err(|error| Problem::bad_request().with_details(format!("Invalid body: {}", error)))
.map(LimitedRaw),
))
}
}

0 comments on commit 639b7ce

Please sign in to comment.