attachment.js 22 KB

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