user-group.js 19 KB

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