page.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. import { body } from 'express-validator';
  2. import mongoose from 'mongoose';
  3. import XssOption from '~/services/xss/xssOption';
  4. import loggerFactory from '~/utils/logger';
  5. import { GlobalNotificationSettingEvent } from '../models';
  6. import { PathAlreadyExistsError } from '../models/errors';
  7. import PageTagRelation from '../models/page-tag-relation';
  8. import UpdatePost from '../models/update-post';
  9. import { configManager } from '../service/config-manager';
  10. /**
  11. * @swagger
  12. * tags:
  13. * name: Pages
  14. */
  15. /**
  16. * @swagger
  17. *
  18. * components:
  19. * schemas:
  20. * Page:
  21. * description: Page
  22. * type: object
  23. * properties:
  24. * _id:
  25. * type: string
  26. * description: page ID
  27. * example: 5e07345972560e001761fa63
  28. * __v:
  29. * type: number
  30. * description: DB record version
  31. * example: 0
  32. * commentCount:
  33. * type: number
  34. * description: count of comments
  35. * example: 3
  36. * createdAt:
  37. * type: string
  38. * description: date created at
  39. * example: 2010-01-01T00:00:00.000Z
  40. * creator:
  41. * $ref: '#/components/schemas/User'
  42. * extended:
  43. * type: object
  44. * description: extend data
  45. * example: {}
  46. * grant:
  47. * type: number
  48. * description: grant
  49. * example: 1
  50. * grantedUsers:
  51. * type: array
  52. * description: granted users
  53. * items:
  54. * type: string
  55. * description: user ID
  56. * example: ["5ae5fccfc5577b0004dbd8ab"]
  57. * lastUpdateUser:
  58. * $ref: '#/components/schemas/User'
  59. * liker:
  60. * type: array
  61. * description: granted users
  62. * items:
  63. * type: string
  64. * description: user ID
  65. * example: []
  66. * path:
  67. * type: string
  68. * description: page path
  69. * example: /
  70. * revision:
  71. * $ref: '#/components/schemas/Revision'
  72. * status:
  73. * type: string
  74. * description: status
  75. * enum:
  76. * - 'wip'
  77. * - 'published'
  78. * - 'deleted'
  79. * - 'deprecated'
  80. * example: published
  81. * updatedAt:
  82. * type: string
  83. * description: date updated at
  84. * example: 2010-01-01T00:00:00.000Z
  85. *
  86. * UpdatePost:
  87. * description: UpdatePost
  88. * type: object
  89. * properties:
  90. * _id:
  91. * type: string
  92. * description: update post ID
  93. * example: 5e0734e472560e001761fa68
  94. * __v:
  95. * type: number
  96. * description: DB record version
  97. * example: 0
  98. * pathPattern:
  99. * type: string
  100. * description: path pattern
  101. * example: /test
  102. * patternPrefix:
  103. * type: string
  104. * description: patternPrefix prefix
  105. * example: /
  106. * patternPrefix2:
  107. * type: string
  108. * description: path
  109. * example: test
  110. * channel:
  111. * type: string
  112. * description: channel
  113. * example: general
  114. * provider:
  115. * type: string
  116. * description: provider
  117. * enum:
  118. * - slack
  119. * example: slack
  120. * creator:
  121. * $ref: '#/components/schemas/User'
  122. * createdAt:
  123. * type: string
  124. * description: date created at
  125. * example: 2010-01-01T00:00:00.000Z
  126. */
  127. /* eslint-disable no-use-before-define */
  128. /**
  129. * @type { (crowi: import('../crowi').default, app) => any }
  130. */
  131. module.exports = function(crowi, app) {
  132. const debug = require('debug')('growi:routes:page');
  133. const logger = loggerFactory('growi:routes:page');
  134. const { pagePathUtils } = require('@growi/core/dist/utils');
  135. /** @type {import('../models/page').PageModel} */
  136. const Page = crowi.model('Page');
  137. const PageRedirect = mongoose.model('PageRedirect');
  138. const ApiResponse = require('../util/apiResponse');
  139. const { xssService } = crowi;
  140. const globalNotificationService = crowi.getGlobalNotificationService();
  141. const Xss = require('~/services/xss/index');
  142. const initializedConfig = {
  143. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:xss:isEnabledPrevention'),
  144. tagWhitelist: xssService.getTagWhitelist(),
  145. attrWhitelist: xssService.getAttrWhitelist(),
  146. };
  147. const xssOption = new XssOption(initializedConfig);
  148. const xss = new Xss(xssOption);
  149. const actions = {};
  150. // async function showPageForPresentation(req, res, next) {
  151. // const id = req.params.id;
  152. // const { revisionId } = req.query;
  153. // let page = await Page.findByIdAndViewer(id, req.user, null, true, true);
  154. // if (page == null) {
  155. // next();
  156. // }
  157. // // empty page
  158. // if (page.isEmpty) {
  159. // // redirect to page (path) url
  160. // const url = new URL('https://dummy.origin');
  161. // url.pathname = page.path;
  162. // Object.entries(req.query).forEach(([key, value], i) => {
  163. // url.searchParams.append(key, value);
  164. // });
  165. // return res.safeRedirect(urljoin(url.pathname, url.search));
  166. // }
  167. // const renderVars = {};
  168. // // populate
  169. // page = await page.populateDataToMakePresentation(revisionId);
  170. // if (page != null) {
  171. // addRenderVarsForPresentation(renderVars, page);
  172. // }
  173. // return res.render('page_presentation', renderVars);
  174. // }
  175. /**
  176. * switch action
  177. * - presentation mode
  178. * - by behaviorType
  179. */
  180. // actions.showPage = async function(req, res, next) {
  181. // // presentation mode
  182. // if (req.query.presentation) {
  183. // return showPageForPresentation(req, res, next);
  184. // }
  185. // // delegate to showPageForGrowiBehavior
  186. // return showPageForGrowiBehavior(req, res, next);
  187. // };
  188. const api = {};
  189. const validator = {};
  190. actions.api = api;
  191. actions.validator = validator;
  192. /**
  193. * @swagger
  194. *
  195. * /pages.getPageTag:
  196. * get:
  197. * tags: [Pages]
  198. * operationId: getPageTag
  199. * summary: /pages.getPageTag
  200. * description: Get page tag
  201. * parameters:
  202. * - in: query
  203. * name: pageId
  204. * schema:
  205. * $ref: '#/components/schemas/Page/properties/_id'
  206. * responses:
  207. * 200:
  208. * description: Succeeded to get page tags.
  209. * content:
  210. * application/json:
  211. * schema:
  212. * properties:
  213. * ok:
  214. * $ref: '#/components/schemas/V1Response/properties/ok'
  215. * tags:
  216. * $ref: '#/components/schemas/Tags'
  217. * 403:
  218. * $ref: '#/components/responses/403'
  219. * 500:
  220. * $ref: '#/components/responses/500'
  221. */
  222. /**
  223. * @api {get} /pages.getPageTag get page tags
  224. * @apiName GetPageTag
  225. * @apiGroup Page
  226. *
  227. * @apiParam {String} pageId
  228. */
  229. api.getPageTag = async function(req, res) {
  230. const result = {};
  231. try {
  232. result.tags = await PageTagRelation.listTagNamesByPage(req.query.pageId);
  233. }
  234. catch (err) {
  235. return res.json(ApiResponse.error(err));
  236. }
  237. return res.json(ApiResponse.success(result));
  238. };
  239. /**
  240. * @swagger
  241. *
  242. * /pages.updatePost:
  243. * get:
  244. * tags: [Pages, CrowiCompatibles]
  245. * operationId: getUpdatePostPage
  246. * summary: /pages.updatePost
  247. * description: Get UpdatePost setting list
  248. * parameters:
  249. * - in: query
  250. * name: path
  251. * schema:
  252. * $ref: '#/components/schemas/Page/properties/path'
  253. * responses:
  254. * 200:
  255. * description: Succeeded to get UpdatePost setting list.
  256. * content:
  257. * application/json:
  258. * schema:
  259. * properties:
  260. * ok:
  261. * $ref: '#/components/schemas/V1Response/properties/ok'
  262. * updatePost:
  263. * $ref: '#/components/schemas/UpdatePost'
  264. * 403:
  265. * $ref: '#/components/responses/403'
  266. * 500:
  267. * $ref: '#/components/responses/500'
  268. */
  269. /**
  270. * @api {get} /pages.updatePost
  271. * @apiName Get UpdatePost setting list
  272. * @apiGroup Page
  273. *
  274. * @apiParam {String} path
  275. */
  276. api.getUpdatePost = function(req, res) {
  277. const path = req.query.path;
  278. if (!path) {
  279. return res.json(ApiResponse.error({}));
  280. }
  281. UpdatePost.findSettingsByPath(path)
  282. .then((data) => {
  283. // eslint-disable-next-line no-param-reassign
  284. data = data.map((e) => {
  285. return e.channel;
  286. });
  287. debug('Found updatePost data', data);
  288. const result = { updatePost: data };
  289. return res.json(ApiResponse.success(result));
  290. })
  291. .catch((err) => {
  292. debug('Error occured while get setting', err);
  293. return res.json(ApiResponse.error({}));
  294. });
  295. };
  296. validator.remove = [
  297. body('completely')
  298. .custom(v => v === 'true' || v === true || v == null)
  299. .withMessage('The body property "completely" must be "true" or true. (Omit param for false)'),
  300. body('recursively')
  301. .custom(v => v === 'true' || v === true || v == null)
  302. .withMessage('The body property "recursively" must be "true" or true. (Omit param for false)'),
  303. ];
  304. /**
  305. * @api {post} /pages.remove Remove page
  306. * @apiName RemovePage
  307. * @apiGroup Page
  308. *
  309. * @apiParam {String} page_id Page Id.
  310. * @apiParam {String} revision_id
  311. */
  312. api.remove = async function(req, res) {
  313. const pageId = req.body.page_id;
  314. const previousRevision = req.body.revision_id || null;
  315. const { recursively: isRecursively, completely: isCompletely } = req.body;
  316. const options = {};
  317. const activityParameters = {
  318. ip: req.ip,
  319. endpoint: req.originalUrl,
  320. };
  321. /** @type {import('../models/page').PageDocument | undefined} */
  322. const page = await Page.findByIdAndViewer(pageId, req.user, null, true);
  323. if (page == null) {
  324. return res.json(ApiResponse.error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  325. }
  326. if (page.isEmpty && !isRecursively) {
  327. return res.json(ApiResponse.error('Empty pages cannot be single deleted', 'single_deletion_empty_pages'));
  328. }
  329. const creatorId = await crowi.pageService.getCreatorIdForCanDelete(page);
  330. debug('Delete page', page._id, page.path);
  331. try {
  332. if (isCompletely) {
  333. const userRelatedGroups = await crowi.pageGrantService.getUserRelatedGroups(req.user);
  334. const canDeleteCompletely = crowi.pageService.canDeleteCompletely(page, creatorId, req.user, isRecursively, userRelatedGroups);
  335. if (!canDeleteCompletely) {
  336. return res.json(ApiResponse.error('You cannot delete this page completely', 'complete_deletion_not_allowed_for_user'));
  337. }
  338. if (pagePathUtils.isUsersHomepage(page.path)) {
  339. if (!crowi.pageService.canDeleteUserHomepageByConfig()) {
  340. return res.json(ApiResponse.error('Could not delete user homepage'));
  341. }
  342. if (!await crowi.pageService.isUsersHomepageOwnerAbsent(page.path)) {
  343. return res.json(ApiResponse.error('Could not delete user homepage'));
  344. }
  345. }
  346. await crowi.pageService.deleteCompletely(page, req.user, options, isRecursively, false, activityParameters);
  347. }
  348. else {
  349. // behave like not found
  350. const notRecursivelyAndEmpty = page.isEmpty && !isRecursively;
  351. if (notRecursivelyAndEmpty) {
  352. return res.json(ApiResponse.error(`Page '${pageId}' is not found.`, 'notfound'));
  353. }
  354. if (!page.isEmpty && !page.isUpdatable(previousRevision)) {
  355. return res.json(ApiResponse.error('Someone could update this page, so couldn\'t delete.', 'outdated'));
  356. }
  357. if (!crowi.pageService.canDelete(page, creatorId, req.user, isRecursively)) {
  358. return res.json(ApiResponse.error('You cannot delete this page', 'user_not_admin'));
  359. }
  360. if (pagePathUtils.isUsersHomepage(page.path)) {
  361. if (!crowi.pageService.canDeleteUserHomepageByConfig()) {
  362. return res.json(ApiResponse.error('Could not delete user homepage'));
  363. }
  364. if (!await crowi.pageService.isUsersHomepageOwnerAbsent(page.path)) {
  365. return res.json(ApiResponse.error('Could not delete user homepage'));
  366. }
  367. }
  368. await crowi.pageService.deletePage(page, req.user, options, isRecursively, activityParameters);
  369. }
  370. }
  371. catch (err) {
  372. logger.error('Error occured while get setting', err);
  373. return res.json(ApiResponse.error('Failed to delete page.', err.message));
  374. }
  375. debug('Page deleted', page.path);
  376. const result = {};
  377. result.path = page.path;
  378. result.isRecursively = isRecursively;
  379. result.isCompletely = isCompletely;
  380. res.json(ApiResponse.success(result));
  381. try {
  382. // global notification
  383. await globalNotificationService.fire(GlobalNotificationSettingEvent.PAGE_DELETE, page, req.user);
  384. }
  385. catch (err) {
  386. logger.error('Delete notification failed', err);
  387. }
  388. };
  389. validator.revertRemove = [
  390. body('recursively')
  391. .optional()
  392. .custom(v => v === 'true' || v === true || v == null)
  393. .withMessage('The body property "recursively" must be "true" or true. (Omit param for false)'),
  394. ];
  395. /**
  396. * @api {post} /pages.revertRemove Revert removed page
  397. * @apiName RevertRemovePage
  398. * @apiGroup Page
  399. *
  400. * @apiParam {String} page_id Page Id.
  401. */
  402. api.revertRemove = async function(req, res, options) {
  403. const pageId = req.body.page_id;
  404. // get recursively flag
  405. const isRecursively = req.body.recursively;
  406. const activityParameters = {
  407. ip: req.ip,
  408. endpoint: req.originalUrl,
  409. };
  410. let page;
  411. try {
  412. page = await Page.findByIdAndViewer(pageId, req.user);
  413. if (page == null) {
  414. throw new Error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden');
  415. }
  416. page = await crowi.pageService.revertDeletedPage(page, req.user, {}, isRecursively, activityParameters);
  417. }
  418. catch (err) {
  419. if (err instanceof PathAlreadyExistsError) {
  420. logger.error('Path already exists', err);
  421. return res.json(ApiResponse.error(err, 'already_exists', err.targetPath));
  422. }
  423. logger.error('Error occured while get setting', err);
  424. return res.json(ApiResponse.error(err));
  425. }
  426. const result = {};
  427. result.page = page; // TODO consider to use serializePageSecurely method -- 2018.08.06 Yuki Takei
  428. return res.json(ApiResponse.success(result));
  429. };
  430. /**
  431. * @api {post} /pages.unlink Remove the redirecting page
  432. * @apiName UnlinkPage
  433. * @apiGroup Page
  434. *
  435. * @apiParam {String} page_id Page Id.
  436. * @apiParam {String} revision_id
  437. */
  438. api.unlink = async function(req, res) {
  439. const path = req.body.path;
  440. try {
  441. await PageRedirect.removePageRedirectsByToPath(path);
  442. logger.debug('Redirect Page deleted', path);
  443. }
  444. catch (err) {
  445. logger.error('Error occured while get setting', err);
  446. return res.json(ApiResponse.error('Failed to delete redirect page.'));
  447. }
  448. const result = { path };
  449. return res.json(ApiResponse.success(result));
  450. };
  451. return actions;
  452. };