user-group.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  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-parent-groups:
  223. * get:
  224. * tags: [UserGroup]
  225. * operationId: getSelectableParentGroups
  226. * summary: /selectable-parent-groups
  227. * description: Get selectable parent UserGroups
  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-parent-groups', loginRequiredStrictly, adminRequired, validator.selectableGroups, async(req, res) => {
  249. const { groupId } = req.query;
  250. try {
  251. const userGroup = await UserGroup.findById(groupId);
  252. const descendantGroups = await UserGroup.findGroupsWithDescendantsRecursively([userGroup], []);
  253. const descendantGroupIds = descendantGroups.map(userGroups => userGroups._id.toString());
  254. const selectableParentGroups = await UserGroup.find({ _id: { $nin: [groupId, ...descendantGroupIds] } });
  255. return res.apiv3({ selectableParentGroups });
  256. }
  257. catch (err) {
  258. const msg = 'Error occurred while searching user groups';
  259. logger.error(msg, err);
  260. return res.apiv3Err(new ErrorV3(msg, 'user-groups-search-failed'));
  261. }
  262. });
  263. /**
  264. * @swagger
  265. *
  266. * paths:
  267. * /selectable-child-groups:
  268. * get:
  269. * tags: [UserGroup]
  270. * operationId: getSelectableChildGroups
  271. * summary: /selectable-child-groups
  272. * description: Get selectable child UserGroups
  273. * parameters:
  274. * - name: groupId
  275. * in: query
  276. * required: true
  277. * description: id of userGroup
  278. * schema:
  279. * type: string
  280. * responses:
  281. * 200:
  282. * description: userGroups are fetched
  283. * content:
  284. * application/json:
  285. * schema:
  286. * properties:
  287. * userGroups:
  288. * type: array
  289. * items:
  290. * type: object
  291. * description: userGroup objects
  292. */
  293. router.get('/selectable-child-groups', loginRequiredStrictly, adminRequired, validator.selectableGroups, async(req, res) => {
  294. const { groupId } = req.query;
  295. try {
  296. const userGroup = await UserGroup.findById(groupId);
  297. const [ancestorGroups, descendantGroups] = await Promise.all([
  298. UserGroup.findGroupsWithAncestorsRecursively(userGroup, []),
  299. UserGroup.findGroupsWithDescendantsRecursively([userGroup], []),
  300. ]);
  301. const excludeUserGroupIds = [userGroup, ...ancestorGroups, ...descendantGroups].map(userGroups => userGroups._id.toString());
  302. const selectableChildGroups = await UserGroup.find({ _id: { $nin: excludeUserGroupIds } });
  303. return res.apiv3({ selectableChildGroups });
  304. }
  305. catch (err) {
  306. const msg = 'Error occurred while searching user groups';
  307. logger.error(msg, err);
  308. return res.apiv3Err(new ErrorV3(msg, 'user-groups-search-failed'));
  309. }
  310. });
  311. /**
  312. * @swagger
  313. *
  314. * paths:
  315. * /user-groups/{id}:
  316. * get:
  317. * tags: [UserGroup]
  318. * operationId: getUserGroupFromGroupId
  319. * summary: /user-groups/{id}
  320. * description: Get UserGroup from Group ID
  321. * parameters:
  322. * - name: id
  323. * in: path
  324. * required: true
  325. * description: id of userGroup
  326. * schema:
  327. * type: string
  328. * responses:
  329. * 200:
  330. * description: userGroup are fetched
  331. * content:
  332. * application/json:
  333. * schema:
  334. * properties:
  335. * userGroup:
  336. * type: object
  337. * description: userGroup object
  338. */
  339. router.get('/:id', loginRequiredStrictly, adminRequired, validator.selectableGroups, async(req, res) => {
  340. const { id: groupId } = req.params;
  341. try {
  342. const userGroup = await UserGroup.findById(groupId);
  343. return res.apiv3({ userGroup });
  344. }
  345. catch (err) {
  346. const msg = 'Error occurred while getting user group';
  347. logger.error(msg, err);
  348. return res.apiv3Err(new ErrorV3(msg, 'user-groups-get-failed'));
  349. }
  350. });
  351. /**
  352. * @swagger
  353. *
  354. * paths:
  355. * /user-groups/{id}:
  356. * delete:
  357. * tags: [UserGroup]
  358. * operationId: deleteUserGroup
  359. * summary: /user-groups/{id}
  360. * description: Deletes userGroup
  361. * parameters:
  362. * - name: id
  363. * in: path
  364. * required: true
  365. * description: id of userGroup
  366. * schema:
  367. * type: string
  368. * - name: actionName
  369. * in: query
  370. * description: name of action
  371. * schema:
  372. * type: string
  373. * - name: transferToUserGroupId
  374. * in: query
  375. * description: userGroup id that will be transferred to
  376. * schema:
  377. * type: string
  378. * responses:
  379. * 200:
  380. * description: userGroup is removed
  381. * content:
  382. * application/json:
  383. * schema:
  384. * properties:
  385. * userGroups:
  386. * type: object
  387. * description: A result of `UserGroup.removeCompletelyById`
  388. */
  389. router.delete('/:id', loginRequiredStrictly, adminRequired, csrf, validator.delete, apiV3FormValidator, async(req, res) => {
  390. const { id: deleteGroupId } = req.params;
  391. const { actionName, transferToUserGroupId } = req.query;
  392. try {
  393. const userGroups = await crowi.userGroupService.removeCompletelyByRootGroupId(deleteGroupId, actionName, transferToUserGroupId, req.user);
  394. return res.apiv3({ userGroups });
  395. }
  396. catch (err) {
  397. const msg = 'Error occurred while deleting user groups';
  398. logger.error(msg, err);
  399. return res.apiv3Err(new ErrorV3(msg, 'user-groups-delete-failed'));
  400. }
  401. });
  402. /**
  403. * @swagger
  404. *
  405. * paths:
  406. * /user-groups/{id}:
  407. * put:
  408. * tags: [UserGroup]
  409. * operationId: updateUserGroups
  410. * summary: /user-groups/{id}
  411. * description: Update userGroup
  412. * parameters:
  413. * - name: id
  414. * in: path
  415. * required: true
  416. * description: id of userGroup
  417. * schema:
  418. * type: string
  419. * responses:
  420. * 200:
  421. * description: userGroup is updated
  422. * content:
  423. * application/json:
  424. * schema:
  425. * properties:
  426. * userGroup:
  427. * type: object
  428. * description: A result of `UserGroup.updateName`
  429. */
  430. router.put('/:id', loginRequiredStrictly, adminRequired, csrf, validator.update, apiV3FormValidator, async(req, res) => {
  431. const { id } = req.params;
  432. const {
  433. name, description, parentId, forceUpdateParents = false,
  434. } = req.body;
  435. try {
  436. const userGroup = await crowi.userGroupService.updateGroup(id, name, description, parentId, forceUpdateParents);
  437. return res.apiv3({ userGroup });
  438. }
  439. catch (err) {
  440. const msg = 'Error occurred in updating a user group name';
  441. logger.error(msg, err);
  442. return res.apiv3Err(new ErrorV3(msg, 'user-group-update-failed'));
  443. }
  444. });
  445. /**
  446. * @swagger
  447. *
  448. * paths:
  449. * /user-groups/{id}/users:
  450. * get:
  451. * tags: [UserGroup]
  452. * operationId: getUsersUserGroups
  453. * summary: /user-groups/{id}/users
  454. * description: Get users related to the userGroup
  455. * parameters:
  456. * - name: id
  457. * in: path
  458. * required: true
  459. * description: id of userGroup
  460. * schema:
  461. * type: string
  462. * responses:
  463. * 200:
  464. * description: users are fetched
  465. * content:
  466. * application/json:
  467. * schema:
  468. * properties:
  469. * users:
  470. * type: array
  471. * items:
  472. * type: object
  473. * description: user objects
  474. */
  475. router.get('/:id/users', loginRequiredStrictly, adminRequired, async(req, res) => {
  476. const { id } = req.params;
  477. try {
  478. const userGroup = await UserGroup.findById(id);
  479. const userGroupRelations = await UserGroupRelation.findAllRelationForUserGroup(userGroup);
  480. const serializeUsers = userGroupRelations.map((userGroupRelation) => {
  481. return serializeUserSecurely(userGroupRelation.relatedUser);
  482. });
  483. const users = serializeUsers.filter(user => user != null);
  484. return res.apiv3({ users });
  485. }
  486. catch (err) {
  487. const msg = `Error occurred in fetching users for group: ${id}`;
  488. logger.error(msg, err);
  489. return res.apiv3Err(new ErrorV3(msg, 'user-group-user-list-fetch-failed'));
  490. }
  491. });
  492. /**
  493. * @swagger
  494. *
  495. * paths:
  496. * /user-groups/{id}/unrelated-users:
  497. * get:
  498. * tags: [UserGroup]
  499. * operationId: getUnrelatedUsersUserGroups
  500. * summary: /user-groups/{id}/unrelated-users
  501. * description: Get users unrelated to the userGroup
  502. * parameters:
  503. * - name: id
  504. * in: path
  505. * required: true
  506. * description: id of userGroup
  507. * schema:
  508. * type: string
  509. * responses:
  510. * 200:
  511. * description: users are fetched
  512. * content:
  513. * application/json:
  514. * schema:
  515. * properties:
  516. * users:
  517. * type: array
  518. * items:
  519. * type: object
  520. * description: user objects
  521. */
  522. router.get('/:id/unrelated-users', loginRequiredStrictly, adminRequired, async(req, res) => {
  523. const { id } = req.params;
  524. const {
  525. searchWord, searchType, isAlsoNameSearched, isAlsoMailSearched,
  526. } = req.query;
  527. const queryOptions = {
  528. searchWord, searchType, isAlsoNameSearched, isAlsoMailSearched,
  529. };
  530. try {
  531. const userGroup = await UserGroup.findById(id);
  532. const users = await UserGroupRelation.findUserByNotRelatedGroup(userGroup, queryOptions);
  533. // return email only this api
  534. const serializedUsers = users.map((user) => {
  535. const { email } = user;
  536. const serializedUser = serializeUserSecurely(user);
  537. serializedUser.email = email;
  538. return serializedUser;
  539. });
  540. return res.apiv3({ users: serializedUsers });
  541. }
  542. catch (err) {
  543. const msg = `Error occurred in fetching unrelated users for group: ${id}`;
  544. logger.error(msg, err);
  545. return res.apiv3Err(new ErrorV3(msg, 'user-group-unrelated-user-list-fetch-failed'));
  546. }
  547. });
  548. /**
  549. * @swagger
  550. *
  551. * paths:
  552. * /user-groups/{id}/users:
  553. * post:
  554. * tags: [UserGroup]
  555. * operationId: addUserUserGroups
  556. * summary: /user-groups/{id}/users
  557. * description: Add a user to the userGroup
  558. * parameters:
  559. * - name: id
  560. * in: path
  561. * required: true
  562. * description: id of userGroup
  563. * schema:
  564. * type: string
  565. * responses:
  566. * 200:
  567. * description: a user is added
  568. * content:
  569. * application/json:
  570. * schema:
  571. * type: object
  572. * properties:
  573. * user:
  574. * type: object
  575. * description: the user added to the group
  576. * userGroup:
  577. * type: object
  578. * description: the group to which a user was added
  579. * userGroupRelation:
  580. * type: object
  581. * description: the associative entity between user and userGroup
  582. */
  583. router.post('/:id/users/:username', loginRequiredStrictly, adminRequired, validator.users.post, apiV3FormValidator, async(req, res) => {
  584. const { id, username } = req.params;
  585. try {
  586. const [userGroup, user] = await Promise.all([
  587. UserGroup.findById(id),
  588. User.findUserByUsername(username),
  589. ]);
  590. const userGroups = await UserGroup.findGroupsWithAncestorsRecursively(userGroup);
  591. const userGroupIds = userGroups.map(g => g._id);
  592. // check for duplicate users in groups
  593. const existingRelations = await UserGroupRelation.find({ relatedGroup: { $in: userGroupIds }, relatedUser: user._id });
  594. const existingGroupIds = existingRelations.map(r => r.relatedGroup);
  595. const groupIdsOfRelationToCreate = excludeTestIdsFromTargetIds(userGroupIds, existingGroupIds);
  596. const insertedRelations = await UserGroupRelation.createRelations(groupIdsOfRelationToCreate, user);
  597. const serializedUser = serializeUserSecurely(user);
  598. return res.apiv3({ user: serializedUser, createdRelationCount: insertedRelations.length });
  599. }
  600. catch (err) {
  601. const msg = `Error occurred in adding the user "${username}" to group "${id}"`;
  602. logger.error(msg, err);
  603. return res.apiv3Err(new ErrorV3(msg, 'user-group-add-user-failed'));
  604. }
  605. });
  606. /**
  607. * @swagger
  608. *
  609. * paths:
  610. * /user-groups/{id}/users:
  611. * delete:
  612. * tags: [UserGroup]
  613. * operationId: deleteUsersUserGroups
  614. * summary: /user-groups/{id}/users
  615. * description: remove a user from the userGroup
  616. * parameters:
  617. * - name: id
  618. * in: path
  619. * required: true
  620. * description: id of userGroup
  621. * schema:
  622. * type: string
  623. * responses:
  624. * 200:
  625. * description: a user was removed
  626. * content:
  627. * application/json:
  628. * schema:
  629. * type: object
  630. * properties:
  631. * user:
  632. * type: object
  633. * description: the user removed from the group
  634. * userGroup:
  635. * type: object
  636. * description: the group from which a user was removed
  637. * userGroupRelation:
  638. * type: object
  639. * description: the associative entity between user and userGroup
  640. */
  641. router.delete('/:id/users/:username', loginRequiredStrictly, adminRequired, validator.users.delete, apiV3FormValidator, async(req, res) => {
  642. const { id, username } = req.params;
  643. try {
  644. const [userGroup, user] = await Promise.all([
  645. UserGroup.findById(id),
  646. User.findUserByUsername(username),
  647. ]);
  648. const groupsOfRelationsToDelete = await UserGroup.findGroupsWithDescendantsRecursively([userGroup]);
  649. const relatedGroupIdsToDelete = groupsOfRelationsToDelete.map(g => g._id);
  650. const deleteManyRes = await UserGroupRelation.deleteMany({ relatedUser: user._id, relatedGroup: { $in: relatedGroupIdsToDelete } });
  651. const serializedUser = serializeUserSecurely(user);
  652. return res.apiv3({ user: serializedUser, deletedGroupsCount: deleteManyRes.deletedCount });
  653. }
  654. catch (err) {
  655. const msg = 'Error occurred while removing the user from groups.';
  656. logger.error(msg, err);
  657. return res.apiv3Err(new ErrorV3(msg, 'user-group-remove-user-failed'));
  658. }
  659. });
  660. /**
  661. * @swagger
  662. *
  663. * paths:
  664. * /user-groups/{id}/user-group-relations:
  665. * get:
  666. * tags: [UserGroup]
  667. * operationId: getUserGroupRelationsUserGroups
  668. * summary: /user-groups/{id}/user-group-relations
  669. * description: Get the user group relations for the userGroup
  670. * parameters:
  671. * - name: id
  672. * in: path
  673. * required: true
  674. * description: id of userGroup
  675. * schema:
  676. * type: string
  677. * responses:
  678. * 200:
  679. * description: user group relations are fetched
  680. * content:
  681. * application/json:
  682. * schema:
  683. * properties:
  684. * userGroupRelations:
  685. * type: array
  686. * items:
  687. * type: object
  688. * description: userGroupRelation objects
  689. */
  690. router.get('/:id/user-group-relations', loginRequiredStrictly, adminRequired, async(req, res) => {
  691. const { id } = req.params;
  692. try {
  693. const userGroup = await UserGroup.findById(id);
  694. const userGroupRelations = await UserGroupRelation.findAllRelationForUserGroup(userGroup);
  695. return res.apiv3({ userGroupRelations });
  696. }
  697. catch (err) {
  698. const msg = `Error occurred in fetching user group relations for group: ${id}`;
  699. logger.error(msg, err);
  700. return res.apiv3Err(new ErrorV3(msg, 'user-group-user-group-relation-list-fetch-failed'));
  701. }
  702. });
  703. /**
  704. * @swagger
  705. *
  706. * paths:
  707. * /user-groups/{id}/pages:
  708. * get:
  709. * tags: [UserGroup]
  710. * operationId: getPagesUserGroups
  711. * summary: /user-groups/{id}/pages
  712. * description: Get closed pages for the userGroup
  713. * parameters:
  714. * - name: id
  715. * in: path
  716. * required: true
  717. * description: id of userGroup
  718. * schema:
  719. * type: string
  720. * responses:
  721. * 200:
  722. * description: pages are fetched
  723. * content:
  724. * application/json:
  725. * schema:
  726. * properties:
  727. * pages:
  728. * type: array
  729. * items:
  730. * type: object
  731. * description: page objects
  732. */
  733. router.get('/:id/pages', loginRequiredStrictly, adminRequired, validator.pages.get, apiV3FormValidator, async(req, res) => {
  734. const { id } = req.params;
  735. const { limit, offset } = req.query;
  736. try {
  737. const { docs, totalDocs } = await Page.paginate({
  738. grant: Page.GRANT_USER_GROUP,
  739. grantedGroup: { $in: [id] },
  740. }, {
  741. offset,
  742. limit,
  743. populate: 'lastUpdateUser',
  744. });
  745. const current = offset / limit + 1;
  746. const pages = docs.map((doc) => {
  747. doc.lastUpdateUser = serializeUserSecurely(doc.lastUpdateUser);
  748. return doc;
  749. });
  750. // TODO: create a common moudule for paginated response
  751. return res.apiv3({ total: totalDocs, current, pages });
  752. }
  753. catch (err) {
  754. const msg = `Error occurred in fetching pages for group: ${id}`;
  755. logger.error(msg, err);
  756. return res.apiv3Err(new ErrorV3(msg, 'user-group-page-list-fetch-failed'));
  757. }
  758. });
  759. return router;
  760. };