user-group-relation.js 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. const debug = require('debug')('growi:models:userGroupRelation');
  2. const mongoose = require('mongoose');
  3. const mongoosePaginate = require('mongoose-paginate-v2');
  4. const uniqueValidator = require('mongoose-unique-validator');
  5. const ObjectId = mongoose.Schema.Types.ObjectId;
  6. /*
  7. * define schema
  8. */
  9. const schema = new mongoose.Schema({
  10. relatedGroup: { type: ObjectId, ref: 'UserGroup', required: true },
  11. relatedUser: { type: ObjectId, ref: 'User', required: true },
  12. }, {
  13. timestamps: { createdAt: true, updatedAt: false },
  14. });
  15. schema.plugin(mongoosePaginate);
  16. schema.plugin(uniqueValidator);
  17. /**
  18. * UserGroupRelation Class
  19. *
  20. * @class UserGroupRelation
  21. */
  22. class UserGroupRelation {
  23. /**
  24. * limit items num for pagination
  25. *
  26. * @readonly
  27. * @static
  28. * @memberof UserGroupRelation
  29. */
  30. static get PAGE_ITEMS() {
  31. return 50;
  32. }
  33. static set crowi(crowi) {
  34. this._crowi = crowi;
  35. }
  36. static get crowi() {
  37. return this._crowi;
  38. }
  39. /**
  40. * remove all invalid relations that has reference to unlinked document
  41. */
  42. static removeAllInvalidRelations() {
  43. return this.findAllRelation()
  44. .then((relations) => {
  45. // filter invalid documents
  46. return relations.filter((relation) => {
  47. return relation.relatedUser == null || relation.relatedGroup == null;
  48. });
  49. })
  50. .then((invalidRelations) => {
  51. const ids = invalidRelations.map((relation) => { return relation._id });
  52. return this.deleteMany({ _id: { $in: ids } });
  53. });
  54. }
  55. /**
  56. * find all user and group relation
  57. *
  58. * @static
  59. * @returns {Promise<UserGroupRelation[]>}
  60. * @memberof UserGroupRelation
  61. */
  62. static findAllRelation() {
  63. return this
  64. .find()
  65. .populate('relatedUser')
  66. .populate('relatedGroup')
  67. .exec();
  68. }
  69. /**
  70. * find all user and group relation of UserGroup
  71. *
  72. * @static
  73. * @param {UserGroup} userGroup
  74. * @returns {Promise<UserGroupRelation[]>}
  75. * @memberof UserGroupRelation
  76. */
  77. static findAllRelationForUserGroup(userGroup) {
  78. debug('findAllRelationForUserGroup is called', userGroup);
  79. return this
  80. .find({ relatedGroup: userGroup })
  81. .populate('relatedUser')
  82. .exec();
  83. }
  84. /**
  85. * find all user and group relation of UserGroups
  86. *
  87. * @static
  88. * @param {UserGroup[]} userGroups
  89. * @returns {Promise<UserGroupRelation[]>}
  90. * @memberof UserGroupRelation
  91. */
  92. static findAllRelationForUserGroups(userGroups) {
  93. return this
  94. .find({ relatedGroup: { $in: userGroups } })
  95. .populate('relatedUser')
  96. .exec();
  97. }
  98. /**
  99. * find all user and group relation of User
  100. *
  101. * @static
  102. * @param {User} user
  103. * @returns {Promise<UserGroupRelation[]>}
  104. * @memberof UserGroupRelation
  105. */
  106. static findAllRelationForUser(user) {
  107. return this
  108. .find({ relatedUser: user.id })
  109. .populate('relatedGroup')
  110. // filter documents only relatedGroup is not null
  111. .then((userGroupRelations) => {
  112. return userGroupRelations.filter((relation) => {
  113. return relation.relatedGroup != null;
  114. });
  115. });
  116. }
  117. /**
  118. * find all UserGroup IDs that related to specified User
  119. *
  120. * @static
  121. * @param {User} user
  122. * @returns {Promise<ObjectId[]>}
  123. */
  124. static async findAllUserGroupIdsRelatedToUser(user) {
  125. const relations = await this.find({ relatedUser: user._id })
  126. .select('relatedGroup')
  127. .exec();
  128. return relations.map((relation) => { return relation.relatedGroup });
  129. }
  130. /**
  131. * count by related group id and related user
  132. *
  133. * @static
  134. * @param {string} userGroupId find query param for relatedGroup
  135. * @param {User} userData find query param for relatedUser
  136. * @returns {Promise<number>}
  137. */
  138. static async countByGroupIdAndUser(userGroupId, userData) {
  139. const query = {
  140. relatedGroup: userGroupId,
  141. relatedUser: userData.id,
  142. };
  143. return this.count(query);
  144. }
  145. /**
  146. * find all "not" related user for UserGroup
  147. *
  148. * @static
  149. * @param {UserGroup} userGroup for find users not related
  150. * @returns {Promise<User>}
  151. * @memberof UserGroupRelation
  152. */
  153. static findUserByNotRelatedGroup(userGroup, queryOptions) {
  154. const User = UserGroupRelation.crowi.model('User');
  155. let searchWord = new RegExp(`${queryOptions.searchWord}`);
  156. switch (queryOptions.searchType) {
  157. case 'forward':
  158. searchWord = new RegExp(`^${queryOptions.searchWord}`);
  159. break;
  160. case 'backword':
  161. searchWord = new RegExp(`${queryOptions.searchWord}$`);
  162. break;
  163. }
  164. const searthField = [
  165. { username: searchWord },
  166. ];
  167. if (queryOptions.isAlsoMailSearched === 'true') { searthField.push({ email: searchWord }) }
  168. if (queryOptions.isAlsoNameSearched === 'true') { searthField.push({ name: searchWord }) }
  169. return this.findAllRelationForUserGroup(userGroup)
  170. .then((relations) => {
  171. const relatedUserIds = relations.map((relation) => {
  172. return relation.relatedUser.id;
  173. });
  174. const query = {
  175. _id: { $nin: relatedUserIds },
  176. status: User.STATUS_ACTIVE,
  177. $or: searthField,
  178. };
  179. debug('findUserByNotRelatedGroup ', query);
  180. return User.find(query).exec();
  181. });
  182. }
  183. /**
  184. * get if the user has relation for group
  185. *
  186. * @static
  187. * @param {UserGroup} userGroup
  188. * @param {User} user
  189. * @returns {Promise<boolean>} is user related for group(or not)
  190. * @memberof UserGroupRelation
  191. */
  192. static isRelatedUserForGroup(userGroup, user) {
  193. const query = {
  194. relatedGroup: userGroup.id,
  195. relatedUser: user.id,
  196. };
  197. return this
  198. .count(query)
  199. .exec()
  200. .then((count) => {
  201. // return true or false of the relation is exists(not count)
  202. return (count > 0);
  203. });
  204. }
  205. /**
  206. * create user and group relation
  207. *
  208. * @static
  209. * @param {UserGroup} userGroup
  210. * @param {User} user
  211. * @returns {Promise<UserGroupRelation>} created relation
  212. * @memberof UserGroupRelation
  213. */
  214. static createRelation(userGroup, user) {
  215. return this.create({
  216. relatedGroup: userGroup.id,
  217. relatedUser: user.id,
  218. });
  219. }
  220. static async createRelations(userGroupIds, user) {
  221. const documentsToInsertMany = userGroupIds.map((groupId) => {
  222. return {
  223. relatedGroup: groupId,
  224. relatedUser: user._id,
  225. createdAt: new Date(),
  226. };
  227. });
  228. return this.insertMany(documentsToInsertMany);
  229. }
  230. /**
  231. * remove all relation for UserGroup
  232. *
  233. * @static
  234. * @param {UserGroup} userGroup related group for remove
  235. * @returns {Promise<any>}
  236. * @memberof UserGroupRelation
  237. */
  238. static removeAllByUserGroups(groupsToDelete) {
  239. if (!Array.isArray(groupsToDelete)) {
  240. throw Error('groupsToDelete must be an array.');
  241. }
  242. return this.deleteMany({ relatedGroup: { $in: groupsToDelete } });
  243. }
  244. /**
  245. * remove relation by id
  246. *
  247. * @static
  248. * @param {ObjectId} id
  249. * @returns {Promise<any>}
  250. * @memberof UserGroupRelation
  251. */
  252. static removeById(id) {
  253. return this.findById(id)
  254. .then((relationData) => {
  255. if (relationData == null) {
  256. throw new Error('UserGroupRelation data is not exists. id:', id);
  257. }
  258. else {
  259. relationData.remove();
  260. }
  261. });
  262. }
  263. static async findUserIdsByGroupId(groupId) {
  264. const relations = await this.find({ relatedGroup: groupId }, { _id: 0, relatedUser: 1 }).lean().exec(); // .lean() to get not ObjectId but string
  265. return relations.map(relation => relation.relatedUser);
  266. }
  267. static async createByGroupIdsAndUserIds(groupIds, userIds) {
  268. const insertOperations = [];
  269. groupIds.forEach((groupId) => {
  270. userIds.forEach((userId) => {
  271. insertOperations.push({
  272. insertOne: {
  273. document: {
  274. relatedGroup: groupId,
  275. relatedUser: userId,
  276. },
  277. },
  278. });
  279. });
  280. });
  281. await this.bulkWrite(insertOperations);
  282. }
  283. /**
  284. * Recursively finds descendant groups by populating relations.
  285. * @static
  286. * @param {UserGroupDocument[]} groups
  287. * @param {UserDocument} user
  288. * @returns UserGroupDocument[]
  289. */
  290. static async findGroupsWithDescendantsByGroupAndUser(group, user) {
  291. const descendantGroups = [group];
  292. const incrementGroupsRecursively = async(groups, user) => {
  293. const groupIds = groups.map(g => g._id);
  294. const populatedRelations = await this.aggregate([
  295. {
  296. $match: {
  297. relatedUser: user._id,
  298. },
  299. },
  300. {
  301. $lookup: {
  302. from: 'usergroups',
  303. localField: 'relatedGroup',
  304. foreignField: '_id',
  305. as: 'relatedGroup',
  306. },
  307. },
  308. {
  309. $unwind: {
  310. path: '$relatedGroup',
  311. },
  312. },
  313. {
  314. $match: {
  315. 'relatedGroup.parent': { $in: groupIds },
  316. },
  317. },
  318. ]);
  319. const nextGroups = populatedRelations.map(d => d.relatedGroup);
  320. // End
  321. const shouldEnd = nextGroups.length === 0;
  322. if (shouldEnd) {
  323. return;
  324. }
  325. // Increment
  326. descendantGroups.push(...nextGroups);
  327. return incrementGroupsRecursively(nextGroups, user);
  328. };
  329. await incrementGroupsRecursively([group], user);
  330. return descendantGroups;
  331. }
  332. }
  333. module.exports = function(crowi) {
  334. UserGroupRelation.crowi = crowi;
  335. schema.loadClass(UserGroupRelation);
  336. const model = mongoose.model('UserGroupRelation', schema);
  337. return model;
  338. };