diff --git a/lib/plugin.js b/lib/plugin.js index acfe93d8..1ad7b1c6 100644 --- a/lib/plugin.js +++ b/lib/plugin.js @@ -2,7 +2,6 @@ const cds = require("@sap/cds/lib") const LOG = cds.log("attachments") const { extname } = require("path") const DEBUG = LOG._debug ? LOG.debug : undefined -const attachmentIDRegex = /\/\w+\(.*ID=([0-9a-fA-F-]{36})/ cds.on(cds.version >= "8.6.0" ? "compile.to.edmx" : "loaded", unfoldModel); function unfoldModel (csn) { @@ -82,35 +81,46 @@ cds.once("served", async function registerPluginHandlers () { /* removing case condition for mediaType annotation as in our case binary value and metadata is stored in different database */ req?.query?.SELECT?.columns?.forEach((element) => { - if (element.as === 'content@odata.mediaContentType' && element.xpr) { - delete element.xpr - element.ref = ['mimeType'] - } - }) - - if (req?.req?.url?.endsWith("/content")) { - const attachmentID = req.req.url.match(attachmentIDRegex)[1] - const status = await AttachmentsSrv.getStatus(req.target, { ID: attachmentID }) - const scanEnabled = cds.env.requires?.attachments?.scan ?? true - if (scanEnabled && status !== 'Clean') { - req.reject(403, 'Unable to download the attachment as scan status is not clean.') - } + if (element.as === 'content@odata.mediaContentType' && element.xpr) { + delete element.xpr; + element.ref = ['mimeType']; } + }); + + if (req?.req?.url?.endsWith("/content")) { + const attachmentKey = req.params?.[1]; + if (!attachmentKey?.ID) return req.reject(400, 'Missing attachment key in request'); + const status = await AttachmentsSrv.getStatus(req.target, attachmentKey); + const scanEnabled = cds.env.requires?.attachments?.scan ?? true; + if (scanEnabled && status !== 'Clean') { + req.reject(403, 'Unable to download the attachment as scan status is not clean.'); + } + } } async function readAttachment ([attachment], req) { if (!req?.req?.url?.endsWith("/content") || !attachment || attachment?.content) return - let keys = { ID: req.req.url.match(attachmentIDRegex)[1] } + const keys = req.params?.[1]; + if (!keys) return; let { target } = req attachment.content = await AttachmentsSrv.get(target, keys, req) //Dependency -> sending req object for usage in SDM plugin } async function nonDraftUpload(req, target) { - if (req?.content?.url?.endsWith("/content")) { - const attachmentID = req.content.url.match(attachmentIDRegex)[1]; - AttachmentsSrv.nonDraftHandler(target, { ID: attachmentID, content: req.content }); - } - } + try { + if (req?.content?.url?.endsWith("/content")) { + const attachmentID = req.params?.[1]?.ID; + if (!attachmentID) return req.reject(400, 'Missing attachment key in URL'); + await AttachmentsSrv.nonDraftHandler(target, { + ID: attachmentID, + content: req.content + }); + } + } catch (err) { + LOG.error('[NON_DRAFT_UPLOAD_ERROR]', err); + throw Object.assign(new Error('Non-draft attachment upload failed.'), { statusCode: 500 }); + } + } }) function validateAttachmentSize (req) {