user-group.js 22 KB

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