attachment.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  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. let pageId = req.body.page_id || null;
  413. const pagePath = req.body.path || null;
  414. const pageBody = req.body.page_body || null;
  415. let pageCreated = false;
  416. // check params
  417. if (pageId == null && pagePath == null) {
  418. return res.json(ApiResponse.error('Either page_id or path is required.'));
  419. }
  420. if (req.file == null) {
  421. return res.json(ApiResponse.error('File error.'));
  422. }
  423. const file = req.file;
  424. let page;
  425. if (pageId == null) {
  426. logger.debug('Create page before file upload');
  427. if (!isCreatablePage(pagePath)) {
  428. return res.json(ApiResponse.error(`Could not use the path '${pagePath}'`));
  429. }
  430. if (isUserPage(pagePath)) {
  431. const isExistUser = await User.isExistUserByUserPagePath(pagePath);
  432. if (!isExistUser) {
  433. return res.json(ApiResponse.error("Unable to create a page under a non-existent user's user page"));
  434. }
  435. }
  436. const isAclEnabled = crowi.aclService.isAclEnabled();
  437. const grant = isAclEnabled ? Page.GRANT_OWNER : Page.GRANT_PUBLIC;
  438. page = await crowi.pageService.create(pagePath, pageBody ?? '', req.user, { grant });
  439. pageCreated = true;
  440. pageId = page._id;
  441. }
  442. else {
  443. page = await Page.findById(pageId);
  444. // check the user is accessible
  445. const isAccessible = await Page.isAccessiblePageByViewer(page.id, req.user);
  446. if (!isAccessible) {
  447. return res.json(ApiResponse.error(`Forbidden to access to the page '${page.id}'`));
  448. }
  449. }
  450. let attachment;
  451. try {
  452. attachment = await attachmentService.createAttachment(file, req.user, pageId, AttachmentType.WIKI_PAGE);
  453. }
  454. catch (err) {
  455. logger.error(err);
  456. return res.json(ApiResponse.error(err.message));
  457. }
  458. const result = {
  459. page: serializePageSecurely(page),
  460. revision: serializeRevisionSecurely(page.revision),
  461. attachment: attachment.toObject({ virtuals: true }),
  462. pageCreated,
  463. };
  464. activityEvent.emit('update', res.locals.activity._id, { action: SupportedAction.ACTION_ATTACHMENT_ADD });
  465. res.json(ApiResponse.success(result));
  466. if (pageCreated) {
  467. // global notification
  468. try {
  469. await globalNotificationService.fire(GlobalNotificationSetting.EVENT.PAGE_CREATE, page, req.user);
  470. }
  471. catch (err) {
  472. logger.error('Create notification failed', err);
  473. }
  474. }
  475. };
  476. /**
  477. * @swagger
  478. *
  479. * /attachments.uploadProfileImage:
  480. * post:
  481. * tags: [Attachments]
  482. * operationId: uploadProfileImage
  483. * summary: /attachments.uploadProfileImage
  484. * description: Upload profile image
  485. * requestBody:
  486. * content:
  487. * "multipart/form-data":
  488. * schema:
  489. * properties:
  490. * file:
  491. * type: string
  492. * format: binary
  493. * description: attachment data
  494. * user:
  495. * type: string
  496. * description: user to set profile image
  497. * encoding:
  498. * path:
  499. * contentType: application/x-www-form-urlencoded
  500. * "*\/*":
  501. * schema:
  502. * properties:
  503. * file:
  504. * type: string
  505. * format: binary
  506. * description: attachment data
  507. * user:
  508. * type: string
  509. * description: user to set profile
  510. * encoding:
  511. * path:
  512. * contentType: application/x-www-form-urlencoded
  513. * responses:
  514. * 200:
  515. * description: Succeeded to add attachment.
  516. * content:
  517. * application/json:
  518. * schema:
  519. * properties:
  520. * ok:
  521. * $ref: '#/components/schemas/V1Response/properties/ok'
  522. * attachment:
  523. * $ref: '#/components/schemas/AttachmentProfile'
  524. * 403:
  525. * $ref: '#/components/responses/403'
  526. * 500:
  527. * $ref: '#/components/responses/500'
  528. */
  529. /**
  530. * @api {post} /attachments.uploadProfileImage Add attachment for profile image
  531. * @apiName UploadProfileImage
  532. * @apiGroup Attachment
  533. *
  534. * @apiParam {File} file
  535. */
  536. api.uploadProfileImage = async function(req, res) {
  537. // check params
  538. if (req.file == null) {
  539. return res.json(ApiResponse.error('File error.'));
  540. }
  541. if (!req.user) {
  542. return res.json(ApiResponse.error('param "user" must be set.'));
  543. }
  544. const file = req.file;
  545. // check type
  546. const acceptableFileType = /image\/.+/;
  547. if (!file.mimetype.match(acceptableFileType)) {
  548. return res.json(ApiResponse.error('File type error. Only image files is allowed to set as user picture.'));
  549. }
  550. let attachment;
  551. try {
  552. req.user.deleteImage();
  553. attachment = await attachmentService.createAttachment(file, req.user, null, AttachmentType.PROFILE_IMAGE);
  554. await req.user.updateImage(attachment);
  555. }
  556. catch (err) {
  557. logger.error(err);
  558. return res.json(ApiResponse.error(err.message));
  559. }
  560. const result = {
  561. attachment: attachment.toObject({ virtuals: true }),
  562. };
  563. return res.json(ApiResponse.success(result));
  564. };
  565. /**
  566. * @swagger
  567. *
  568. * /attachments.remove:
  569. * post:
  570. * tags: [Attachments, CrowiCompatibles]
  571. * operationId: removeAttachment
  572. * summary: /attachments.remove
  573. * description: Remove attachment
  574. * requestBody:
  575. * content:
  576. * application/json:
  577. * schema:
  578. * properties:
  579. * attachment_id:
  580. * $ref: '#/components/schemas/Attachment/properties/_id'
  581. * required:
  582. * - attachment_id
  583. * responses:
  584. * 200:
  585. * description: Succeeded to remove attachment.
  586. * content:
  587. * application/json:
  588. * schema:
  589. * properties:
  590. * ok:
  591. * $ref: '#/components/schemas/V1Response/properties/ok'
  592. * 403:
  593. * $ref: '#/components/responses/403'
  594. * 500:
  595. * $ref: '#/components/responses/500'
  596. */
  597. /**
  598. * @api {post} /attachments.remove Remove attachments
  599. * @apiName RemoveAttachments
  600. * @apiGroup Attachment
  601. *
  602. * @apiParam {String} attachment_id
  603. */
  604. api.remove = async function(req, res) {
  605. const id = req.body.attachment_id;
  606. const attachment = await Attachment.findById(id);
  607. if (attachment == null) {
  608. return res.json(ApiResponse.error('attachment not found'));
  609. }
  610. const isDeletable = await isDeletableByUser(req.user, attachment);
  611. if (!isDeletable) {
  612. return res.json(ApiResponse.error(`Forbidden to remove the attachment '${attachment.id}'`));
  613. }
  614. try {
  615. await attachmentService.removeAttachment(attachment);
  616. }
  617. catch (err) {
  618. logger.error(err);
  619. return res.status(500).json(ApiResponse.error('Error while deleting file'));
  620. }
  621. activityEvent.emit('update', res.locals.activity._id, { action: SupportedAction.ACTION_ATTACHMENT_REMOVE });
  622. return res.json(ApiResponse.success({}));
  623. };
  624. /**
  625. * @swagger
  626. *
  627. * /attachments.removeProfileImage:
  628. * post:
  629. * tags: [Attachments]
  630. * operationId: removeProfileImage
  631. * summary: /attachments.removeProfileImage
  632. * description: Remove profile image
  633. * requestBody:
  634. * content:
  635. * application/json:
  636. * schema:
  637. * properties:
  638. * user:
  639. * type: string
  640. * description: user to remove profile image
  641. * responses:
  642. * 200:
  643. * description: Succeeded to add attachment.
  644. * content:
  645. * application/json:
  646. * schema:
  647. * properties:
  648. * ok:
  649. * $ref: '#/components/schemas/V1Response/properties/ok'
  650. * 403:
  651. * $ref: '#/components/responses/403'
  652. * 500:
  653. * $ref: '#/components/responses/500'
  654. */
  655. /**
  656. * @api {post} /attachments.removeProfileImage Remove profile image attachments
  657. * @apiGroup Attachment
  658. * @apiParam {String} attachment_id
  659. */
  660. api.removeProfileImage = async function(req, res) {
  661. const user = req.user;
  662. const attachment = await Attachment.findById(user.imageAttachment);
  663. if (attachment == null) {
  664. return res.json(ApiResponse.error('attachment not found'));
  665. }
  666. const isDeletable = await isDeletableByUser(user, attachment);
  667. if (!isDeletable) {
  668. return res.json(ApiResponse.error(`Forbidden to remove the attachment '${attachment.id}'`));
  669. }
  670. try {
  671. await user.deleteImage();
  672. }
  673. catch (err) {
  674. logger.error(err);
  675. return res.status(500).json(ApiResponse.error('Error while deleting image'));
  676. }
  677. return res.json(ApiResponse.success({}));
  678. };
  679. return actions;
  680. };