user-group.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import mongoose from 'mongoose';
  2. import loggerFactory from '~/utils/logger';
  3. import UserGroup from '~/server/models/user-group';
  4. const logger = loggerFactory('growi:service:UserGroupService'); // eslint-disable-line no-unused-vars
  5. const UserGroupRelation = mongoose.model('UserGroupRelation') as any; // TODO: Typescriptize model
  6. /**
  7. * the service class of UserGroupService
  8. */
  9. class UserGroupService {
  10. crowi: any;
  11. constructor(crowi) {
  12. this.crowi = crowi;
  13. }
  14. async init() {
  15. logger.debug('removing all invalid relations');
  16. return UserGroupRelation.removeAllInvalidRelations();
  17. }
  18. // TODO 85062: write test code
  19. // ref: https://dev.growi.org/61b2cdabaa330ce7d8152844
  20. async updateGroup(id, name, description, parentId, forceUpdateParents = false) {
  21. const userGroup = await UserGroup.findById(id);
  22. if (userGroup == null) {
  23. throw new Error('The group does not exist');
  24. }
  25. // check if the new group name is available
  26. const isExist = (await UserGroup.countDocuments({ name })) > 0;
  27. if (userGroup.name !== name && isExist) {
  28. throw new Error('The group name is already taken');
  29. }
  30. userGroup.name = name;
  31. userGroup.description = description;
  32. // return when not update parent
  33. if (userGroup.parent === parentId) {
  34. return userGroup.save();
  35. }
  36. const parent = await UserGroup.findById(parentId);
  37. // find users for comparison
  38. const [targetGroupUsers, parentGroupUsers] = await Promise.all(
  39. [UserGroupRelation.findUserIdsByGroupId(userGroup._id), UserGroupRelation.findUserIdsByGroupId(parent?._id)], // TODO 85062: consider when parent is null to update the group as the root
  40. );
  41. const usersBelongsToTargetButNotParent = targetGroupUsers.filter(user => !parentGroupUsers.includes(user));
  42. // add the target group's users to all ancestors
  43. if (forceUpdateParents) {
  44. const ancestorGroups = await UserGroup.findAllAncestorGroups(parent);
  45. const ancestorGroupIds = ancestorGroups.map(group => group._id);
  46. await UserGroupRelation.createByGroupIdsAndUserIds(ancestorGroupIds, usersBelongsToTargetButNotParent);
  47. userGroup.parent = parent?._id; // TODO 85062: consider when parent is null to update the group as the root
  48. }
  49. // validate related users
  50. else {
  51. const isUpdatable = usersBelongsToTargetButNotParent.length === 0;
  52. if (!isUpdatable) {
  53. throw Error('The parent group does not contain the users in this group.');
  54. }
  55. }
  56. return userGroup.save();
  57. }
  58. }
  59. module.exports = UserGroupService;