From 9bd9ca519cd61f6f571ab26ca4accb97d0e14f91 Mon Sep 17 00:00:00 2001 From: Samir Gondzetovic Date: Sun, 28 Jan 2018 12:23:51 +0000 Subject: [PATCH] add file download endpoint --- src/permissions/index.js | 1 + src/routes/attachments/download.js | 46 ++++++++++++++++++++++++++++++ src/routes/index.js | 1 + 3 files changed, 48 insertions(+) create mode 100644 src/routes/attachments/download.js diff --git a/src/permissions/index.js b/src/permissions/index.js index f8563d6a..bf19b40b 100644 --- a/src/permissions/index.js +++ b/src/permissions/index.js @@ -19,5 +19,6 @@ module.exports = () => { Authorizer.setPolicy('project.addAttachment', projectEdit); Authorizer.setPolicy('project.updateAttachment', projectEdit); Authorizer.setPolicy('project.removeAttachment', projectEdit); + Authorizer.setPolicy('project.downloadAttachment', projectView); Authorizer.setPolicy('project.updateMember', projectEdit); }; diff --git a/src/routes/attachments/download.js b/src/routes/attachments/download.js new file mode 100644 index 00000000..f226d520 --- /dev/null +++ b/src/routes/attachments/download.js @@ -0,0 +1,46 @@ + +import _ from 'lodash'; +import { middleware as tcMiddleware } from 'tc-core-library-js'; +import models from '../../models'; +import util from '../../util'; + +/** + * API to download a project attachment. + * + */ + +const permissions = tcMiddleware.permissions; + +module.exports = [ + permissions('project.downloadAttachment'), + (req, res, next) => { + const projectId = _.parseInt(req.params.projectId); + const attachmentId = _.parseInt(req.params.id); + + models.ProjectAttachment.findOne( + { + where: { + id: attachmentId, + projectId, + }, + }) + .then((attachment) => { + if (!attachment) { + const err = new Error('Record not found'); + err.status = 404; + return Promise.reject(err); + } + return util.getFileDownloadUrl(req, attachment.filePath); + }) + .then((result) => { + const url = result[1]; + res.status(200).json(util.wrapResponse(req.id, { url })); + }) + .catch((error) => { + req.log.error('Error fetching attachment', error); + const rerr = error; + rerr.status = rerr.status || 500; + next(rerr); + }); + }, +]; diff --git a/src/routes/index.js b/src/routes/index.js index 4932602c..f29c2872 100644 --- a/src/routes/index.js +++ b/src/routes/index.js @@ -48,6 +48,7 @@ router.route('/v4/projects/:projectId(\\d+)/members/:id(\\d+)') router.route('/v4/projects/:projectId(\\d+)/attachments') .post(require('./attachments/create')); router.route('/v4/projects/:projectId(\\d+)/attachments/:id(\\d+)') + .get(require('./attachments/download')) .patch(require('./attachments/update')) .delete(require('./attachments/delete'));