From ccd7798996a779b939c198e24440c53827c74089 Mon Sep 17 00:00:00 2001 From: Joe Biellik Date: Fri, 14 Aug 2020 00:22:49 +0100 Subject: [PATCH] Improve file handling --- controllers/pastes.js | 40 ++++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/controllers/pastes.js b/controllers/pastes.js index 5c9ef41..c99c4aa 100644 --- a/controllers/pastes.js +++ b/controllers/pastes.js @@ -41,12 +41,12 @@ module.exports = { async create(ctx) { ctx.set('Cache-Control', 'no-cache'); - // Request body - if (!ctx.request.body.paste && ctx.request.files) { - try { - // Request body, xxx - let path = Object.values(ctx.request.files)[0].path; + // File body + if (ctx.request.files && Object.keys(ctx.request.files).length > 0) { + // Request body, xxx + let path = Object.values(ctx.request.files)[0].path; + try { // Request body, paste=xxx if (ctx.request.files.paste) { path = ctx.request.files.paste.path; @@ -55,30 +55,21 @@ module.exports = { const data = await fs.readFile(path); const stat = await fs.lstat(path); - if (isBinaryFile(data, stat.size)) ctx.throw(); - - ctx.request.body.paste = data; + if (await isBinaryFile(data, stat.size)) ctx.throw('Binary file'); + ctx.request.body.paste = data.toString(); + } catch { + ctx.throw(400, 'Bad Paste Body'); + } finally { try { await fs.unlink(path); } catch { // Ignore } - } catch { - ctx.throw(400, 'Bad Paste Body'); } } - // Expiry multiplier - try { - if (ctx.request.body.expire && ctx.request.body.multiplier) { - ctx.request.body.expire *= ctx.request.body.multiplier; - } - } catch { - ctx.throw(400, 'Bad Paste Expiry'); - } - - // Raw request body + // Raw body if (typeof ctx.request.body === 'string') { ctx.request.body = { paste: ctx.request.body @@ -89,6 +80,15 @@ module.exports = { ctx.throw(400, 'No Paste Provided'); } + // Expiry multiplier + try { + if (ctx.request.body.expire && ctx.request.body.multiplier) { + ctx.request.body.expire *= ctx.request.body.multiplier; + } + } catch { + ctx.throw(400, 'Bad Paste Expiry'); + } + // /?expire=xxx if (!ctx.request.body.expire && ctx.query.expire) { ctx.request.body.expire = ctx.query.expire;