page.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  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.exist:
  196. * get:
  197. * tags: [Pages]
  198. * operationId: getPageExistence
  199. * summary: /pages.exist
  200. * description: Get page existence
  201. * parameters:
  202. * - in: query
  203. * name: pagePaths
  204. * schema:
  205. * type: string
  206. * description: Page path list in JSON Array format
  207. * example: '["/", "/user/unknown"]'
  208. * responses:
  209. * 200:
  210. * description: Succeeded to get page existence.
  211. * content:
  212. * application/json:
  213. * schema:
  214. * properties:
  215. * ok:
  216. * $ref: '#/components/schemas/V1Response/properties/ok'
  217. * pages:
  218. * type: string
  219. * description: Properties of page path and existence
  220. * example: '{"/": true, "/user/unknown": false}'
  221. * 403:
  222. * $ref: '#/components/responses/403'
  223. * 500:
  224. * $ref: '#/components/responses/500'
  225. */
  226. /**
  227. * @api {get} /pages.exist Get if page exists
  228. * @apiName GetPage
  229. * @apiGroup Page
  230. *
  231. * @apiParam {String} pages (stringified JSON)
  232. */
  233. api.exist = async function(req, res) {
  234. const pagePaths = JSON.parse(req.query.pagePaths || '[]');
  235. const pages = {};
  236. await Promise.all(pagePaths.map(async(path) => {
  237. // check page existence
  238. const isExist = await Page.count({ path }) > 0;
  239. pages[path] = isExist;
  240. return;
  241. }));
  242. const result = { pages };
  243. return res.json(ApiResponse.success(result));
  244. };
  245. /**
  246. * @swagger
  247. *
  248. * /pages.getPageTag:
  249. * get:
  250. * tags: [Pages]
  251. * operationId: getPageTag
  252. * summary: /pages.getPageTag
  253. * description: Get page tag
  254. * parameters:
  255. * - in: query
  256. * name: pageId
  257. * schema:
  258. * $ref: '#/components/schemas/Page/properties/_id'
  259. * responses:
  260. * 200:
  261. * description: Succeeded to get page tags.
  262. * content:
  263. * application/json:
  264. * schema:
  265. * properties:
  266. * ok:
  267. * $ref: '#/components/schemas/V1Response/properties/ok'
  268. * tags:
  269. * $ref: '#/components/schemas/Tags'
  270. * 403:
  271. * $ref: '#/components/responses/403'
  272. * 500:
  273. * $ref: '#/components/responses/500'
  274. */
  275. /**
  276. * @api {get} /pages.getPageTag get page tags
  277. * @apiName GetPageTag
  278. * @apiGroup Page
  279. *
  280. * @apiParam {String} pageId
  281. */
  282. api.getPageTag = async function(req, res) {
  283. const result = {};
  284. try {
  285. result.tags = await PageTagRelation.listTagNamesByPage(req.query.pageId);
  286. }
  287. catch (err) {
  288. return res.json(ApiResponse.error(err));
  289. }
  290. return res.json(ApiResponse.success(result));
  291. };
  292. /**
  293. * @swagger
  294. *
  295. * /pages.updatePost:
  296. * get:
  297. * tags: [Pages, CrowiCompatibles]
  298. * operationId: getUpdatePostPage
  299. * summary: /pages.updatePost
  300. * description: Get UpdatePost setting list
  301. * parameters:
  302. * - in: query
  303. * name: path
  304. * schema:
  305. * $ref: '#/components/schemas/Page/properties/path'
  306. * responses:
  307. * 200:
  308. * description: Succeeded to get UpdatePost setting list.
  309. * content:
  310. * application/json:
  311. * schema:
  312. * properties:
  313. * ok:
  314. * $ref: '#/components/schemas/V1Response/properties/ok'
  315. * updatePost:
  316. * $ref: '#/components/schemas/UpdatePost'
  317. * 403:
  318. * $ref: '#/components/responses/403'
  319. * 500:
  320. * $ref: '#/components/responses/500'
  321. */
  322. /**
  323. * @api {get} /pages.updatePost
  324. * @apiName Get UpdatePost setting list
  325. * @apiGroup Page
  326. *
  327. * @apiParam {String} path
  328. */
  329. api.getUpdatePost = function(req, res) {
  330. const path = req.query.path;
  331. if (!path) {
  332. return res.json(ApiResponse.error({}));
  333. }
  334. UpdatePost.findSettingsByPath(path)
  335. .then((data) => {
  336. // eslint-disable-next-line no-param-reassign
  337. data = data.map((e) => {
  338. return e.channel;
  339. });
  340. debug('Found updatePost data', data);
  341. const result = { updatePost: data };
  342. return res.json(ApiResponse.success(result));
  343. })
  344. .catch((err) => {
  345. debug('Error occured while get setting', err);
  346. return res.json(ApiResponse.error({}));
  347. });
  348. };
  349. validator.remove = [
  350. body('completely')
  351. .custom(v => v === 'true' || v === true || v == null)
  352. .withMessage('The body property "completely" must be "true" or true. (Omit param for false)'),
  353. body('recursively')
  354. .custom(v => v === 'true' || v === true || v == null)
  355. .withMessage('The body property "recursively" must be "true" or true. (Omit param for false)'),
  356. ];
  357. /**
  358. * @api {post} /pages.remove Remove page
  359. * @apiName RemovePage
  360. * @apiGroup Page
  361. *
  362. * @apiParam {String} page_id Page Id.
  363. * @apiParam {String} revision_id
  364. */
  365. api.remove = async function(req, res) {
  366. const pageId = req.body.page_id;
  367. const previousRevision = req.body.revision_id || null;
  368. const { recursively: isRecursively, completely: isCompletely } = req.body;
  369. const options = {};
  370. const activityParameters = {
  371. ip: req.ip,
  372. endpoint: req.originalUrl,
  373. };
  374. /** @type {import('../models/page').PageDocument | undefined} */
  375. const page = await Page.findByIdAndViewer(pageId, req.user, null, true);
  376. if (page == null) {
  377. return res.json(ApiResponse.error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  378. }
  379. if (page.isEmpty && !isRecursively) {
  380. return res.json(ApiResponse.error('Empty pages cannot be single deleted', 'single_deletion_empty_pages'));
  381. }
  382. // -- canDelete no longer needs creator,
  383. // however it might be required to retrieve the closest non-empty ancestor page's owner -- 2024.02.09 Yuki Takei
  384. //
  385. // let creator;
  386. // if (page.isEmpty) {
  387. // // If empty, the creator is inherited from the closest non-empty ancestor page.
  388. // const notEmptyClosestAncestor = await Page.findNonEmptyClosestAncestor(page.path);
  389. // creator = notEmptyClosestAncestor.creator;
  390. // }
  391. // else {
  392. // creator = page.creator;
  393. // }
  394. debug('Delete page', page._id, page.path);
  395. try {
  396. if (isCompletely) {
  397. const userRelatedGroups = await crowi.pageGrantService.getUserRelatedGroups(req.user);
  398. const canDeleteCompletely = crowi.pageService.canDeleteCompletely(page, req.user, isRecursively, userRelatedGroups);
  399. if (!canDeleteCompletely) {
  400. return res.json(ApiResponse.error('You cannot delete this page completely', 'complete_deletion_not_allowed_for_user'));
  401. }
  402. if (pagePathUtils.isUsersHomepage(page.path)) {
  403. if (!crowi.pageService.canDeleteUserHomepageByConfig()) {
  404. return res.json(ApiResponse.error('Could not delete user homepage'));
  405. }
  406. if (!await crowi.pageService.isUsersHomepageOwnerAbsent(page.path)) {
  407. return res.json(ApiResponse.error('Could not delete user homepage'));
  408. }
  409. }
  410. await crowi.pageService.deleteCompletely(page, req.user, options, isRecursively, false, activityParameters);
  411. }
  412. else {
  413. // behave like not found
  414. const notRecursivelyAndEmpty = page.isEmpty && !isRecursively;
  415. if (notRecursivelyAndEmpty) {
  416. return res.json(ApiResponse.error(`Page '${pageId}' is not found.`, 'notfound'));
  417. }
  418. if (!page.isEmpty && !page.isUpdatable(previousRevision)) {
  419. return res.json(ApiResponse.error('Someone could update this page, so couldn\'t delete.', 'outdated'));
  420. }
  421. if (!crowi.pageService.canDelete(page, req.user, isRecursively)) {
  422. return res.json(ApiResponse.error('You can not delete this page', 'user_not_admin'));
  423. }
  424. if (pagePathUtils.isUsersHomepage(page.path)) {
  425. if (!crowi.pageService.canDeleteUserHomepageByConfig()) {
  426. return res.json(ApiResponse.error('Could not delete user homepage'));
  427. }
  428. if (!await crowi.pageService.isUsersHomepageOwnerAbsent(page.path)) {
  429. return res.json(ApiResponse.error('Could not delete user homepage'));
  430. }
  431. }
  432. await crowi.pageService.deletePage(page, req.user, options, isRecursively, activityParameters);
  433. }
  434. }
  435. catch (err) {
  436. logger.error('Error occured while get setting', err);
  437. return res.json(ApiResponse.error('Failed to delete page.', err.message));
  438. }
  439. debug('Page deleted', page.path);
  440. const result = {};
  441. result.path = page.path;
  442. result.isRecursively = isRecursively;
  443. result.isCompletely = isCompletely;
  444. res.json(ApiResponse.success(result));
  445. try {
  446. // global notification
  447. await globalNotificationService.fire(GlobalNotificationSettingEvent.PAGE_DELETE, page, req.user);
  448. }
  449. catch (err) {
  450. logger.error('Delete notification failed', err);
  451. }
  452. };
  453. validator.revertRemove = [
  454. body('recursively')
  455. .optional()
  456. .custom(v => v === 'true' || v === true || v == null)
  457. .withMessage('The body property "recursively" must be "true" or true. (Omit param for false)'),
  458. ];
  459. /**
  460. * @api {post} /pages.revertRemove Revert removed page
  461. * @apiName RevertRemovePage
  462. * @apiGroup Page
  463. *
  464. * @apiParam {String} page_id Page Id.
  465. */
  466. api.revertRemove = async function(req, res, options) {
  467. const pageId = req.body.page_id;
  468. // get recursively flag
  469. const isRecursively = req.body.recursively;
  470. const activityParameters = {
  471. ip: req.ip,
  472. endpoint: req.originalUrl,
  473. };
  474. let page;
  475. try {
  476. page = await Page.findByIdAndViewer(pageId, req.user);
  477. if (page == null) {
  478. throw new Error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden');
  479. }
  480. page = await crowi.pageService.revertDeletedPage(page, req.user, {}, isRecursively, activityParameters);
  481. }
  482. catch (err) {
  483. if (err instanceof PathAlreadyExistsError) {
  484. logger.error('Path already exists', err);
  485. return res.json(ApiResponse.error(err, 'already_exists', err.targetPath));
  486. }
  487. logger.error('Error occured while get setting', err);
  488. return res.json(ApiResponse.error(err));
  489. }
  490. const result = {};
  491. result.page = page; // TODO consider to use serializePageSecurely method -- 2018.08.06 Yuki Takei
  492. return res.json(ApiResponse.success(result));
  493. };
  494. /**
  495. * @api {post} /pages.unlink Remove the redirecting page
  496. * @apiName UnlinkPage
  497. * @apiGroup Page
  498. *
  499. * @apiParam {String} page_id Page Id.
  500. * @apiParam {String} revision_id
  501. */
  502. api.unlink = async function(req, res) {
  503. const path = req.body.path;
  504. try {
  505. await PageRedirect.removePageRedirectsByToPath(path);
  506. logger.debug('Redirect Page deleted', path);
  507. }
  508. catch (err) {
  509. logger.error('Error occured while get setting', err);
  510. return res.json(ApiResponse.error('Failed to delete redirect page.'));
  511. }
  512. const result = { path };
  513. return res.json(ApiResponse.success(result));
  514. };
  515. return actions;
  516. };