user-group.js 21 KB

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