page.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. /* eslint-disable @typescript-eslint/no-explicit-any */
  2. import mongoose, {
  3. Schema, Model, Document, AnyObject,
  4. } from 'mongoose';
  5. import mongoosePaginate from 'mongoose-paginate-v2';
  6. import uniqueValidator from 'mongoose-unique-validator';
  7. import nodePath from 'path';
  8. import { getOrCreateModel, pagePathUtils, getModelSafely } from '@growi/core';
  9. import loggerFactory from '../../utils/logger';
  10. import Crowi from '../crowi';
  11. import { IPage } from '../../interfaces/page';
  12. import { getPageSchema, PageQueryBuilder } from './obsolete-page';
  13. const { isTopPage, collectAncestorPaths } = pagePathUtils;
  14. const logger = loggerFactory('growi:models:page');
  15. /*
  16. * define schema
  17. */
  18. const GRANT_PUBLIC = 1;
  19. const GRANT_RESTRICTED = 2;
  20. const GRANT_SPECIFIED = 3; // DEPRECATED
  21. const GRANT_OWNER = 4;
  22. const GRANT_USER_GROUP = 5;
  23. const PAGE_GRANT_ERROR = 1;
  24. const STATUS_PUBLISHED = 'published';
  25. const STATUS_DELETED = 'deleted';
  26. export interface PageDocument extends IPage, Document {}
  27. type TargetAndAncestorsResult = {
  28. targetAndAncestors: PageDocument[]
  29. rootPage: PageDocument
  30. }
  31. export interface PageModel extends Model<PageDocument> {
  32. [x: string]: any; // for obsolete methods
  33. createEmptyPagesByPaths(paths: string[], publicOnly?: boolean): Promise<void>
  34. getParentIdAndFillAncestors(path: string, parent: (PageDocument & { _id: any }) | null): Promise<string | null>
  35. findByPathAndViewer(path: string | null, user, userGroups?, useFindOne?: boolean, includeEmpty?: boolean): Promise<PageDocument[]>
  36. findTargetAndAncestorsByPathOrId(pathOrId: string): Promise<TargetAndAncestorsResult>
  37. findChildrenByParentPathOrIdAndViewer(parentPathOrId: string, user, userGroups?): Promise<PageDocument[]>
  38. findAncestorsChildrenByPathAndViewer(path: string, user, userGroups?): Promise<Record<string, PageDocument[]>>
  39. PageQueryBuilder: typeof PageQueryBuilder
  40. GRANT_PUBLIC
  41. GRANT_RESTRICTED
  42. GRANT_SPECIFIED
  43. GRANT_OWNER
  44. GRANT_USER_GROUP
  45. PAGE_GRANT_ERROR
  46. STATUS_PUBLISHED
  47. STATUS_DELETED
  48. }
  49. type IObjectId = mongoose.Types.ObjectId;
  50. const ObjectId = mongoose.Schema.Types.ObjectId;
  51. const schema = new Schema<PageDocument, PageModel>({
  52. parent: {
  53. type: ObjectId, ref: 'Page', index: true, default: null,
  54. },
  55. descendantCount: { type: Number, default: 0 },
  56. isEmpty: { type: Boolean, default: false },
  57. path: {
  58. type: String, required: true, index: true,
  59. },
  60. revision: { type: ObjectId, ref: 'Revision' },
  61. redirectTo: { type: String, index: true },
  62. status: { type: String, default: STATUS_PUBLISHED, index: true },
  63. grant: { type: Number, default: GRANT_PUBLIC, index: true },
  64. grantedUsers: [{ type: ObjectId, ref: 'User' }],
  65. grantedGroup: { type: ObjectId, ref: 'UserGroup', index: true },
  66. creator: { type: ObjectId, ref: 'User', index: true },
  67. lastUpdateUser: { type: ObjectId, ref: 'User' },
  68. liker: [{ type: ObjectId, ref: 'User' }],
  69. seenUsers: [{ type: ObjectId, ref: 'User' }],
  70. commentCount: { type: Number, default: 0 },
  71. slackChannels: { type: String },
  72. pageIdOnHackmd: { type: String },
  73. revisionHackmdSynced: { type: ObjectId, ref: 'Revision' }, // the revision that is synced to HackMD
  74. hasDraftOnHackmd: { type: Boolean }, // set true if revision and revisionHackmdSynced are same but HackMD document has modified
  75. createdAt: { type: Date, default: new Date() },
  76. updatedAt: { type: Date, default: new Date() },
  77. deleteUser: { type: ObjectId, ref: 'User' },
  78. deletedAt: { type: Date },
  79. }, {
  80. toJSON: { getters: true },
  81. toObject: { getters: true },
  82. });
  83. // apply plugins
  84. schema.plugin(mongoosePaginate);
  85. schema.plugin(uniqueValidator);
  86. const hasSlash = (str: string): boolean => {
  87. return str.includes('/');
  88. };
  89. /*
  90. * Generate RegExp instance for one level lower path
  91. */
  92. const generateChildrenRegExp = (path: string): RegExp => {
  93. // https://regex101.com/r/laJGzj/1
  94. // ex. /any_level1
  95. if (isTopPage(path)) return new RegExp(/^\/[^/]+$/);
  96. // https://regex101.com/r/mrDJrx/1
  97. // ex. /parent/any_child OR /any_level1
  98. return new RegExp(`^${path}(\\/[^/]+)\\/?$`);
  99. };
  100. /*
  101. * Create empty pages if the page in paths didn't exist
  102. */
  103. schema.statics.createEmptyPagesByPaths = async function(paths: string[], publicOnly = false): Promise<void> {
  104. // find existing parents
  105. const builder = new PageQueryBuilder(this.find(publicOnly ? { grant: GRANT_PUBLIC } : {}, { _id: 0, path: 1 }), true);
  106. const existingPages = await builder
  107. .addConditionToListByPathsArray(paths)
  108. .query
  109. .lean()
  110. .exec();
  111. const existingPagePaths = existingPages.map(page => page.path);
  112. // paths to create empty pages
  113. const notExistingPagePaths = paths.filter(path => !existingPagePaths.includes(path));
  114. // insertMany empty pages
  115. try {
  116. await this.insertMany(notExistingPagePaths.map(path => ({ path, isEmpty: true })));
  117. }
  118. catch (err) {
  119. logger.error('Failed to insert empty pages.', err);
  120. throw err;
  121. }
  122. };
  123. /*
  124. * Find the parent and update if the parent exists.
  125. * If not,
  126. * - first run createEmptyPagesByPaths with ancestor's paths to ensure all the ancestors exist
  127. * - second update ancestor pages' parent
  128. * - finally return the target's parent page id
  129. */
  130. schema.statics.getParentIdAndFillAncestors = async function(path: string, parent: PageDocument | null): Promise<Schema.Types.ObjectId> {
  131. const parentPath = nodePath.dirname(path);
  132. if (parent != null) {
  133. return parent._id;
  134. }
  135. /*
  136. * Fill parents if parent is null
  137. */
  138. const ancestorPaths = collectAncestorPaths(path); // paths of parents need to be created
  139. // just create ancestors with empty pages
  140. await this.createEmptyPagesByPaths(ancestorPaths);
  141. // find ancestors
  142. const builder = new PageQueryBuilder(this.find({}, { _id: 1, path: 1 }), true);
  143. const ancestors = await builder
  144. .addConditionToListByPathsArray(ancestorPaths)
  145. .addConditionToSortPagesByDescPath()
  146. .query
  147. .lean()
  148. .exec();
  149. const ancestorsMap = new Map(); // Map<path, _id>
  150. ancestors.forEach(page => !ancestorsMap.has(page.path) && ancestorsMap.set(page.path, page._id)); // the earlier element should be the true ancestor
  151. // bulkWrite to update ancestors
  152. const nonRootAncestors = ancestors.filter(page => !isTopPage(page.path));
  153. const operations = nonRootAncestors.map((page) => {
  154. const { path } = page;
  155. const parentPath = nodePath.dirname(path);
  156. return {
  157. updateOne: {
  158. filter: {
  159. path,
  160. },
  161. update: {
  162. parent: ancestorsMap.get(parentPath),
  163. },
  164. },
  165. };
  166. });
  167. await this.bulkWrite(operations);
  168. const parentId = ancestorsMap.get(parentPath);
  169. return parentId;
  170. };
  171. // Utility function to add viewer condition to PageQueryBuilder instance
  172. const addViewerCondition = async(queryBuilder: PageQueryBuilder, user, userGroups = null): Promise<void> => {
  173. let relatedUserGroups = userGroups;
  174. if (user != null && relatedUserGroups == null) {
  175. const UserGroupRelation: any = mongoose.model('UserGroupRelation');
  176. relatedUserGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  177. }
  178. queryBuilder.addConditionToFilteringByViewer(user, relatedUserGroups, false);
  179. };
  180. /*
  181. * Find a page by path and viewer. Pass false to useFindOne to use findOne method.
  182. */
  183. schema.statics.findByPathAndViewer = async function(
  184. path: string | null, user, userGroups = null, useFindOne = true, includeEmpty = false,
  185. ): Promise<PageDocument | PageDocument[] | null> {
  186. if (path == null) {
  187. throw new Error('path is required.');
  188. }
  189. const baseQuery = useFindOne ? this.findOne({ path }) : this.find({ path });
  190. const queryBuilder = new PageQueryBuilder(baseQuery, includeEmpty);
  191. const User = getModelSafely('User') || require('~/server/models/user')();
  192. queryBuilder.populateDataToList(User.USER_FIELDS_EXCEPT_CONFIDENTIAL);
  193. await addViewerCondition(queryBuilder, user, userGroups);
  194. return queryBuilder.query.exec();
  195. };
  196. /*
  197. * Find all ancestor pages by path. When duplicate pages found, it uses the oldest page as a result
  198. * The result will include the target as well
  199. */
  200. schema.statics.findTargetAndAncestorsByPathOrId = async function(pathOrId: string, user, userGroups): Promise<TargetAndAncestorsResult> {
  201. let path;
  202. if (!hasSlash(pathOrId)) {
  203. const _id = pathOrId;
  204. const page = await this.findOne({ _id });
  205. if (page == null) throw new Error('Page not found.');
  206. path = page.path;
  207. }
  208. else {
  209. path = pathOrId;
  210. }
  211. const ancestorPaths = collectAncestorPaths(path);
  212. ancestorPaths.push(path); // include target
  213. // Do not populate
  214. const queryBuilder = new PageQueryBuilder(this.find(), true);
  215. await addViewerCondition(queryBuilder, user, userGroups);
  216. const _targetAndAncestors: PageDocument[] = await queryBuilder
  217. .addConditionAsMigrated()
  218. .addConditionToListByPathsArray(ancestorPaths)
  219. .addConditionToMinimizeDataForRendering()
  220. .addConditionToSortPagesByDescPath()
  221. .query
  222. .lean()
  223. .exec();
  224. // no same path pages
  225. const ancestorsMap = new Map<string, PageDocument>();
  226. _targetAndAncestors.forEach(page => ancestorsMap.set(page.path, page));
  227. const targetAndAncestors = Array.from(ancestorsMap.values());
  228. const rootPage = targetAndAncestors[targetAndAncestors.length - 1];
  229. return { targetAndAncestors, rootPage };
  230. };
  231. /*
  232. * Find all children by parent's path or id. Using id should be prioritized
  233. */
  234. schema.statics.findChildrenByParentPathOrIdAndViewer = async function(parentPathOrId: string, user, userGroups = null): Promise<PageDocument[]> {
  235. let queryBuilder: PageQueryBuilder;
  236. if (hasSlash(parentPathOrId)) {
  237. const path = parentPathOrId;
  238. const regexp = generateChildrenRegExp(path);
  239. queryBuilder = new PageQueryBuilder(this.find({ path: { $regex: regexp } }), true);
  240. }
  241. else {
  242. const parentId = parentPathOrId;
  243. queryBuilder = new PageQueryBuilder(this.find({ parent: parentId }), true);
  244. }
  245. await addViewerCondition(queryBuilder, user, userGroups);
  246. return queryBuilder
  247. .addConditionToSortPagesByAscPath()
  248. .query
  249. .lean()
  250. .exec();
  251. };
  252. schema.statics.findAncestorsChildrenByPathAndViewer = async function(path: string, user, userGroups = null): Promise<Record<string, PageDocument[]>> {
  253. const ancestorPaths = isTopPage(path) ? ['/'] : collectAncestorPaths(path); // root path is necessary for rendering
  254. const regexps = ancestorPaths.map(path => new RegExp(generateChildrenRegExp(path))); // cannot use re2
  255. // get pages at once
  256. const queryBuilder = new PageQueryBuilder(this.find({ path: { $in: regexps } }), true);
  257. await addViewerCondition(queryBuilder, user, userGroups);
  258. const _pages = await queryBuilder
  259. .addConditionAsMigrated()
  260. .addConditionToMinimizeDataForRendering()
  261. .addConditionToSortPagesByAscPath()
  262. .query
  263. .lean()
  264. .exec();
  265. // mark target
  266. const pages = _pages.map((page: PageDocument & {isTarget?: boolean}) => {
  267. if (page.path === path) {
  268. page.isTarget = true;
  269. }
  270. return page;
  271. });
  272. /*
  273. * If any non-migrated page is found during creating the pathToChildren map, it will stop incrementing at that moment
  274. */
  275. const pathToChildren: Record<string, PageDocument[]> = {};
  276. const sortedPaths = ancestorPaths.sort((a, b) => a.length - b.length); // sort paths by path.length
  277. sortedPaths.every((path) => {
  278. const children = pages.filter(page => nodePath.dirname(page.path) === path);
  279. if (children.length === 0) {
  280. return false; // break when children do not exist
  281. }
  282. pathToChildren[path] = children;
  283. return true;
  284. });
  285. return pathToChildren;
  286. };
  287. /*
  288. * Utils from obsolete-page.js
  289. */
  290. async function pushRevision(pageData, newRevision, user) {
  291. await newRevision.save();
  292. pageData.revision = newRevision;
  293. pageData.lastUpdateUser = user;
  294. pageData.updatedAt = Date.now();
  295. return pageData.save();
  296. }
  297. /**
  298. * return aggregate condition to get following pages
  299. * - page that has the same path as the provided path
  300. * - pages that are descendants of the above page
  301. * pages without parent will be ignored
  302. */
  303. schema.statics.getAggrConditionForPageWithProvidedPathAndDescendants = function(path:string) {
  304. let match;
  305. if (isTopPage(path)) {
  306. match = {
  307. // https://regex101.com/r/Kip2rV/1
  308. $match: { $or: [{ path: { $regex: '^/.*' }, parent: { $ne: null } }, { path: '/' }] },
  309. };
  310. }
  311. else {
  312. match = {
  313. // https://regex101.com/r/mJvGrG/1
  314. $match: { path: { $regex: `^${path}(/.*|$)` }, parent: { $ne: null } },
  315. };
  316. }
  317. return [
  318. match,
  319. {
  320. $project: {
  321. path: 1,
  322. parent: 1,
  323. field_length: { $strLenCP: '$path' },
  324. },
  325. },
  326. { $sort: { field_length: -1 } },
  327. { $project: { field_length: 0 } },
  328. ];
  329. };
  330. /**
  331. * add/subtract descendantCount of pages with provided paths by increment.
  332. * increment can be negative number
  333. */
  334. schema.statics.incrementDescendantCountOfPaths = async function(paths:string[], increment: number):Promise<void> {
  335. const pages = await this.aggregate([{ $match: { path: { $in: paths } } }]);
  336. const operations = pages.map((page) => {
  337. return {
  338. updateOne: {
  339. filter: { path: page.path },
  340. update: { descendantCount: page.descendantCount + increment },
  341. },
  342. };
  343. });
  344. await this.bulkWrite(operations);
  345. };
  346. // update descendantCount of a page with provided id
  347. schema.statics.recountDescendantCountOfSelfAndDescendants = async function(id:mongoose.Types.ObjectId):Promise<void> {
  348. const res = await this.aggregate(
  349. [
  350. {
  351. $match: {
  352. parent: id,
  353. },
  354. },
  355. {
  356. $project: {
  357. path: 1,
  358. parent: 1,
  359. descendantCount: 1,
  360. },
  361. },
  362. {
  363. $group: {
  364. _id: '$parent',
  365. sumOfDescendantCount: {
  366. $sum: '$descendantCount',
  367. },
  368. sumOfDocsCount: {
  369. $sum: 1,
  370. },
  371. },
  372. },
  373. {
  374. $set: {
  375. descendantCount: {
  376. $sum: ['$sumOfDescendantCount', '$sumOfDocsCount'],
  377. },
  378. },
  379. },
  380. ],
  381. );
  382. const query = { descendantCount: res.length === 0 ? 0 : res[0].descendantCount };
  383. await this.findByIdAndUpdate(id, query);
  384. };
  385. /*
  386. * Merge obsolete page model methods and define new methods which depend on crowi instance
  387. */
  388. export default (crowi: Crowi): any => {
  389. let pageEvent;
  390. if (crowi != null) {
  391. pageEvent = crowi.event('page');
  392. }
  393. schema.statics.create = async function(path, body, user, options = {}) {
  394. if (crowi.pageGrantService == null || crowi.configManager == null) {
  395. throw Error('Crowi is not setup');
  396. }
  397. const isV5Compatible = crowi.configManager.getConfig('crowi', 'app:isV5Compatible');
  398. // v4 compatible process
  399. if (!isV5Compatible) {
  400. return this.createV4(path, body, user, options);
  401. }
  402. const Page = this;
  403. const Revision = crowi.model('Revision');
  404. const {
  405. format = 'markdown', redirectTo, grantUserGroupId,
  406. } = options;
  407. let grant = options.grant;
  408. // sanitize path
  409. path = crowi.xss.process(path); // eslint-disable-line no-param-reassign
  410. // throw if exists
  411. const isExist = (await this.count({ path, isEmpty: false })) > 0; // not validate empty page
  412. if (isExist) {
  413. throw new Error('Cannot create new page to existed path');
  414. }
  415. // force public
  416. if (isTopPage(path)) {
  417. grant = GRANT_PUBLIC;
  418. }
  419. // find an existing empty page
  420. const emptyPage = await Page.findOne({ path, isEmpty: true });
  421. /*
  422. * UserGroup & Owner validation
  423. */
  424. if (grant !== GRANT_RESTRICTED) {
  425. let isGrantNormalized = false;
  426. try {
  427. // It must check descendants as well if emptyTarget is not null
  428. const shouldCheckDescendants = emptyPage != null;
  429. const newGrantedUserIds = grant === GRANT_OWNER ? [user._id] as IObjectId[] : undefined;
  430. isGrantNormalized = await crowi.pageGrantService.isGrantNormalized(path, grant, newGrantedUserIds, grantUserGroupId, shouldCheckDescendants);
  431. }
  432. catch (err) {
  433. logger.error(`Failed to validate grant of page at "${path}" of grant ${grant}:`, err);
  434. throw err;
  435. }
  436. if (!isGrantNormalized) {
  437. throw Error('The selected grant or grantedGroup is not assignable to this page.');
  438. }
  439. }
  440. /*
  441. * update empty page if exists, if not, create a new page
  442. */
  443. let page;
  444. if (emptyPage != null) {
  445. page = emptyPage;
  446. page.isEmpty = false;
  447. }
  448. else {
  449. page = new Page();
  450. }
  451. let parentId: string | null = null;
  452. const parentPath = nodePath.dirname(path);
  453. const parent = await this.findOne({ path: parentPath }); // find the oldest parent which must always be the true parent
  454. if (!isTopPage(path)) {
  455. parentId = await Page.getParentIdAndFillAncestors(path, parent);
  456. }
  457. page.path = path;
  458. page.creator = user;
  459. page.lastUpdateUser = user;
  460. page.redirectTo = redirectTo;
  461. page.status = STATUS_PUBLISHED;
  462. // set parent to null when GRANT_RESTRICTED
  463. if (grant === GRANT_RESTRICTED) {
  464. page.parent = null;
  465. }
  466. else {
  467. page.parent = parentId;
  468. }
  469. page.applyScope(user, grant, grantUserGroupId);
  470. let savedPage = await page.save();
  471. /*
  472. * After save
  473. */
  474. const newRevision = Revision.prepareRevision(savedPage, body, null, user, { format });
  475. const revision = await pushRevision(savedPage, newRevision, user);
  476. savedPage = await this.findByPath(revision.path);
  477. await savedPage.populateDataToShowRevision();
  478. pageEvent.emit('create', savedPage, user);
  479. return savedPage;
  480. };
  481. schema.statics.updatePage = async function(pageData, body, previousBody, user, options = {}) {
  482. if (crowi.configManager == null || crowi.pageGrantService == null) {
  483. throw Error('Crowi is not set up');
  484. }
  485. const isV5Compatible = crowi.configManager.getConfig('crowi', 'app:isV5Compatible');
  486. if (!isV5Compatible) {
  487. // v4 compatible process
  488. return this.updatePageV4(pageData, body, previousBody, user, options);
  489. }
  490. const Revision = mongoose.model('Revision') as any; // TODO: Typescriptize model
  491. const grant = options.grant || pageData.grant; // use the previous data if absence
  492. const grantUserGroupId = options.grantUserGroupId || pageData.grantUserGroupId; // use the previous data if absence
  493. const isSyncRevisionToHackmd = options.isSyncRevisionToHackmd;
  494. const grantedUserIds = pageData.grantedUserIds || [user._id];
  495. const newPageData = pageData;
  496. if (grant === GRANT_RESTRICTED) {
  497. newPageData.parent = null;
  498. }
  499. else {
  500. /*
  501. * UserGroup & Owner validation
  502. */
  503. let isGrantNormalized = false;
  504. try {
  505. const shouldCheckDescendants = true;
  506. isGrantNormalized = await crowi.pageGrantService.isGrantNormalized(pageData.path, grant, grantedUserIds, grantUserGroupId, shouldCheckDescendants);
  507. }
  508. catch (err) {
  509. logger.error(`Failed to validate grant of page at "${pageData.path}" of grant ${grant}:`, err);
  510. throw err;
  511. }
  512. if (!isGrantNormalized) {
  513. throw Error('The selected grant or grantedGroup is not assignable to this page.');
  514. }
  515. }
  516. newPageData.applyScope(user, grant, grantUserGroupId);
  517. // update existing page
  518. let savedPage = await newPageData.save();
  519. const newRevision = await Revision.prepareRevision(newPageData, body, previousBody, user);
  520. const revision = await pushRevision(savedPage, newRevision, user);
  521. savedPage = await this.findByPath(revision.path);
  522. await savedPage.populateDataToShowRevision();
  523. if (isSyncRevisionToHackmd) {
  524. savedPage = await this.syncRevisionToHackmd(savedPage);
  525. }
  526. pageEvent.emit('update', savedPage, user);
  527. return savedPage;
  528. };
  529. // add old page schema methods
  530. const pageSchema = getPageSchema(crowi);
  531. schema.methods = { ...pageSchema.methods, ...schema.methods };
  532. schema.statics = { ...pageSchema.statics, ...schema.statics };
  533. return getOrCreateModel<PageDocument, PageModel>('Page', schema);
  534. };
  535. /*
  536. * Aggregation utilities
  537. */
  538. // TODO: use the original type when upgraded https://github.com/Automattic/mongoose/blob/master/index.d.ts#L3090
  539. type PipelineStageMatch = {
  540. $match: AnyObject
  541. };
  542. export const generateGrantCondition = async(
  543. user, _userGroups, showAnyoneKnowsLink = false, showPagesRestrictedByOwner = false, showPagesRestrictedByGroup = false,
  544. ): Promise<PipelineStageMatch> => {
  545. let userGroups = _userGroups;
  546. if (user != null && userGroups == null) {
  547. const UserGroupRelation: any = mongoose.model('UserGroupRelation');
  548. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  549. }
  550. const grantConditions: AnyObject[] = [
  551. { grant: null },
  552. { grant: GRANT_PUBLIC },
  553. ];
  554. if (showAnyoneKnowsLink) {
  555. grantConditions.push({ grant: GRANT_RESTRICTED });
  556. }
  557. if (showPagesRestrictedByOwner) {
  558. grantConditions.push(
  559. { grant: GRANT_SPECIFIED },
  560. { grant: GRANT_OWNER },
  561. );
  562. }
  563. else if (user != null) {
  564. grantConditions.push(
  565. { grant: GRANT_SPECIFIED, grantedUsers: user._id },
  566. { grant: GRANT_OWNER, grantedUsers: user._id },
  567. );
  568. }
  569. if (showPagesRestrictedByGroup) {
  570. grantConditions.push(
  571. { grant: GRANT_USER_GROUP },
  572. );
  573. }
  574. else if (userGroups != null && userGroups.length > 0) {
  575. grantConditions.push(
  576. { grant: GRANT_USER_GROUP, grantedGroup: { $in: userGroups } },
  577. );
  578. }
  579. return {
  580. $match: {
  581. $or: grantConditions,
  582. },
  583. };
  584. };