user-group.ts 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. import mongoose from 'mongoose';
  2. import loggerFactory from '~/utils/logger';
  3. import UserGroup, { UserGroupDocument } from '~/server/models/user-group';
  4. import { excludeTestIdsFromTargetIds, isIncludesObjectId } from '~/server/util/compare-objectId';
  5. const logger = loggerFactory('growi:service:UserGroupService'); // eslint-disable-line no-unused-vars
  6. const UserGroupRelation = mongoose.model('UserGroupRelation') as any; // TODO: Typescriptize model
  7. /**
  8. * the service class of UserGroupService
  9. */
  10. class UserGroupService {
  11. crowi: any;
  12. constructor(crowi) {
  13. this.crowi = crowi;
  14. }
  15. async init() {
  16. logger.debug('removing all invalid relations');
  17. return UserGroupRelation.removeAllInvalidRelations();
  18. }
  19. // TODO 85062: write test code
  20. // ref: https://dev.growi.org/61b2cdabaa330ce7d8152844
  21. async updateGroup(id, name: string, description: string, parentId?: string, forceUpdateParents = false) {
  22. const userGroup = await UserGroup.findById(id);
  23. if (userGroup == null) {
  24. throw new Error('The group does not exist');
  25. }
  26. // check if the new group name is available
  27. const isExist = (await UserGroup.countDocuments({ name })) > 0;
  28. if (userGroup.name !== name && isExist) {
  29. throw new Error('The group name is already taken');
  30. }
  31. userGroup.name = name;
  32. userGroup.description = description;
  33. // return when not update parent
  34. if (userGroup.parent === parentId) {
  35. return userGroup.save();
  36. }
  37. // set parent to null and return when parentId is null
  38. if (parentId == null) {
  39. userGroup.parent = null;
  40. return userGroup.save();
  41. }
  42. const parent = await UserGroup.findById(parentId);
  43. if (parent == null) { // it should not be null
  44. throw Error('Parent group does not exist.');
  45. }
  46. /*
  47. * check if able to update parent or not
  48. */
  49. // throw if parent was in self and its descendants
  50. const descendantsWithTarget = await UserGroup.findGroupsWithDescendantsRecursively([userGroup]);
  51. if (isIncludesObjectId(descendantsWithTarget, parent._id)) {
  52. throw Error('It is not allowed to choose parent from descendant groups.');
  53. }
  54. // find users for comparison
  55. const [targetGroupUsers, parentGroupUsers] = await Promise.all(
  56. [UserGroupRelation.findUserIdsByGroupId(userGroup._id), UserGroupRelation.findUserIdsByGroupId(parent._id)],
  57. );
  58. const usersBelongsToTargetButNotParent = excludeTestIdsFromTargetIds(targetGroupUsers, parentGroupUsers);
  59. // save if no users exist in both target and parent groups
  60. if (targetGroupUsers.length === 0 && parentGroupUsers.length === 0) {
  61. userGroup.parent = parent._id;
  62. return userGroup.save();
  63. }
  64. // add the target group's users to all ancestors
  65. if (forceUpdateParents) {
  66. const ancestorGroups = await UserGroup.findGroupsWithAncestorsRecursively(parent);
  67. const ancestorGroupIds = ancestorGroups.map(group => group._id);
  68. await UserGroupRelation.createByGroupIdsAndUserIds(ancestorGroupIds, usersBelongsToTargetButNotParent);
  69. }
  70. // throw if any of users in the target group is NOT included in the parent group
  71. else {
  72. const isUpdatable = usersBelongsToTargetButNotParent.length === 0;
  73. if (!isUpdatable) {
  74. throw Error('The parent group does not contain the users in this group.');
  75. }
  76. }
  77. userGroup.parent = parent._id;
  78. return userGroup.save();
  79. }
  80. async removeCompletelyByRootGroupId(deleteRootGroupId, action, transferToUserGroupId, user) {
  81. const rootGroup = await UserGroup.findById(deleteRootGroupId);
  82. if (rootGroup == null) {
  83. throw new Error(`UserGroup data does not exist. id: ${deleteRootGroupId}`);
  84. }
  85. const groupsToDelete = await UserGroup.findGroupsWithDescendantsRecursively([rootGroup]);
  86. // 1. update page & remove all groups
  87. await this.crowi.pageService.handlePrivatePagesForGroupsToDelete(groupsToDelete, action, transferToUserGroupId, user);
  88. // 2. remove all groups
  89. const deletedGroups = await UserGroup.deleteMany({ _id: { $in: groupsToDelete.map(g => g._id) } });
  90. // 3. remove all relations
  91. await UserGroupRelation.removeAllByUserGroups(groupsToDelete);
  92. return deletedGroups;
  93. }
  94. }
  95. module.exports = UserGroupService;