attachment.js 23 KB

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