From f96208a0c80a65ec498a8f802acc1abffe7029e0 Mon Sep 17 00:00:00 2001 From: Julian Lam Date: Tue, 13 Nov 2018 13:56:21 -0500 Subject: [PATCH] fix(uploads): ugly filenames on uploaded asset downloading During regular processing, a timestamp is prepended to the filename for any uploaded files. We don't want this to be part of the filename if an end-user elects to download the file. This commit adds a middleware to strip out that portion of the basename and adds the appropriate Content-Disposition header for files in /uploads/files Fixes #6953 --- src/middleware/index.js | 15 +++++++++++++++ src/routes/index.js | 2 +- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/middleware/index.js b/src/middleware/index.js index b0aaf3dbd4..4151dbbd26 100644 --- a/src/middleware/index.js +++ b/src/middleware/index.js @@ -28,6 +28,10 @@ var delayCache = LRU({ var middleware = module.exports; +middleware.regexes = { + timestampedUpload: /^\d+-.+$/, +}; + middleware.applyCSRF = csrf(); middleware.ensureLoggedIn = ensureLoggedIn.ensureLoggedIn(nconf.get('relative_path') + '/login'); @@ -218,3 +222,14 @@ middleware.buildSkinAsset = function (req, res, next) { setImmediate(next); } }; + +middleware.trimUploadTimestamps = (req, res, next) => { + // Check match + let basename = path.basename(req.path); + if (req.path.startsWith('/uploads/files/') && middleware.regexes.timestampedUpload.test(basename)) { + basename = basename.slice(14); + res.header('Content-Disposition', 'inline; filename="' + basename + '"'); + } + + return next(); +}; diff --git a/src/routes/index.js b/src/routes/index.js index d82c6b2b09..0d651db41f 100644 --- a/src/routes/index.js +++ b/src/routes/index.js @@ -159,7 +159,7 @@ module.exports = function (app, middleware, callback) { }); statics.forEach(function (obj) { - app.use(relativePath + obj.route, express.static(obj.path, staticOptions)); + app.use(relativePath + obj.route, middleware.trimUploadTimestamps, express.static(obj.path, staticOptions)); }); app.use(relativePath + '/uploads', function (req, res) { res.redirect(relativePath + '/assets/uploads' + req.path + '?' + meta.config['cache-buster']);