attachment.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  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 User = crowi.model('User');
  124. const Page = crowi.model('Page');
  125. const { fileUploadService, attachmentService } = crowi;
  126. /**
  127. * Check the user is accessible to the related page
  128. *
  129. * @param {User} user
  130. * @param {Attachment} attachment
  131. */
  132. async function isAccessibleByViewer(user, attachment) {
  133. if (attachment.page != null) {
  134. // eslint-disable-next-line no-return-await
  135. return await Page.isAccessiblePageByViewer(attachment.page, user);
  136. }
  137. return true;
  138. }
  139. /**
  140. * Check the user is accessible to the related page
  141. *
  142. * @param {User} user
  143. * @param {Attachment} attachment
  144. */
  145. async function isDeletableByUser(user, attachment) {
  146. const ownerId = attachment.creator._id || attachment.creator;
  147. if (attachment.page == null) { // when profile image
  148. return user.id === ownerId.toString();
  149. }
  150. // eslint-disable-next-line no-return-await
  151. return await Page.isAccessiblePageByViewer(attachment.page, user);
  152. }
  153. /**
  154. * Common method to response
  155. *
  156. * @param {Request} req
  157. * @param {Response} res
  158. * @param {User} user
  159. * @param {Attachment} attachment
  160. * @param {boolean} forceDownload
  161. */
  162. async function responseForAttachment(req, res, attachment, forceDownload) {
  163. if (attachment == null) {
  164. return res.json(ApiResponse.error('attachment not found'));
  165. }
  166. const user = req.user;
  167. const isAccessible = await isAccessibleByViewer(user, attachment);
  168. if (!isAccessible) {
  169. return res.json(ApiResponse.error(`Forbidden to access to the attachment '${attachment.id}'`));
  170. }
  171. // add headers before evaluating 'req.fresh'
  172. setHeaderToRes(res, attachment, forceDownload);
  173. // return 304 if request is "fresh"
  174. // see: http://expressjs.com/en/5x/api.html#req.fresh
  175. if (req.fresh) {
  176. return res.sendStatus(304);
  177. }
  178. if (fileUploadService.canRespond()) {
  179. return fileUploadService.respond(res, attachment);
  180. }
  181. let fileStream;
  182. try {
  183. fileStream = await fileUploadService.findDeliveryFile(attachment);
  184. }
  185. catch (e) {
  186. logger.error(e);
  187. return res.json(ApiResponse.error(e.message));
  188. }
  189. return fileStream.pipe(res);
  190. }
  191. /**
  192. * set http response header
  193. *
  194. * @param {Response} res
  195. * @param {Attachment} attachment
  196. * @param {boolean} forceDownload
  197. */
  198. function setHeaderToRes(res, attachment, forceDownload) {
  199. res.set({
  200. ETag: `Attachment-${attachment._id}`,
  201. 'Last-Modified': attachment.createdAt.toUTCString(),
  202. });
  203. // download
  204. if (forceDownload) {
  205. res.set({
  206. 'Content-Disposition': `attachment;filename*=UTF-8''${encodeURIComponent(attachment.originalName)}`,
  207. });
  208. }
  209. // reference
  210. else {
  211. res.set({
  212. 'Content-Type': attachment.fileFormat,
  213. 'Content-Security-Policy': "script-src 'unsafe-hashes'",
  214. });
  215. }
  216. }
  217. async function removeAttachment(attachmentId) {
  218. const { fileUploadService } = crowi;
  219. // retrieve data from DB to get a completely populated instance
  220. const attachment = await Attachment.findById(attachmentId);
  221. await fileUploadService.deleteFile(attachment);
  222. return attachment.remove();
  223. }
  224. const actions = {};
  225. const api = {};
  226. actions.api = api;
  227. api.download = async function(req, res) {
  228. const id = req.params.id;
  229. const attachment = await Attachment.findById(id);
  230. return responseForAttachment(req, res, attachment, true);
  231. };
  232. /**
  233. * @api {get} /attachments.get get attachments
  234. * @apiName get
  235. * @apiGroup Attachment
  236. *
  237. * @apiParam {String} id
  238. */
  239. api.get = async function(req, res) {
  240. const id = req.params.id;
  241. const attachment = await Attachment.findById(id);
  242. return responseForAttachment(req, res, attachment);
  243. };
  244. /**
  245. * @api {get} /attachments.obsoletedGetForMongoDB get attachments from mongoDB
  246. * @apiName get
  247. * @apiGroup Attachment
  248. *
  249. * @apiParam {String} pageId, fileName
  250. */
  251. api.obsoletedGetForMongoDB = async function(req, res) {
  252. if (process.env.FILE_UPLOAD !== 'mongodb') {
  253. return res.status(400);
  254. }
  255. const pageId = req.params.pageId;
  256. const fileName = req.params.fileName;
  257. const filePath = `attachment/${pageId}/${fileName}`;
  258. const attachment = await Attachment.findOne({ filePath });
  259. return responseForAttachment(req, res, attachment);
  260. };
  261. /**
  262. * @swagger
  263. *
  264. * /attachments.list:
  265. * get:
  266. * tags: [Attachments, CrowiCompatibles]
  267. * operationId: listAttachments
  268. * summary: /attachments.list
  269. * description: Get list of attachments in page
  270. * parameters:
  271. * - in: query
  272. * name: page_id
  273. * schema:
  274. * $ref: '#/components/schemas/Page/properties/_id'
  275. * required: true
  276. * responses:
  277. * 200:
  278. * description: Succeeded to get list of attachments.
  279. * content:
  280. * application/json:
  281. * schema:
  282. * properties:
  283. * ok:
  284. * $ref: '#/components/schemas/V1Response/properties/ok'
  285. * attachments:
  286. * type: array
  287. * items:
  288. * $ref: '#/components/schemas/Attachment'
  289. * description: attachment list
  290. * 403:
  291. * $ref: '#/components/responses/403'
  292. * 500:
  293. * $ref: '#/components/responses/500'
  294. */
  295. /**
  296. * @api {get} /attachments.list Get attachments of the page
  297. * @apiName ListAttachments
  298. * @apiGroup Attachment
  299. *
  300. * @apiParam {String} page_id
  301. */
  302. api.list = async function(req, res) {
  303. const id = req.query.page_id || null;
  304. if (!id) {
  305. return res.json(ApiResponse.error('Parameters page_id is required.'));
  306. }
  307. let attachments = await Attachment.find({ page: id })
  308. .sort({ updatedAt: 1 })
  309. .populate({ path: 'creator', select: User.USER_PUBLIC_FIELDS });
  310. attachments = attachments.map((attachment) => {
  311. return attachment.toObject({ virtuals: true });
  312. });
  313. return res.json(ApiResponse.success({ attachments }));
  314. };
  315. /**
  316. * @swagger
  317. *
  318. * /attachments.limit:
  319. * get:
  320. * tags: [Attachments]
  321. * operationId: getAttachmentsLimit
  322. * summary: /attachments.limit
  323. * description: Get available capacity of uploaded file with GridFS
  324. * parameters:
  325. * - in: query
  326. * name: fileSize
  327. * schema:
  328. * type: number
  329. * description: file size
  330. * example: 23175
  331. * required: true
  332. * responses:
  333. * 200:
  334. * description: Succeeded to get available capacity of uploaded file with GridFS.
  335. * content:
  336. * application/json:
  337. * schema:
  338. * properties:
  339. * isUploadable:
  340. * type: boolean
  341. * description: uploadable
  342. * example: true
  343. * ok:
  344. * $ref: '#/components/schemas/V1Response/properties/ok'
  345. * 403:
  346. * $ref: '#/components/responses/403'
  347. * 500:
  348. * $ref: '#/components/responses/500'
  349. */
  350. /**
  351. * @api {get} /attachments.limit get available capacity of uploaded file with GridFS
  352. * @apiName AddAttachments
  353. * @apiGroup Attachment
  354. */
  355. api.limit = async function(req, res) {
  356. const fileSize = Number(req.query.fileSize);
  357. return res.json(ApiResponse.success(await fileUploadService.checkLimit(fileSize)));
  358. };
  359. /**
  360. * @swagger
  361. *
  362. * /attachments.add:
  363. * post:
  364. * tags: [Attachments, CrowiCompatibles]
  365. * operationId: addAttachment
  366. * summary: /attachments.add
  367. * description: Add attachment to the page
  368. * requestBody:
  369. * content:
  370. * "multipart/form-data":
  371. * schema:
  372. * properties:
  373. * page_id:
  374. * nullable: true
  375. * type: string
  376. * path:
  377. * nullable: true
  378. * type: string
  379. * file:
  380. * type: string
  381. * format: binary
  382. * description: attachment data
  383. * encoding:
  384. * path:
  385. * contentType: application/x-www-form-urlencoded
  386. * "*\/*":
  387. * schema:
  388. * properties:
  389. * page_id:
  390. * nullable: true
  391. * type: string
  392. * path:
  393. * nullable: true
  394. * type: string
  395. * file:
  396. * type: string
  397. * format: binary
  398. * description: attachment data
  399. * encoding:
  400. * path:
  401. * contentType: application/x-www-form-urlencoded
  402. * responses:
  403. * 200:
  404. * description: Succeeded to add attachment.
  405. * content:
  406. * application/json:
  407. * schema:
  408. * properties:
  409. * ok:
  410. * $ref: '#/components/schemas/V1Response/properties/ok'
  411. * page:
  412. * $ref: '#/components/schemas/Page'
  413. * attachment:
  414. * $ref: '#/components/schemas/Attachment'
  415. * url:
  416. * $ref: '#/components/schemas/Attachment/properties/url'
  417. * pageCreated:
  418. * type: boolean
  419. * description: whether the page was created
  420. * example: false
  421. * 403:
  422. * $ref: '#/components/responses/403'
  423. * 500:
  424. * $ref: '#/components/responses/500'
  425. */
  426. /**
  427. * @api {post} /attachments.add Add attachment to the page
  428. * @apiName AddAttachments
  429. * @apiGroup Attachment
  430. *
  431. * @apiParam {String} page_id
  432. * @apiParam {File} file
  433. */
  434. api.add = async function(req, res) {
  435. let pageId = req.body.page_id || null;
  436. const pagePath = req.body.path || null;
  437. let pageCreated = false;
  438. // check params
  439. if (pageId == null && pagePath == null) {
  440. return res.json(ApiResponse.error('Either page_id or path is required.'));
  441. }
  442. if (!req.file) {
  443. return res.json(ApiResponse.error('File error.'));
  444. }
  445. const file = req.file;
  446. let page;
  447. if (pageId == null) {
  448. logger.debug('Create page before file upload');
  449. page = await Page.create(pagePath, `# ${pagePath}`, req.user, { grant: Page.GRANT_OWNER });
  450. pageCreated = true;
  451. pageId = page._id;
  452. }
  453. else {
  454. page = await Page.findById(pageId);
  455. // check the user is accessible
  456. const isAccessible = await Page.isAccessiblePageByViewer(page.id, req.user);
  457. if (!isAccessible) {
  458. return res.json(ApiResponse.error(`Forbidden to access to the page '${page.id}'`));
  459. }
  460. }
  461. let attachment;
  462. try {
  463. attachment = await attachmentService.createAttachment(file, req.user, pageId);
  464. }
  465. catch (err) {
  466. logger.error(err);
  467. return res.json(ApiResponse.error(err.message));
  468. }
  469. const result = {
  470. page: page.toObject(),
  471. attachment: attachment.toObject({ virtuals: true }),
  472. pageCreated,
  473. };
  474. return res.json(ApiResponse.success(result));
  475. };
  476. /**
  477. * @swagger
  478. *
  479. * /attachments.uploadProfileImage:
  480. * post:
  481. * tags: [Attachments]
  482. * operationId: uploadProfileImage
  483. * summary: /attachments.uploadProfileImage
  484. * description: Upload profile image
  485. * requestBody:
  486. * content:
  487. * "multipart/form-data":
  488. * schema:
  489. * properties:
  490. * file:
  491. * type: string
  492. * format: binary
  493. * description: attachment data
  494. * user:
  495. * type: string
  496. * description: user to set profile image
  497. * encoding:
  498. * path:
  499. * contentType: application/x-www-form-urlencoded
  500. * "*\/*":
  501. * schema:
  502. * properties:
  503. * file:
  504. * type: string
  505. * format: binary
  506. * description: attachment data
  507. * user:
  508. * type: string
  509. * description: user to set profile
  510. * encoding:
  511. * path:
  512. * contentType: application/x-www-form-urlencoded
  513. * responses:
  514. * 200:
  515. * description: Succeeded to add attachment.
  516. * content:
  517. * application/json:
  518. * schema:
  519. * properties:
  520. * ok:
  521. * $ref: '#/components/schemas/V1Response/properties/ok'
  522. * attachment:
  523. * $ref: '#/components/schemas/AttachmentProfile'
  524. * 403:
  525. * $ref: '#/components/responses/403'
  526. * 500:
  527. * $ref: '#/components/responses/500'
  528. */
  529. /**
  530. * @api {post} /attachments.uploadProfileImage Add attachment for profile image
  531. * @apiName UploadProfileImage
  532. * @apiGroup Attachment
  533. *
  534. * @apiParam {File} file
  535. */
  536. api.uploadProfileImage = async function(req, res) {
  537. // check params
  538. if (!req.file) {
  539. return res.json(ApiResponse.error('File error.'));
  540. }
  541. if (!req.user) {
  542. return res.json(ApiResponse.error('param "user" must be set.'));
  543. }
  544. const file = req.file;
  545. // check type
  546. const acceptableFileType = /image\/.+/;
  547. if (!file.mimetype.match(acceptableFileType)) {
  548. return res.json(ApiResponse.error('File type error. Only image files is allowed to set as user picture.'));
  549. }
  550. let attachment;
  551. try {
  552. req.user.deleteImage();
  553. attachment = await attachmentService.createAttachment(file, req.user);
  554. await req.user.updateImage(attachment);
  555. }
  556. catch (err) {
  557. logger.error(err);
  558. return res.json(ApiResponse.error(err.message));
  559. }
  560. const result = {
  561. attachment: attachment.toObject({ virtuals: true }),
  562. };
  563. return res.json(ApiResponse.success(result));
  564. };
  565. /**
  566. * @swagger
  567. *
  568. * /attachments.remove:
  569. * post:
  570. * tags: [Attachments, CrowiCompatibles]
  571. * operationId: removeAttachment
  572. * summary: /attachments.remove
  573. * description: Remove attachment
  574. * requestBody:
  575. * content:
  576. * application/json:
  577. * schema:
  578. * properties:
  579. * attachment_id:
  580. * $ref: '#/components/schemas/Attachment/properties/_id'
  581. * required:
  582. * - attachment_id
  583. * responses:
  584. * 200:
  585. * description: Succeeded to remove attachment.
  586. * content:
  587. * application/json:
  588. * schema:
  589. * properties:
  590. * ok:
  591. * $ref: '#/components/schemas/V1Response/properties/ok'
  592. * 403:
  593. * $ref: '#/components/responses/403'
  594. * 500:
  595. * $ref: '#/components/responses/500'
  596. */
  597. /**
  598. * @api {post} /attachments.remove Remove attachments
  599. * @apiName RemoveAttachments
  600. * @apiGroup Attachment
  601. *
  602. * @apiParam {String} attachment_id
  603. */
  604. api.remove = async function(req, res) {
  605. const id = req.body.attachment_id;
  606. const attachment = await Attachment.findById(id);
  607. if (attachment == null) {
  608. return res.json(ApiResponse.error('attachment not found'));
  609. }
  610. const isDeletable = await isDeletableByUser(req.user, attachment);
  611. if (!isDeletable) {
  612. return res.json(ApiResponse.error(`Forbidden to remove the attachment '${attachment.id}'`));
  613. }
  614. try {
  615. await removeAttachment(attachment);
  616. }
  617. catch (err) {
  618. logger.error(err);
  619. return res.status(500).json(ApiResponse.error('Error while deleting file'));
  620. }
  621. return res.json(ApiResponse.success({}));
  622. };
  623. /**
  624. * @swagger
  625. *
  626. * /attachments.removeProfileImage:
  627. * post:
  628. * tags: [Attachments]
  629. * operationId: removeProfileImage
  630. * summary: /attachments.removeProfileImage
  631. * description: Remove profile image
  632. * requestBody:
  633. * content:
  634. * application/json:
  635. * schema:
  636. * properties:
  637. * user:
  638. * type: string
  639. * description: user to remove profile image
  640. * responses:
  641. * 200:
  642. * description: Succeeded to add attachment.
  643. * content:
  644. * application/json:
  645. * schema:
  646. * properties:
  647. * ok:
  648. * $ref: '#/components/schemas/V1Response/properties/ok'
  649. * 403:
  650. * $ref: '#/components/responses/403'
  651. * 500:
  652. * $ref: '#/components/responses/500'
  653. */
  654. /**
  655. * @api {post} /attachments.removeProfileImage Remove profile image attachments
  656. * @apiGroup Attachment
  657. * @apiParam {String} attachment_id
  658. */
  659. api.removeProfileImage = async function(req, res) {
  660. const user = req.user;
  661. const attachment = await Attachment.findById(user.imageAttachment);
  662. if (attachment == null) {
  663. return res.json(ApiResponse.error('attachment not found'));
  664. }
  665. const isDeletable = await isDeletableByUser(user, attachment);
  666. if (!isDeletable) {
  667. return res.json(ApiResponse.error(`Forbidden to remove the attachment '${attachment.id}'`));
  668. }
  669. try {
  670. await user.deleteImage();
  671. }
  672. catch (err) {
  673. logger.error(err);
  674. return res.status(500).json(ApiResponse.error('Error while deleting image'));
  675. }
  676. return res.json(ApiResponse.success({}));
  677. };
  678. return actions;
  679. };