attachment.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  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.limit:
  265. * get:
  266. * tags: [Attachments]
  267. * operationId: getAttachmentsLimit
  268. * summary: /attachments.limit
  269. * description: Get available capacity of uploaded file with GridFS
  270. * parameters:
  271. * - in: query
  272. * name: fileSize
  273. * schema:
  274. * type: number
  275. * description: file size
  276. * example: 23175
  277. * required: true
  278. * responses:
  279. * 200:
  280. * description: Succeeded to get available capacity of uploaded file with GridFS.
  281. * content:
  282. * application/json:
  283. * schema:
  284. * properties:
  285. * isUploadable:
  286. * type: boolean
  287. * description: uploadable
  288. * example: true
  289. * ok:
  290. * $ref: '#/components/schemas/V1Response/properties/ok'
  291. * 403:
  292. * $ref: '#/components/responses/403'
  293. * 500:
  294. * $ref: '#/components/responses/500'
  295. */
  296. /**
  297. * @api {get} /attachments.limit get available capacity of uploaded file with GridFS
  298. * @apiName AddAttachments
  299. * @apiGroup Attachment
  300. */
  301. api.limit = async function(req, res) {
  302. const fileSize = Number(req.query.fileSize);
  303. return res.json(ApiResponse.success(await fileUploadService.checkLimit(fileSize)));
  304. };
  305. /**
  306. * @swagger
  307. *
  308. * /attachments.add:
  309. * post:
  310. * tags: [Attachments, CrowiCompatibles]
  311. * operationId: addAttachment
  312. * summary: /attachments.add
  313. * description: Add attachment to the page
  314. * requestBody:
  315. * content:
  316. * "multipart/form-data":
  317. * schema:
  318. * properties:
  319. * page_id:
  320. * nullable: true
  321. * type: string
  322. * path:
  323. * nullable: true
  324. * type: string
  325. * file:
  326. * type: string
  327. * format: binary
  328. * description: attachment data
  329. * encoding:
  330. * path:
  331. * contentType: application/x-www-form-urlencoded
  332. * "*\/*":
  333. * schema:
  334. * properties:
  335. * page_id:
  336. * nullable: true
  337. * type: string
  338. * path:
  339. * nullable: true
  340. * type: string
  341. * file:
  342. * type: string
  343. * format: binary
  344. * description: attachment data
  345. * encoding:
  346. * path:
  347. * contentType: application/x-www-form-urlencoded
  348. * responses:
  349. * 200:
  350. * description: Succeeded to add attachment.
  351. * content:
  352. * application/json:
  353. * schema:
  354. * properties:
  355. * ok:
  356. * $ref: '#/components/schemas/V1Response/properties/ok'
  357. * page:
  358. * $ref: '#/components/schemas/Page'
  359. * attachment:
  360. * $ref: '#/components/schemas/Attachment'
  361. * url:
  362. * $ref: '#/components/schemas/Attachment/properties/url'
  363. * pageCreated:
  364. * type: boolean
  365. * description: whether the page was created
  366. * example: false
  367. * 403:
  368. * $ref: '#/components/responses/403'
  369. * 500:
  370. * $ref: '#/components/responses/500'
  371. */
  372. /**
  373. * @api {post} /attachments.add Add attachment to the page
  374. * @apiName AddAttachments
  375. * @apiGroup Attachment
  376. *
  377. * @apiParam {String} page_id
  378. * @apiParam {File} file
  379. */
  380. api.add = async function(req, res) {
  381. let pageId = req.body.page_id || null;
  382. const pagePath = req.body.path || null;
  383. let pageCreated = false;
  384. // check params
  385. if (pageId == null && pagePath == null) {
  386. return res.json(ApiResponse.error('Either page_id or path is required.'));
  387. }
  388. if (!req.file) {
  389. return res.json(ApiResponse.error('File error.'));
  390. }
  391. const file = req.file;
  392. let page;
  393. if (pageId == null) {
  394. logger.debug('Create page before file upload');
  395. page = await Page.create(pagePath, `# ${pagePath}`, req.user, { grant: Page.GRANT_OWNER });
  396. pageCreated = true;
  397. pageId = page._id;
  398. }
  399. else {
  400. page = await Page.findById(pageId);
  401. // check the user is accessible
  402. const isAccessible = await Page.isAccessiblePageByViewer(page.id, req.user);
  403. if (!isAccessible) {
  404. return res.json(ApiResponse.error(`Forbidden to access to the page '${page.id}'`));
  405. }
  406. }
  407. let attachment;
  408. try {
  409. attachment = await attachmentService.createAttachment(file, req.user, pageId);
  410. }
  411. catch (err) {
  412. logger.error(err);
  413. return res.json(ApiResponse.error(err.message));
  414. }
  415. const result = {
  416. page: page.toObject(),
  417. attachment: attachment.toObject({ virtuals: true }),
  418. pageCreated,
  419. };
  420. return res.json(ApiResponse.success(result));
  421. };
  422. /**
  423. * @swagger
  424. *
  425. * /attachments.uploadProfileImage:
  426. * post:
  427. * tags: [Attachments]
  428. * operationId: uploadProfileImage
  429. * summary: /attachments.uploadProfileImage
  430. * description: Upload profile image
  431. * requestBody:
  432. * content:
  433. * "multipart/form-data":
  434. * schema:
  435. * properties:
  436. * file:
  437. * type: string
  438. * format: binary
  439. * description: attachment data
  440. * user:
  441. * type: string
  442. * description: user to set profile image
  443. * encoding:
  444. * path:
  445. * contentType: application/x-www-form-urlencoded
  446. * "*\/*":
  447. * schema:
  448. * properties:
  449. * file:
  450. * type: string
  451. * format: binary
  452. * description: attachment data
  453. * user:
  454. * type: string
  455. * description: user to set profile
  456. * encoding:
  457. * path:
  458. * contentType: application/x-www-form-urlencoded
  459. * responses:
  460. * 200:
  461. * description: Succeeded to add attachment.
  462. * content:
  463. * application/json:
  464. * schema:
  465. * properties:
  466. * ok:
  467. * $ref: '#/components/schemas/V1Response/properties/ok'
  468. * attachment:
  469. * $ref: '#/components/schemas/AttachmentProfile'
  470. * 403:
  471. * $ref: '#/components/responses/403'
  472. * 500:
  473. * $ref: '#/components/responses/500'
  474. */
  475. /**
  476. * @api {post} /attachments.uploadProfileImage Add attachment for profile image
  477. * @apiName UploadProfileImage
  478. * @apiGroup Attachment
  479. *
  480. * @apiParam {File} file
  481. */
  482. api.uploadProfileImage = async function(req, res) {
  483. // check params
  484. if (!req.file) {
  485. return res.json(ApiResponse.error('File error.'));
  486. }
  487. if (!req.user) {
  488. return res.json(ApiResponse.error('param "user" must be set.'));
  489. }
  490. const file = req.file;
  491. // check type
  492. const acceptableFileType = /image\/.+/;
  493. if (!file.mimetype.match(acceptableFileType)) {
  494. return res.json(ApiResponse.error('File type error. Only image files is allowed to set as user picture.'));
  495. }
  496. let attachment;
  497. try {
  498. req.user.deleteImage();
  499. attachment = await attachmentService.createAttachment(file, req.user);
  500. await req.user.updateImage(attachment);
  501. }
  502. catch (err) {
  503. logger.error(err);
  504. return res.json(ApiResponse.error(err.message));
  505. }
  506. const result = {
  507. attachment: attachment.toObject({ virtuals: true }),
  508. };
  509. return res.json(ApiResponse.success(result));
  510. };
  511. /**
  512. * @swagger
  513. *
  514. * /attachments.remove:
  515. * post:
  516. * tags: [Attachments, CrowiCompatibles]
  517. * operationId: removeAttachment
  518. * summary: /attachments.remove
  519. * description: Remove attachment
  520. * requestBody:
  521. * content:
  522. * application/json:
  523. * schema:
  524. * properties:
  525. * attachment_id:
  526. * $ref: '#/components/schemas/Attachment/properties/_id'
  527. * required:
  528. * - attachment_id
  529. * responses:
  530. * 200:
  531. * description: Succeeded to remove attachment.
  532. * content:
  533. * application/json:
  534. * schema:
  535. * properties:
  536. * ok:
  537. * $ref: '#/components/schemas/V1Response/properties/ok'
  538. * 403:
  539. * $ref: '#/components/responses/403'
  540. * 500:
  541. * $ref: '#/components/responses/500'
  542. */
  543. /**
  544. * @api {post} /attachments.remove Remove attachments
  545. * @apiName RemoveAttachments
  546. * @apiGroup Attachment
  547. *
  548. * @apiParam {String} attachment_id
  549. */
  550. api.remove = async function(req, res) {
  551. const id = req.body.attachment_id;
  552. const attachment = await Attachment.findById(id);
  553. if (attachment == null) {
  554. return res.json(ApiResponse.error('attachment not found'));
  555. }
  556. const isDeletable = await isDeletableByUser(req.user, attachment);
  557. if (!isDeletable) {
  558. return res.json(ApiResponse.error(`Forbidden to remove the attachment '${attachment.id}'`));
  559. }
  560. try {
  561. await removeAttachment(attachment);
  562. }
  563. catch (err) {
  564. logger.error(err);
  565. return res.status(500).json(ApiResponse.error('Error while deleting file'));
  566. }
  567. return res.json(ApiResponse.success({}));
  568. };
  569. /**
  570. * @swagger
  571. *
  572. * /attachments.removeProfileImage:
  573. * post:
  574. * tags: [Attachments]
  575. * operationId: removeProfileImage
  576. * summary: /attachments.removeProfileImage
  577. * description: Remove profile image
  578. * requestBody:
  579. * content:
  580. * application/json:
  581. * schema:
  582. * properties:
  583. * user:
  584. * type: string
  585. * description: user to remove profile image
  586. * responses:
  587. * 200:
  588. * description: Succeeded to add attachment.
  589. * content:
  590. * application/json:
  591. * schema:
  592. * properties:
  593. * ok:
  594. * $ref: '#/components/schemas/V1Response/properties/ok'
  595. * 403:
  596. * $ref: '#/components/responses/403'
  597. * 500:
  598. * $ref: '#/components/responses/500'
  599. */
  600. /**
  601. * @api {post} /attachments.removeProfileImage Remove profile image attachments
  602. * @apiGroup Attachment
  603. * @apiParam {String} attachment_id
  604. */
  605. api.removeProfileImage = async function(req, res) {
  606. const user = req.user;
  607. const attachment = await Attachment.findById(user.imageAttachment);
  608. if (attachment == null) {
  609. return res.json(ApiResponse.error('attachment not found'));
  610. }
  611. const isDeletable = await isDeletableByUser(user, attachment);
  612. if (!isDeletable) {
  613. return res.json(ApiResponse.error(`Forbidden to remove the attachment '${attachment.id}'`));
  614. }
  615. try {
  616. await user.deleteImage();
  617. }
  618. catch (err) {
  619. logger.error(err);
  620. return res.status(500).json(ApiResponse.error('Error while deleting image'));
  621. }
  622. return res.json(ApiResponse.success({}));
  623. };
  624. return actions;
  625. };