user-group.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  1. import loggerFactory from '~/utils/logger';
  2. import { excludeTestIdsFromTargetIds } from '~/server/util/compare-objectId';
  3. import UserGroup from '~/server/models/user-group';
  4. import { apiV3FormValidator } from '../../middlewares/apiv3-form-validator';
  5. const logger = loggerFactory('growi:routes:apiv3:user-group'); // eslint-disable-line no-unused-vars
  6. const express = require('express');
  7. const router = express.Router();
  8. const { body, param, query } = require('express-validator');
  9. const { sanitizeQuery } = require('express-validator');
  10. const mongoose = require('mongoose');
  11. const ErrorV3 = require('../../models/vo/error-apiv3');
  12. const { serializeUserSecurely } = require('../../models/serializers/user-serializer');
  13. const { toPagingLimit, toPagingOffset } = require('../../util/express-validator/sanitizer');
  14. const { ObjectId } = mongoose.Types;
  15. /**
  16. * @swagger
  17. * tags:
  18. * name: UserGroup
  19. */
  20. module.exports = (crowi) => {
  21. const loginRequiredStrictly = require('../../middlewares/login-required')(crowi);
  22. const adminRequired = require('../../middlewares/admin-required')(crowi);
  23. const csrf = require('../../middlewares/csrf')(crowi);
  24. const {
  25. UserGroupRelation,
  26. User,
  27. Page,
  28. } = crowi.models;
  29. const validator = {
  30. create: [
  31. body('name', 'Group name is required').trim().exists({ checkFalsy: true }),
  32. body('description', 'Description must be a string').optional().isString(),
  33. body('parentId', 'ParentId must be a string').optional().isString(),
  34. ],
  35. update: [
  36. body('name', 'Group name is required').trim().exists({ checkFalsy: true }),
  37. body('description', 'Group description must be a string').optional().isString(),
  38. body('parentId', 'parentId must be a string').optional().isString(),
  39. body('forceUpdateParents', 'forceUpdateParents must be a boolean').optional().isBoolean(),
  40. ],
  41. delete: [
  42. param('id').trim().exists({ checkFalsy: true }),
  43. query('actionName').trim().exists({ checkFalsy: true }),
  44. query('transferToUserGroupId').trim(),
  45. ],
  46. listChildren: [
  47. query('parentIds', 'parentIds must be an array').optional().isArray(),
  48. query('includeGrandChildren', 'parentIds must be boolean').optional().isBoolean(),
  49. ],
  50. ancestorGroup: [
  51. query('groupId', 'groupId must be a string').optional().isString(),
  52. ],
  53. selectableGroups: [
  54. query('groupId', 'groupId must be a string').optional().isString(),
  55. ],
  56. users: {
  57. post: [
  58. param('id').trim().exists({ checkFalsy: true }),
  59. param('username').trim().exists({ checkFalsy: true }),
  60. ],
  61. delete: [
  62. param('id').trim().exists({ checkFalsy: true }),
  63. param('username').trim().exists({ checkFalsy: true }),
  64. ],
  65. },
  66. pages: {
  67. get: [
  68. param('id').trim().exists({ checkFalsy: true }),
  69. sanitizeQuery('limit').customSanitizer(toPagingLimit),
  70. sanitizeQuery('offset').customSanitizer(toPagingOffset),
  71. ],
  72. },
  73. };
  74. /**
  75. * @swagger
  76. *
  77. * paths:
  78. * /user-groups:
  79. * get:
  80. * tags: [UserGroup]
  81. * operationId: getUserGroup
  82. * summary: /user-groups
  83. * description: Get usergroups
  84. * responses:
  85. * 200:
  86. * description: usergroups are fetched
  87. * content:
  88. * application/json:
  89. * schema:
  90. * properties:
  91. * userGroups:
  92. * type: object
  93. * description: a result of `UserGroup.find`
  94. */
  95. router.get('/', loginRequiredStrictly, adminRequired, async(req, res) => { // TODO 85062: userGroups with no parent
  96. const { query } = req;
  97. // TODO 85062: improve sort
  98. try {
  99. const page = query.page != null ? parseInt(query.page) : undefined;
  100. const limit = query.limit != null ? parseInt(query.limit) : undefined;
  101. const offset = query.offset != null ? parseInt(query.offset) : undefined;
  102. const pagination = query.pagination != null ? query.pagination !== 'false' : undefined;
  103. const result = await UserGroup.findUserGroupsWithPagination({
  104. page, limit, offset, pagination,
  105. });
  106. const { docs: userGroups, totalDocs: totalUserGroups, limit: pagingLimit } = result;
  107. return res.apiv3({ userGroups, totalUserGroups, pagingLimit });
  108. }
  109. catch (err) {
  110. const msg = 'Error occurred in fetching user group list';
  111. logger.error('Error', err);
  112. return res.apiv3Err(new ErrorV3(msg, 'user-group-list-fetch-failed'));
  113. }
  114. });
  115. /**
  116. * @swagger
  117. *
  118. * paths:
  119. * /ancestors:
  120. * get:
  121. * tags: [UserGroup]
  122. * operationId: getAncestorUserGroups
  123. * summary: /ancestors
  124. * description: Get ancestor user groups.
  125. * parameters:
  126. * - name: groupId
  127. * in: query
  128. * required: true
  129. * description: id of userGroup
  130. * schema:
  131. * type: string
  132. * responses:
  133. * 200:
  134. * description: userGroups are fetched
  135. * content:
  136. * application/json:
  137. * schema:
  138. * properties:
  139. * userGroups:
  140. * type: array
  141. * items:
  142. * type: object
  143. * description: userGroup objects
  144. */
  145. router.get('/ancestors', loginRequiredStrictly, adminRequired, validator.ancestorGroup, async(req, res) => {
  146. const { groupId } = req.query;
  147. try {
  148. const userGroup = await UserGroup.findById(groupId);
  149. const ancestorUserGroups = await UserGroup.findGroupsWithAncestorsRecursively(userGroup, []);
  150. return res.apiv3({ ancestorUserGroups });
  151. }
  152. catch (err) {
  153. const msg = 'Error occurred while searching user groups';
  154. logger.error(msg, err);
  155. return res.apiv3Err(new ErrorV3(msg, 'user-groups-search-failed'));
  156. }
  157. });
  158. // TODO 85062: improve sort
  159. router.get('/children', loginRequiredStrictly, adminRequired, validator.listChildren, async(req, res) => {
  160. try {
  161. const { parentIds, includeGrandChildren = false } = req.query;
  162. const userGroupsResult = await UserGroup.findChildUserGroupsByParentIds(parentIds, includeGrandChildren);
  163. return res.apiv3({
  164. childUserGroups: userGroupsResult.childUserGroups,
  165. grandChildUserGroups: userGroupsResult.grandChildUserGroups,
  166. });
  167. }
  168. catch (err) {
  169. const msg = 'Error occurred in fetching child user group list';
  170. logger.error(msg, err);
  171. return res.apiv3Err(new ErrorV3(msg, 'child-user-group-list-fetch-failed'));
  172. }
  173. });
  174. /**
  175. * @swagger
  176. *
  177. * paths:
  178. * /user-groups:
  179. * post:
  180. * tags: [UserGroup]
  181. * operationId: createUserGroup
  182. * summary: /user-groups
  183. * description: Adds userGroup
  184. * requestBody:
  185. * required: true
  186. * content:
  187. * application/json:
  188. * schema:
  189. * properties:
  190. * name:
  191. * type: string
  192. * description: name of the userGroup trying to be added
  193. * responses:
  194. * 200:
  195. * description: userGroup is added
  196. * content:
  197. * application/json:
  198. * schema:
  199. * properties:
  200. * userGroup:
  201. * type: object
  202. * description: A result of `UserGroup.createGroupByName`
  203. */
  204. router.post('/', loginRequiredStrictly, adminRequired, csrf, validator.create, apiV3FormValidator, async(req, res) => {
  205. const { name, description = '', parentId } = req.body;
  206. try {
  207. const userGroupName = crowi.xss.process(name);
  208. const userGroupDescription = crowi.xss.process(description);
  209. const userGroup = await UserGroup.createGroup(userGroupName, userGroupDescription, parentId);
  210. return res.apiv3({ userGroup }, 201);
  211. }
  212. catch (err) {
  213. const msg = 'Error occurred in creating a user group';
  214. logger.error(msg, err);
  215. return res.apiv3Err(new ErrorV3(msg, 'user-group-create-failed'));
  216. }
  217. });
  218. /**
  219. * @swagger
  220. *
  221. * paths:
  222. * /selectable-groups:
  223. * get:
  224. * tags: [UserGroup]
  225. * operationId: getSelectableGroups
  226. * summary: /selectable-groups
  227. * description: Get selectable user groups.
  228. * parameters:
  229. * - name: groupId
  230. * in: query
  231. * required: true
  232. * description: id of userGroup
  233. * schema:
  234. * type: string
  235. * responses:
  236. * 200:
  237. * description: userGroups are fetched
  238. * content:
  239. * application/json:
  240. * schema:
  241. * properties:
  242. * userGroups:
  243. * type: array
  244. * items:
  245. * type: object
  246. * description: userGroup objects
  247. */
  248. router.get('/selectable-groups', loginRequiredStrictly, adminRequired, validator.selectableGroups, async(req, res) => {
  249. const { groupId } = req.query;
  250. try {
  251. const userGroup = await UserGroup.findById(groupId);
  252. const [ancestorGroups, descendantGroups] = await Promise.all([
  253. UserGroup.findGroupsWithAncestorsRecursively(userGroup, []),
  254. UserGroup.findGroupsWithDescendantsRecursively([userGroup], []),
  255. ]);
  256. const excludeUserGroupIds = [userGroup, ...ancestorGroups, ...descendantGroups].map(userGroups => userGroups._id.toString());
  257. const selectableUserGroups = await UserGroup.find({ _id: { $nin: excludeUserGroupIds } });
  258. return res.apiv3({ selectableUserGroups });
  259. }
  260. catch (err) {
  261. const msg = 'Error occurred while searching user groups';
  262. logger.error(msg, err);
  263. return res.apiv3Err(new ErrorV3(msg, 'user-groups-search-failed'));
  264. }
  265. });
  266. /**
  267. * @swagger
  268. *
  269. * paths:
  270. * /user-groups/{id}:
  271. * delete:
  272. * tags: [UserGroup]
  273. * operationId: deleteUserGroup
  274. * summary: /user-groups/{id}
  275. * description: Deletes userGroup
  276. * parameters:
  277. * - name: id
  278. * in: path
  279. * required: true
  280. * description: id of userGroup
  281. * schema:
  282. * type: string
  283. * - name: actionName
  284. * in: query
  285. * description: name of action
  286. * schema:
  287. * type: string
  288. * - name: transferToUserGroupId
  289. * in: query
  290. * description: userGroup id that will be transferred to
  291. * schema:
  292. * type: string
  293. * responses:
  294. * 200:
  295. * description: userGroup is removed
  296. * content:
  297. * application/json:
  298. * schema:
  299. * properties:
  300. * userGroups:
  301. * type: object
  302. * description: A result of `UserGroup.removeCompletelyById`
  303. */
  304. router.delete('/:id', loginRequiredStrictly, adminRequired, csrf, validator.delete, apiV3FormValidator, async(req, res) => {
  305. const { id: deleteGroupId } = req.params;
  306. const { actionName, transferToUserGroupId } = req.query;
  307. try {
  308. const userGroups = await crowi.userGroupService.removeCompletelyByRootGroupId(deleteGroupId, actionName, transferToUserGroupId, req.user);
  309. return res.apiv3({ userGroups });
  310. }
  311. catch (err) {
  312. const msg = 'Error occurred while deleting user groups';
  313. logger.error(msg, err);
  314. return res.apiv3Err(new ErrorV3(msg, 'user-groups-delete-failed'));
  315. }
  316. });
  317. /**
  318. * @swagger
  319. *
  320. * paths:
  321. * /user-groups/{id}:
  322. * put:
  323. * tags: [UserGroup]
  324. * operationId: updateUserGroups
  325. * summary: /user-groups/{id}
  326. * description: Update userGroup
  327. * parameters:
  328. * - name: id
  329. * in: path
  330. * required: true
  331. * description: id of userGroup
  332. * schema:
  333. * type: string
  334. * responses:
  335. * 200:
  336. * description: userGroup is updated
  337. * content:
  338. * application/json:
  339. * schema:
  340. * properties:
  341. * userGroup:
  342. * type: object
  343. * description: A result of `UserGroup.updateName`
  344. */
  345. router.put('/:id', loginRequiredStrictly, adminRequired, csrf, validator.update, apiV3FormValidator, async(req, res) => {
  346. const { id } = req.params;
  347. const {
  348. name, description, parentId, forceUpdateParents = false,
  349. } = req.body;
  350. try {
  351. const userGroup = await crowi.userGroupService.updateGroup(id, name, description, parentId, forceUpdateParents);
  352. return res.apiv3({ userGroup });
  353. }
  354. catch (err) {
  355. const msg = 'Error occurred in updating a user group name';
  356. logger.error(msg, err);
  357. return res.apiv3Err(new ErrorV3(msg, 'user-group-update-failed'));
  358. }
  359. });
  360. /**
  361. * @swagger
  362. *
  363. * paths:
  364. * /user-groups/{id}/users:
  365. * get:
  366. * tags: [UserGroup]
  367. * operationId: getUsersUserGroups
  368. * summary: /user-groups/{id}/users
  369. * description: Get users related to the userGroup
  370. * parameters:
  371. * - name: id
  372. * in: path
  373. * required: true
  374. * description: id of userGroup
  375. * schema:
  376. * type: string
  377. * responses:
  378. * 200:
  379. * description: users are fetched
  380. * content:
  381. * application/json:
  382. * schema:
  383. * properties:
  384. * users:
  385. * type: array
  386. * items:
  387. * type: object
  388. * description: user objects
  389. */
  390. router.get('/:id/users', loginRequiredStrictly, adminRequired, async(req, res) => {
  391. const { id } = req.params;
  392. try {
  393. const userGroup = await UserGroup.findById(id);
  394. const userGroupRelations = await UserGroupRelation.findAllRelationForUserGroup(userGroup);
  395. const serializeUsers = userGroupRelations.map((userGroupRelation) => {
  396. return serializeUserSecurely(userGroupRelation.relatedUser);
  397. });
  398. const users = serializeUsers.filter(user => user != null);
  399. return res.apiv3({ users });
  400. }
  401. catch (err) {
  402. const msg = `Error occurred in fetching users for group: ${id}`;
  403. logger.error(msg, err);
  404. return res.apiv3Err(new ErrorV3(msg, 'user-group-user-list-fetch-failed'));
  405. }
  406. });
  407. /**
  408. * @swagger
  409. *
  410. * paths:
  411. * /user-groups/{id}/unrelated-users:
  412. * get:
  413. * tags: [UserGroup]
  414. * operationId: getUnrelatedUsersUserGroups
  415. * summary: /user-groups/{id}/unrelated-users
  416. * description: Get users unrelated to the userGroup
  417. * parameters:
  418. * - name: id
  419. * in: path
  420. * required: true
  421. * description: id of userGroup
  422. * schema:
  423. * type: string
  424. * responses:
  425. * 200:
  426. * description: users are fetched
  427. * content:
  428. * application/json:
  429. * schema:
  430. * properties:
  431. * users:
  432. * type: array
  433. * items:
  434. * type: object
  435. * description: user objects
  436. */
  437. router.get('/:id/unrelated-users', loginRequiredStrictly, adminRequired, async(req, res) => {
  438. const { id } = req.params;
  439. const {
  440. searchWord, searchType, isAlsoNameSearched, isAlsoMailSearched,
  441. } = req.query;
  442. const queryOptions = {
  443. searchWord, searchType, isAlsoNameSearched, isAlsoMailSearched,
  444. };
  445. try {
  446. const userGroup = await UserGroup.findById(id);
  447. const users = await UserGroupRelation.findUserByNotRelatedGroup(userGroup, queryOptions);
  448. // return email only this api
  449. const serializedUsers = users.map((user) => {
  450. const { email } = user;
  451. const serializedUser = serializeUserSecurely(user);
  452. serializedUser.email = email;
  453. return serializedUser;
  454. });
  455. return res.apiv3({ users: serializedUsers });
  456. }
  457. catch (err) {
  458. const msg = `Error occurred in fetching unrelated users for group: ${id}`;
  459. logger.error(msg, err);
  460. return res.apiv3Err(new ErrorV3(msg, 'user-group-unrelated-user-list-fetch-failed'));
  461. }
  462. });
  463. /**
  464. * @swagger
  465. *
  466. * paths:
  467. * /user-groups/{id}/users:
  468. * post:
  469. * tags: [UserGroup]
  470. * operationId: addUserUserGroups
  471. * summary: /user-groups/{id}/users
  472. * description: Add a user to the userGroup
  473. * parameters:
  474. * - name: id
  475. * in: path
  476. * required: true
  477. * description: id of userGroup
  478. * schema:
  479. * type: string
  480. * responses:
  481. * 200:
  482. * description: a user is added
  483. * content:
  484. * application/json:
  485. * schema:
  486. * type: object
  487. * properties:
  488. * user:
  489. * type: object
  490. * description: the user added to the group
  491. * userGroup:
  492. * type: object
  493. * description: the group to which a user was added
  494. * userGroupRelation:
  495. * type: object
  496. * description: the associative entity between user and userGroup
  497. */
  498. router.post('/:id/users/:username', loginRequiredStrictly, adminRequired, validator.users.post, apiV3FormValidator, async(req, res) => {
  499. const { id, username } = req.params;
  500. try {
  501. const [userGroup, user] = await Promise.all([
  502. UserGroup.findById(id),
  503. User.findUserByUsername(username),
  504. ]);
  505. const userGroups = await UserGroup.findGroupsWithAncestorsRecursively(userGroup);
  506. const userGroupIds = userGroups.map(g => g._id);
  507. // check for duplicate users in groups
  508. const existingRelations = await UserGroupRelation.find({ relatedGroup: { $in: userGroupIds }, relatedUser: user._id });
  509. const existingGroupIds = existingRelations.map(r => r.relatedGroup);
  510. const groupIdsOfRelationToCreate = excludeTestIdsFromTargetIds(userGroupIds, existingGroupIds);
  511. const insertedRelations = await UserGroupRelation.createRelations(groupIdsOfRelationToCreate, user);
  512. const serializedUser = serializeUserSecurely(user);
  513. return res.apiv3({ user: serializedUser, createdRelationCount: insertedRelations.length });
  514. }
  515. catch (err) {
  516. const msg = `Error occurred in adding the user "${username}" to group "${id}"`;
  517. logger.error(msg, err);
  518. return res.apiv3Err(new ErrorV3(msg, 'user-group-add-user-failed'));
  519. }
  520. });
  521. /**
  522. * @swagger
  523. *
  524. * paths:
  525. * /user-groups/{id}/users:
  526. * delete:
  527. * tags: [UserGroup]
  528. * operationId: deleteUsersUserGroups
  529. * summary: /user-groups/{id}/users
  530. * description: remove a user from the userGroup
  531. * parameters:
  532. * - name: id
  533. * in: path
  534. * required: true
  535. * description: id of userGroup
  536. * schema:
  537. * type: string
  538. * responses:
  539. * 200:
  540. * description: a user was removed
  541. * content:
  542. * application/json:
  543. * schema:
  544. * type: object
  545. * properties:
  546. * user:
  547. * type: object
  548. * description: the user removed from the group
  549. * userGroup:
  550. * type: object
  551. * description: the group from which a user was removed
  552. * userGroupRelation:
  553. * type: object
  554. * description: the associative entity between user and userGroup
  555. */
  556. router.delete('/:id/users/:username', loginRequiredStrictly, adminRequired, validator.users.delete, apiV3FormValidator, async(req, res) => {
  557. const { id, username } = req.params;
  558. try {
  559. const [userGroup, user] = await Promise.all([
  560. UserGroup.findById(id),
  561. User.findUserByUsername(username),
  562. ]);
  563. const groupsOfRelationsToDelete = await UserGroup.findGroupsWithDescendantsRecursively([userGroup]);
  564. const relatedGroupIdsToDelete = groupsOfRelationsToDelete.map(g => g._id);
  565. const deleteManyRes = await UserGroupRelation.deleteMany({ relatedUser: user._id, relatedGroup: { $in: relatedGroupIdsToDelete } });
  566. const serializedUser = serializeUserSecurely(user);
  567. return res.apiv3({ user: serializedUser, deletedGroupsCount: deleteManyRes.deletedCount });
  568. }
  569. catch (err) {
  570. const msg = 'Error occurred while removing the user from groups.';
  571. logger.error(msg, err);
  572. return res.apiv3Err(new ErrorV3(msg, 'user-group-remove-user-failed'));
  573. }
  574. });
  575. /**
  576. * @swagger
  577. *
  578. * paths:
  579. * /user-groups/{id}/user-group-relations:
  580. * get:
  581. * tags: [UserGroup]
  582. * operationId: getUserGroupRelationsUserGroups
  583. * summary: /user-groups/{id}/user-group-relations
  584. * description: Get the user group relations for the userGroup
  585. * parameters:
  586. * - name: id
  587. * in: path
  588. * required: true
  589. * description: id of userGroup
  590. * schema:
  591. * type: string
  592. * responses:
  593. * 200:
  594. * description: user group relations are fetched
  595. * content:
  596. * application/json:
  597. * schema:
  598. * properties:
  599. * userGroupRelations:
  600. * type: array
  601. * items:
  602. * type: object
  603. * description: userGroupRelation objects
  604. */
  605. router.get('/:id/user-group-relations', loginRequiredStrictly, adminRequired, async(req, res) => {
  606. const { id } = req.params;
  607. try {
  608. const userGroup = await UserGroup.findById(id);
  609. const userGroupRelations = await UserGroupRelation.findAllRelationForUserGroup(userGroup);
  610. return res.apiv3({ userGroupRelations });
  611. }
  612. catch (err) {
  613. const msg = `Error occurred in fetching user group relations for group: ${id}`;
  614. logger.error(msg, err);
  615. return res.apiv3Err(new ErrorV3(msg, 'user-group-user-group-relation-list-fetch-failed'));
  616. }
  617. });
  618. /**
  619. * @swagger
  620. *
  621. * paths:
  622. * /user-groups/{id}/pages:
  623. * get:
  624. * tags: [UserGroup]
  625. * operationId: getPagesUserGroups
  626. * summary: /user-groups/{id}/pages
  627. * description: Get closed pages for the userGroup
  628. * parameters:
  629. * - name: id
  630. * in: path
  631. * required: true
  632. * description: id of userGroup
  633. * schema:
  634. * type: string
  635. * responses:
  636. * 200:
  637. * description: pages are fetched
  638. * content:
  639. * application/json:
  640. * schema:
  641. * properties:
  642. * pages:
  643. * type: array
  644. * items:
  645. * type: object
  646. * description: page objects
  647. */
  648. router.get('/:id/pages', loginRequiredStrictly, adminRequired, validator.pages.get, apiV3FormValidator, async(req, res) => {
  649. const { id } = req.params;
  650. const { limit, offset } = req.query;
  651. try {
  652. const { docs, totalDocs } = await Page.paginate({
  653. grant: Page.GRANT_USER_GROUP,
  654. grantedGroup: { $in: [id] },
  655. }, {
  656. offset,
  657. limit,
  658. populate: 'lastUpdateUser',
  659. });
  660. const current = offset / limit + 1;
  661. const pages = docs.map((doc) => {
  662. doc.lastUpdateUser = serializeUserSecurely(doc.lastUpdateUser);
  663. return doc;
  664. });
  665. // TODO: create a common moudule for paginated response
  666. return res.apiv3({ total: totalDocs, current, pages });
  667. }
  668. catch (err) {
  669. const msg = `Error occurred in fetching pages for group: ${id}`;
  670. logger.error(msg, err);
  671. return res.apiv3Err(new ErrorV3(msg, 'user-group-page-list-fetch-failed'));
  672. }
  673. });
  674. return router;
  675. };