From 4f35b0d1265b5b839ae3c80d2e08c043e3f8432c Mon Sep 17 00:00:00 2001 From: francoischalifour Date: Sun, 5 Mar 2017 17:11:14 +0100 Subject: [PATCH] Partially check file size (#3) We need to totally abort the request when the file is too big. Right now, the server detects that case but it still uploads the file. --- api/v1/classify/Classify.controller.js | 12 ++++++++++-- api/v1/classify/index.js | 4 +++- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/api/v1/classify/Classify.controller.js b/api/v1/classify/Classify.controller.js index a9224d5..be30c26 100644 --- a/api/v1/classify/Classify.controller.js +++ b/api/v1/classify/Classify.controller.js @@ -5,6 +5,8 @@ const { APIError } = require('../../../helpers/error') const { createError } = require('../../../helpers/response') const { logger, modelDirectory, pythonPath } = require('../../../config') +const BIT_TO_BYTES = 1048576 +const MAX_FILE_SIZE = 10 * BIT_TO_BYTES const AUTHORIZED_FORMATS = ['jpg', 'jpeg'] module.exports = dependencies => { @@ -26,12 +28,19 @@ module.exports = dependencies => { return { * classify ({ request, response }) { + const { parts, contentLength } = request const { answer, abort } = response - const { parts } = request let filepath try { + if (contentLength > MAX_FILE_SIZE) { + const code = 413 + const message = `The file is too big (maximum size allowed is ${MAX_FILE_SIZE / BIT_TO_BYTES} MB).` + + throw new APIError({ code, message }) + } + const part = yield parts if (!part) { @@ -42,7 +51,6 @@ module.exports = dependencies => { } const { mime } = part - const [, format] = mime.split('/') if (!AUTHORIZED_FORMATS.includes(format)) { diff --git a/api/v1/classify/index.js b/api/v1/classify/index.js index 0a962c4..1c0125e 100644 --- a/api/v1/classify/index.js +++ b/api/v1/classify/index.js @@ -9,10 +9,12 @@ const Controller = require('./Classify.controller')({ router .post('/', function * (next) { const parts = parse(this) + const contentLength = this.request.header['content-length'] yield Controller.classify({ request: { - parts + parts, + contentLength }, response: { answer: data => (this.body = data),