attachment.js 22 KB

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