attachment.js 21 KB

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