user-group.js 20 KB

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