user-group-relation.js 7.8 KB

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