attachment.js 23 KB

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