attachment.js 21 KB

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