attachment.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  1. /* eslint-disable no-use-before-define */
  2. const logger = require('@alias/logger')('growi:routes:attachment');
  3. const ApiResponse = require('../util/apiResponse');
  4. /**
  5. * @swagger
  6. * tags:
  7. * name: Attachments
  8. */
  9. /**
  10. * @swagger
  11. *
  12. * components:
  13. * schemas:
  14. * Attachment:
  15. * description: Attachment
  16. * type: object
  17. * properties:
  18. * _id:
  19. * type: string
  20. * description: attachment ID
  21. * example: 5e0734e072560e001761fa67
  22. * __v:
  23. * type: number
  24. * description: attachment version
  25. * example: 0
  26. * fileFormat:
  27. * type: string
  28. * description: file format in MIME
  29. * example: text/plain
  30. * fileName:
  31. * type: string
  32. * description: file name
  33. * example: 601b7c59d43a042c0117e08dd37aad0aimage.txt
  34. * originalName:
  35. * type: string
  36. * description: original file name
  37. * example: file.txt
  38. * creator:
  39. * $ref: '#/components/schemas/User'
  40. * page:
  41. * type: string
  42. * description: page ID attached at
  43. * example: 5e07345972560e001761fa63
  44. * createdAt:
  45. * type: string
  46. * description: date created at
  47. * example: 2010-01-01T00:00:00.000Z
  48. * fileSize:
  49. * type: number
  50. * description: file size
  51. * example: 3494332
  52. * url:
  53. * type: string
  54. * description: attachment URL
  55. * example: http://localhost/files/5e0734e072560e001761fa67
  56. * filePathProxied:
  57. * type: string
  58. * description: file path proxied
  59. * example: "/attachment/5e0734e072560e001761fa67"
  60. * downloadPathProxied:
  61. * type: string
  62. * description: download path proxied
  63. * example: "/download/5e0734e072560e001761fa67"
  64. */
  65. /**
  66. * @swagger
  67. *
  68. * components:
  69. * schemas:
  70. * AttachmentProfile:
  71. * description: Attachment
  72. * type: object
  73. * properties:
  74. * id:
  75. * type: string
  76. * description: attachment ID
  77. * example: 5e0734e072560e001761fa67
  78. * _id:
  79. * type: string
  80. * description: attachment ID
  81. * example: 5e0734e072560e001761fa67
  82. * __v:
  83. * type: number
  84. * description: attachment version
  85. * example: 0
  86. * fileFormat:
  87. * type: string
  88. * description: file format in MIME
  89. * example: image/png
  90. * fileName:
  91. * type: string
  92. * description: file name
  93. * example: 601b7c59d43a042c0117e08dd37aad0a.png
  94. * originalName:
  95. * type: string
  96. * description: original file name
  97. * example: profile.png
  98. * creator:
  99. * $ref: '#/components/schemas/User/properties/_id'
  100. * page:
  101. * type: string
  102. * description: page ID attached at
  103. * example: null
  104. * createdAt:
  105. * type: string
  106. * description: date created at
  107. * example: 2010-01-01T00:00:00.000Z
  108. * fileSize:
  109. * type: number
  110. * description: file size
  111. * example: 3494332
  112. * filePathProxied:
  113. * type: string
  114. * description: file path proxied
  115. * example: "/attachment/5e0734e072560e001761fa67"
  116. * downloadPathProxied:
  117. * type: string
  118. * description: download path proxied
  119. * example: "/download/5e0734e072560e001761fa67"
  120. */
  121. module.exports = function(crowi, app) {
  122. const Attachment = crowi.model('Attachment');
  123. const Page = crowi.model('Page');
  124. const { fileUploadService, attachmentService } = crowi;
  125. /**
  126. * Check the user is accessible to the related page
  127. *
  128. * @param {User} user
  129. * @param {Attachment} attachment
  130. */
  131. async function isAccessibleByViewer(user, attachment) {
  132. if (attachment.page != null) {
  133. // eslint-disable-next-line no-return-await
  134. return await Page.isAccessiblePageByViewer(attachment.page, user);
  135. }
  136. return true;
  137. }
  138. /**
  139. * Check the user is accessible to the related page
  140. *
  141. * @param {User} user
  142. * @param {Attachment} attachment
  143. */
  144. async function isDeletableByUser(user, attachment) {
  145. const ownerId = attachment.creator._id || attachment.creator;
  146. if (attachment.page == null) { // when profile image
  147. return user.id === ownerId.toString();
  148. }
  149. // eslint-disable-next-line no-return-await
  150. return await Page.isAccessiblePageByViewer(attachment.page, user);
  151. }
  152. /**
  153. * Common method to response
  154. *
  155. * @param {Request} req
  156. * @param {Response} res
  157. * @param {User} user
  158. * @param {Attachment} attachment
  159. * @param {boolean} forceDownload
  160. */
  161. async function responseForAttachment(req, res, attachment, forceDownload) {
  162. if (attachment == null) {
  163. return res.json(ApiResponse.error('attachment not found'));
  164. }
  165. const user = req.user;
  166. const isAccessible = await isAccessibleByViewer(user, attachment);
  167. if (!isAccessible) {
  168. return res.json(ApiResponse.error(`Forbidden to access to the attachment '${attachment.id}'`));
  169. }
  170. // add headers before evaluating 'req.fresh'
  171. setHeaderToRes(res, attachment, forceDownload);
  172. // return 304 if request is "fresh"
  173. // see: http://expressjs.com/en/5x/api.html#req.fresh
  174. if (req.fresh) {
  175. return res.sendStatus(304);
  176. }
  177. if (fileUploadService.canRespond()) {
  178. return fileUploadService.respond(res, attachment);
  179. }
  180. let fileStream;
  181. try {
  182. fileStream = await fileUploadService.findDeliveryFile(attachment);
  183. }
  184. catch (e) {
  185. logger.error(e);
  186. return res.json(ApiResponse.error(e.message));
  187. }
  188. return fileStream.pipe(res);
  189. }
  190. /**
  191. * set http response header
  192. *
  193. * @param {Response} res
  194. * @param {Attachment} attachment
  195. * @param {boolean} forceDownload
  196. */
  197. function setHeaderToRes(res, attachment, forceDownload) {
  198. res.set({
  199. ETag: `Attachment-${attachment._id}`,
  200. 'Last-Modified': attachment.createdAt.toUTCString(),
  201. });
  202. // download
  203. if (forceDownload) {
  204. res.set({
  205. 'Content-Disposition': `attachment;filename*=UTF-8''${encodeURIComponent(attachment.originalName)}`,
  206. });
  207. }
  208. // reference
  209. else {
  210. res.set({
  211. 'Content-Type': attachment.fileFormat,
  212. 'Content-Security-Policy': "script-src 'unsafe-hashes'",
  213. });
  214. }
  215. }
  216. async function removeAttachment(attachmentId) {
  217. const { fileUploadService } = crowi;
  218. // retrieve data from DB to get a completely populated instance
  219. const attachment = await Attachment.findById(attachmentId);
  220. await fileUploadService.deleteFile(attachment);
  221. return attachment.remove();
  222. }
  223. const actions = {};
  224. const api = {};
  225. actions.api = api;
  226. api.download = async function(req, res) {
  227. const id = req.params.id;
  228. const attachment = await Attachment.findById(id);
  229. return responseForAttachment(req, res, attachment, true);
  230. };
  231. /**
  232. * @api {get} /attachments.get get attachments
  233. * @apiName get
  234. * @apiGroup Attachment
  235. *
  236. * @apiParam {String} id
  237. */
  238. api.get = async function(req, res) {
  239. const id = req.params.id;
  240. const attachment = await Attachment.findById(id);
  241. return responseForAttachment(req, res, attachment);
  242. };
  243. /**
  244. * @api {get} /attachments.obsoletedGetForMongoDB get attachments from mongoDB
  245. * @apiName get
  246. * @apiGroup Attachment
  247. *
  248. * @apiParam {String} pageId, fileName
  249. */
  250. api.obsoletedGetForMongoDB = async function(req, res) {
  251. if (process.env.FILE_UPLOAD !== 'mongodb') {
  252. return res.status(400);
  253. }
  254. const pageId = req.params.pageId;
  255. const fileName = req.params.fileName;
  256. const filePath = `attachment/${pageId}/${fileName}`;
  257. const attachment = await Attachment.findOne({ filePath });
  258. return responseForAttachment(req, res, attachment);
  259. };
  260. /**
  261. * @swagger
  262. *
  263. * /attachments.limit:
  264. * get:
  265. * tags: [Attachments]
  266. * operationId: getAttachmentsLimit
  267. * summary: /attachments.limit
  268. * description: Get available capacity of uploaded file with GridFS
  269. * parameters:
  270. * - in: query
  271. * name: fileSize
  272. * schema:
  273. * type: number
  274. * description: file size
  275. * example: 23175
  276. * required: true
  277. * responses:
  278. * 200:
  279. * description: Succeeded to get available capacity of uploaded file with GridFS.
  280. * content:
  281. * application/json:
  282. * schema:
  283. * properties:
  284. * isUploadable:
  285. * type: boolean
  286. * description: uploadable
  287. * example: true
  288. * ok:
  289. * $ref: '#/components/schemas/V1Response/properties/ok'
  290. * 403:
  291. * $ref: '#/components/responses/403'
  292. * 500:
  293. * $ref: '#/components/responses/500'
  294. */
  295. /**
  296. * @api {get} /attachments.limit get available capacity of uploaded file with GridFS
  297. * @apiName AddAttachments
  298. * @apiGroup Attachment
  299. */
  300. api.limit = async function(req, res) {
  301. const fileSize = Number(req.query.fileSize);
  302. return res.json(ApiResponse.success(await fileUploadService.checkLimit(fileSize)));
  303. };
  304. /**
  305. * @swagger
  306. *
  307. * /attachments.add:
  308. * post:
  309. * tags: [Attachments, CrowiCompatibles]
  310. * operationId: addAttachment
  311. * summary: /attachments.add
  312. * description: Add attachment to the page
  313. * requestBody:
  314. * content:
  315. * "multipart/form-data":
  316. * schema:
  317. * properties:
  318. * page_id:
  319. * nullable: true
  320. * type: string
  321. * path:
  322. * nullable: true
  323. * type: string
  324. * file:
  325. * type: string
  326. * format: binary
  327. * description: attachment data
  328. * encoding:
  329. * path:
  330. * contentType: application/x-www-form-urlencoded
  331. * "*\/*":
  332. * schema:
  333. * properties:
  334. * page_id:
  335. * nullable: true
  336. * type: string
  337. * path:
  338. * nullable: true
  339. * type: string
  340. * file:
  341. * type: string
  342. * format: binary
  343. * description: attachment data
  344. * encoding:
  345. * path:
  346. * contentType: application/x-www-form-urlencoded
  347. * responses:
  348. * 200:
  349. * description: Succeeded to add attachment.
  350. * content:
  351. * application/json:
  352. * schema:
  353. * properties:
  354. * ok:
  355. * $ref: '#/components/schemas/V1Response/properties/ok'
  356. * page:
  357. * $ref: '#/components/schemas/Page'
  358. * attachment:
  359. * $ref: '#/components/schemas/Attachment'
  360. * url:
  361. * $ref: '#/components/schemas/Attachment/properties/url'
  362. * pageCreated:
  363. * type: boolean
  364. * description: whether the page was created
  365. * example: false
  366. * 403:
  367. * $ref: '#/components/responses/403'
  368. * 500:
  369. * $ref: '#/components/responses/500'
  370. */
  371. /**
  372. * @api {post} /attachments.add Add attachment to the page
  373. * @apiName AddAttachments
  374. * @apiGroup Attachment
  375. *
  376. * @apiParam {String} page_id
  377. * @apiParam {File} file
  378. */
  379. api.add = async function(req, res) {
  380. let pageId = req.body.page_id || null;
  381. const pagePath = req.body.path || null;
  382. let pageCreated = false;
  383. // check params
  384. if (pageId == null && pagePath == null) {
  385. return res.json(ApiResponse.error('Either page_id or path is required.'));
  386. }
  387. if (!req.file) {
  388. return res.json(ApiResponse.error('File error.'));
  389. }
  390. const file = req.file;
  391. let page;
  392. if (pageId == null) {
  393. logger.debug('Create page before file upload');
  394. page = await Page.create(pagePath, `# ${pagePath}`, req.user, { grant: Page.GRANT_OWNER });
  395. pageCreated = true;
  396. pageId = page._id;
  397. }
  398. else {
  399. page = await Page.findById(pageId);
  400. // check the user is accessible
  401. const isAccessible = await Page.isAccessiblePageByViewer(page.id, req.user);
  402. if (!isAccessible) {
  403. return res.json(ApiResponse.error(`Forbidden to access to the page '${page.id}'`));
  404. }
  405. }
  406. let attachment;
  407. try {
  408. attachment = await attachmentService.createAttachment(file, req.user, pageId);
  409. }
  410. catch (err) {
  411. logger.error(err);
  412. return res.json(ApiResponse.error(err.message));
  413. }
  414. const result = {
  415. page: page.toObject(),
  416. attachment: attachment.toObject({ virtuals: true }),
  417. pageCreated,
  418. };
  419. return res.json(ApiResponse.success(result));
  420. };
  421. /**
  422. * @swagger
  423. *
  424. * /attachments.uploadProfileImage:
  425. * post:
  426. * tags: [Attachments]
  427. * operationId: uploadProfileImage
  428. * summary: /attachments.uploadProfileImage
  429. * description: Upload profile image
  430. * requestBody:
  431. * content:
  432. * "multipart/form-data":
  433. * schema:
  434. * properties:
  435. * file:
  436. * type: string
  437. * format: binary
  438. * description: attachment data
  439. * user:
  440. * type: string
  441. * description: user to set profile image
  442. * encoding:
  443. * path:
  444. * contentType: application/x-www-form-urlencoded
  445. * "*\/*":
  446. * schema:
  447. * properties:
  448. * file:
  449. * type: string
  450. * format: binary
  451. * description: attachment data
  452. * user:
  453. * type: string
  454. * description: user to set profile
  455. * encoding:
  456. * path:
  457. * contentType: application/x-www-form-urlencoded
  458. * responses:
  459. * 200:
  460. * description: Succeeded to add attachment.
  461. * content:
  462. * application/json:
  463. * schema:
  464. * properties:
  465. * ok:
  466. * $ref: '#/components/schemas/V1Response/properties/ok'
  467. * attachment:
  468. * $ref: '#/components/schemas/AttachmentProfile'
  469. * 403:
  470. * $ref: '#/components/responses/403'
  471. * 500:
  472. * $ref: '#/components/responses/500'
  473. */
  474. /**
  475. * @api {post} /attachments.uploadProfileImage Add attachment for profile image
  476. * @apiName UploadProfileImage
  477. * @apiGroup Attachment
  478. *
  479. * @apiParam {File} file
  480. */
  481. api.uploadProfileImage = async function(req, res) {
  482. // check params
  483. if (!req.file) {
  484. return res.json(ApiResponse.error('File error.'));
  485. }
  486. if (!req.user) {
  487. return res.json(ApiResponse.error('param "user" must be set.'));
  488. }
  489. const file = req.file;
  490. // check type
  491. const acceptableFileType = /image\/.+/;
  492. if (!file.mimetype.match(acceptableFileType)) {
  493. return res.json(ApiResponse.error('File type error. Only image files is allowed to set as user picture.'));
  494. }
  495. let attachment;
  496. try {
  497. req.user.deleteImage();
  498. attachment = await attachmentService.createAttachment(file, req.user);
  499. await req.user.updateImage(attachment);
  500. }
  501. catch (err) {
  502. logger.error(err);
  503. return res.json(ApiResponse.error(err.message));
  504. }
  505. const result = {
  506. attachment: attachment.toObject({ virtuals: true }),
  507. };
  508. return res.json(ApiResponse.success(result));
  509. };
  510. /**
  511. * @swagger
  512. *
  513. * /attachments.remove:
  514. * post:
  515. * tags: [Attachments, CrowiCompatibles]
  516. * operationId: removeAttachment
  517. * summary: /attachments.remove
  518. * description: Remove attachment
  519. * requestBody:
  520. * content:
  521. * application/json:
  522. * schema:
  523. * properties:
  524. * attachment_id:
  525. * $ref: '#/components/schemas/Attachment/properties/_id'
  526. * required:
  527. * - attachment_id
  528. * responses:
  529. * 200:
  530. * description: Succeeded to remove attachment.
  531. * content:
  532. * application/json:
  533. * schema:
  534. * properties:
  535. * ok:
  536. * $ref: '#/components/schemas/V1Response/properties/ok'
  537. * 403:
  538. * $ref: '#/components/responses/403'
  539. * 500:
  540. * $ref: '#/components/responses/500'
  541. */
  542. /**
  543. * @api {post} /attachments.remove Remove attachments
  544. * @apiName RemoveAttachments
  545. * @apiGroup Attachment
  546. *
  547. * @apiParam {String} attachment_id
  548. */
  549. api.remove = async function(req, res) {
  550. const id = req.body.attachment_id;
  551. const attachment = await Attachment.findById(id);
  552. if (attachment == null) {
  553. return res.json(ApiResponse.error('attachment not found'));
  554. }
  555. const isDeletable = await isDeletableByUser(req.user, attachment);
  556. if (!isDeletable) {
  557. return res.json(ApiResponse.error(`Forbidden to remove the attachment '${attachment.id}'`));
  558. }
  559. try {
  560. await removeAttachment(attachment);
  561. }
  562. catch (err) {
  563. logger.error(err);
  564. return res.status(500).json(ApiResponse.error('Error while deleting file'));
  565. }
  566. return res.json(ApiResponse.success({}));
  567. };
  568. /**
  569. * @swagger
  570. *
  571. * /attachments.removeProfileImage:
  572. * post:
  573. * tags: [Attachments]
  574. * operationId: removeProfileImage
  575. * summary: /attachments.removeProfileImage
  576. * description: Remove profile image
  577. * requestBody:
  578. * content:
  579. * application/json:
  580. * schema:
  581. * properties:
  582. * user:
  583. * type: string
  584. * description: user to remove profile image
  585. * responses:
  586. * 200:
  587. * description: Succeeded to add attachment.
  588. * content:
  589. * application/json:
  590. * schema:
  591. * properties:
  592. * ok:
  593. * $ref: '#/components/schemas/V1Response/properties/ok'
  594. * 403:
  595. * $ref: '#/components/responses/403'
  596. * 500:
  597. * $ref: '#/components/responses/500'
  598. */
  599. /**
  600. * @api {post} /attachments.removeProfileImage Remove profile image attachments
  601. * @apiGroup Attachment
  602. * @apiParam {String} attachment_id
  603. */
  604. api.removeProfileImage = async function(req, res) {
  605. const user = req.user;
  606. const attachment = await Attachment.findById(user.imageAttachment);
  607. if (attachment == null) {
  608. return res.json(ApiResponse.error('attachment not found'));
  609. }
  610. const isDeletable = await isDeletableByUser(user, attachment);
  611. if (!isDeletable) {
  612. return res.json(ApiResponse.error(`Forbidden to remove the attachment '${attachment.id}'`));
  613. }
  614. try {
  615. await user.deleteImage();
  616. }
  617. catch (err) {
  618. logger.error(err);
  619. return res.status(500).json(ApiResponse.error('Error while deleting image'));
  620. }
  621. return res.json(ApiResponse.success({}));
  622. };
  623. return actions;
  624. };