user-group-relation.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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. createdAt: { type: Date, default: Date.now, required: true },
  13. });
  14. schema.plugin(mongoosePaginate);
  15. schema.plugin(uniqueValidator);
  16. /**
  17. * UserGroupRelation Class
  18. *
  19. * @class UserGroupRelation
  20. */
  21. class UserGroupRelation {
  22. /**
  23. * limit items num for pagination
  24. *
  25. * @readonly
  26. * @static
  27. * @memberof UserGroupRelation
  28. */
  29. static get PAGE_ITEMS() {
  30. return 50;
  31. }
  32. static set crowi(crowi) {
  33. this._crowi = crowi;
  34. }
  35. static get crowi() {
  36. return this._crowi;
  37. }
  38. /**
  39. * remove all invalid relations that has reference to unlinked document
  40. */
  41. static removeAllInvalidRelations() {
  42. return this.findAllRelation()
  43. .then((relations) => {
  44. // filter invalid documents
  45. return relations.filter((relation) => {
  46. return relation.relatedUser == null || relation.relatedGroup == null;
  47. });
  48. })
  49. .then((invalidRelations) => {
  50. const ids = invalidRelations.map((relation) => { return relation._id });
  51. return this.deleteMany({ _id: { $in: ids } });
  52. });
  53. }
  54. /**
  55. * find all user and group relation
  56. *
  57. * @static
  58. * @returns {Promise<UserGroupRelation[]>}
  59. * @memberof UserGroupRelation
  60. */
  61. static findAllRelation() {
  62. return this
  63. .find()
  64. .populate('relatedUser')
  65. .populate('relatedGroup')
  66. .exec();
  67. }
  68. /**
  69. * find all user and group relation of UserGroup
  70. *
  71. * @static
  72. * @param {UserGroup} userGroup
  73. * @returns {Promise<UserGroupRelation[]>}
  74. * @memberof UserGroupRelation
  75. */
  76. static findAllRelationForUserGroup(userGroup) {
  77. debug('findAllRelationForUserGroup is called', userGroup);
  78. return this
  79. .find({ relatedGroup: userGroup })
  80. .populate({
  81. path: 'relatedUser',
  82. })
  83. .exec();
  84. }
  85. /**
  86. * find all user and group relation of UserGroups
  87. *
  88. * @static
  89. * @param {UserGroup[]} userGroups
  90. * @returns {Promise<UserGroupRelation[]>}
  91. * @memberof UserGroupRelation
  92. */
  93. static findAllRelationForUserGroups(userGroups) {
  94. return this
  95. .find({ relatedGroup: { $in: userGroups } })
  96. .populate('relatedUser')
  97. .exec();
  98. }
  99. /**
  100. * find all user and group relation of User
  101. *
  102. * @static
  103. * @param {User} user
  104. * @returns {Promise<UserGroupRelation[]>}
  105. * @memberof UserGroupRelation
  106. */
  107. static findAllRelationForUser(user) {
  108. return this
  109. .find({ relatedUser: user.id })
  110. .populate('relatedGroup')
  111. // filter documents only relatedGroup is not null
  112. .then((userGroupRelations) => {
  113. return userGroupRelations.filter((relation) => {
  114. return relation.relatedGroup != null;
  115. });
  116. });
  117. }
  118. /**
  119. * find all UserGroup IDs that related to specified User
  120. *
  121. * @static
  122. * @param {User} user
  123. * @returns {Promise<ObjectId[]>}
  124. */
  125. static async findAllUserGroupIdsRelatedToUser(user) {
  126. const relations = await this.find({ relatedUser: user._id })
  127. .select('relatedGroup')
  128. .exec();
  129. return relations.map((relation) => { return relation.relatedGroup });
  130. }
  131. /**
  132. * find all entities with pagination
  133. *
  134. * @see https://github.com/edwardhotchkiss/mongoose-paginate
  135. *
  136. * @static
  137. * @param {UserGroup} userGroup
  138. * @param {any} opts mongoose-paginate options object
  139. * @returns {Promise<any>} mongoose-paginate result object
  140. * @memberof UserGroupRelation
  141. */
  142. static findUserGroupRelationsWithPagination(userGroup, opts) {
  143. const query = { relatedGroup: userGroup };
  144. const options = Object.assign({}, opts);
  145. if (options.page == null) {
  146. options.page = 1;
  147. }
  148. if (options.limit == null) {
  149. options.limit = UserGroupRelation.PAGE_ITEMS;
  150. }
  151. return this.paginate(query, options)
  152. .catch((err) => {
  153. debug('Error on pagination:', err);
  154. });
  155. }
  156. /**
  157. * count by related group id and related user
  158. *
  159. * @static
  160. * @param {string} userGroupId find query param for relatedGroup
  161. * @param {User} userData find query param for relatedUser
  162. * @returns {Promise<number>}
  163. */
  164. static async countByGroupIdAndUser(userGroupId, userData) {
  165. const query = {
  166. relatedGroup: userGroupId,
  167. relatedUser: userData.id,
  168. };
  169. return this.count(query);
  170. }
  171. /**
  172. * find all "not" related user for UserGroup
  173. *
  174. * @static
  175. * @param {UserGroup} userGroup for find users not related
  176. * @returns {Promise<User>}
  177. * @memberof UserGroupRelation
  178. */
  179. static findUserByNotRelatedGroup(userGroup, queryOptions) {
  180. const User = UserGroupRelation.crowi.model('User');
  181. let searchWord = new RegExp(`${queryOptions.searchWord}`);
  182. switch (queryOptions.searchType) {
  183. case 'forward':
  184. searchWord = new RegExp(`^${queryOptions.searchWord}`);
  185. break;
  186. case 'backword':
  187. searchWord = new RegExp(`${queryOptions.searchWord}$`);
  188. break;
  189. }
  190. const searthField = [
  191. { username: searchWord },
  192. ];
  193. if (queryOptions.isAlsoMailSearched === 'true') { searthField.push({ email: searchWord }) }
  194. if (queryOptions.isAlsoNameSearched === 'true') { searthField.push({ name: searchWord }) }
  195. return this.findAllRelationForUserGroup(userGroup)
  196. .then((relations) => {
  197. const relatedUserIds = relations.map((relation) => {
  198. return relation.relatedUser.id;
  199. });
  200. const query = {
  201. _id: { $nin: relatedUserIds },
  202. status: User.STATUS_ACTIVE,
  203. $or: searthField,
  204. };
  205. debug('findUserByNotRelatedGroup ', query);
  206. return User.find(query).exec();
  207. });
  208. }
  209. /**
  210. * get if the user has relation for group
  211. *
  212. * @static
  213. * @param {UserGroup} userGroup
  214. * @param {User} user
  215. * @returns {Promise<boolean>} is user related for group(or not)
  216. * @memberof UserGroupRelation
  217. */
  218. static isRelatedUserForGroup(userGroup, user) {
  219. const query = {
  220. relatedGroup: userGroup.id,
  221. relatedUser: user.id,
  222. };
  223. return this
  224. .count(query)
  225. .exec()
  226. .then((count) => {
  227. // return true or false of the relation is exists(not count)
  228. return (count > 0);
  229. });
  230. }
  231. /**
  232. * create user and group relation
  233. *
  234. * @static
  235. * @param {UserGroup} userGroup
  236. * @param {User} user
  237. * @returns {Promise<UserGroupRelation>} created relation
  238. * @memberof UserGroupRelation
  239. */
  240. static createRelation(userGroup, user) {
  241. return this.create({
  242. relatedGroup: userGroup.id,
  243. relatedUser: user.id,
  244. });
  245. }
  246. /**
  247. * remove all relation for UserGroup
  248. *
  249. * @static
  250. * @param {UserGroup} userGroup related group for remove
  251. * @returns {Promise<any>}
  252. * @memberof UserGroupRelation
  253. */
  254. static removeAllByUserGroup(userGroup) {
  255. return this.deleteMany({ relatedGroup: userGroup });
  256. }
  257. /**
  258. * remove relation by id
  259. *
  260. * @static
  261. * @param {ObjectId} id
  262. * @returns {Promise<any>}
  263. * @memberof UserGroupRelation
  264. */
  265. static removeById(id) {
  266. return this.findById(id)
  267. .then((relationData) => {
  268. if (relationData == null) {
  269. throw new Error('UserGroupRelation data is not exists. id:', id);
  270. }
  271. else {
  272. relationData.remove();
  273. }
  274. });
  275. }
  276. }
  277. module.exports = function(crowi) {
  278. UserGroupRelation.crowi = crowi;
  279. schema.loadClass(UserGroupRelation);
  280. const model = mongoose.model('UserGroupRelation', schema);
  281. return model;
  282. };