user.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  1. /* eslint-disable no-use-before-define */
  2. import { i18n } from '^/config/next-i18next.config';
  3. import { generateGravatarSrc } from '~/utils/gravatar';
  4. import loggerFactory from '~/utils/logger';
  5. const crypto = require('crypto');
  6. const mongoose = require('mongoose');
  7. const mongoosePaginate = require('mongoose-paginate-v2');
  8. const uniqueValidator = require('mongoose-unique-validator');
  9. const ObjectId = mongoose.Schema.Types.ObjectId;
  10. const { omitInsecureAttributes } = require('./serializers/user-serializer');
  11. const logger = loggerFactory('growi:models:user');
  12. module.exports = function(crowi) {
  13. const STATUS_REGISTERED = 1;
  14. const STATUS_ACTIVE = 2;
  15. const STATUS_SUSPENDED = 3;
  16. const STATUS_DELETED = 4;
  17. const STATUS_INVITED = 5;
  18. const USER_FIELDS_EXCEPT_CONFIDENTIAL = '_id image isEmailPublished isGravatarEnabled googleId name username email introduction'
  19. + ' status lang createdAt lastLoginAt admin imageUrlCached';
  20. const PAGE_ITEMS = 50;
  21. let userEvent;
  22. // init event
  23. if (crowi != null) {
  24. userEvent = crowi.event('user');
  25. userEvent.on('activated', userEvent.onActivated);
  26. }
  27. const userSchema = new mongoose.Schema({
  28. userId: String,
  29. image: String,
  30. imageAttachment: { type: ObjectId, ref: 'Attachment' },
  31. imageUrlCached: String,
  32. isGravatarEnabled: { type: Boolean, default: false },
  33. isEmailPublished: { type: Boolean, default: true },
  34. googleId: String,
  35. name: { type: String },
  36. username: { type: String, required: true, unique: true },
  37. email: { type: String, unique: true, sparse: true },
  38. slackMemberId: { type: String, unique: true, sparse: true },
  39. // === Crowi settings
  40. // username: { type: String, index: true },
  41. // email: { type: String, required: true, index: true },
  42. // === crowi-plus (>= 2.1.0, <2.3.0) settings
  43. // email: { type: String, required: true, unique: true },
  44. introduction: String,
  45. password: String,
  46. apiToken: { type: String, index: true },
  47. lang: {
  48. type: String,
  49. enum: i18n.locales,
  50. default: 'en_US',
  51. },
  52. status: {
  53. type: Number, required: true, default: STATUS_ACTIVE, index: true,
  54. },
  55. lastLoginAt: { type: Date },
  56. admin: { type: Boolean, default: 0, index: true },
  57. readOnly: { type: Boolean, default: 0 },
  58. isInvitationEmailSended: { type: Boolean, default: false },
  59. isQuestionnaireEnabled: { type: Boolean, default: true },
  60. }, {
  61. timestamps: true,
  62. toObject: {
  63. transform: (doc, ret, opt) => {
  64. return omitInsecureAttributes(ret);
  65. },
  66. },
  67. });
  68. userSchema.plugin(mongoosePaginate);
  69. userSchema.plugin(uniqueValidator);
  70. function validateCrowi() {
  71. if (crowi == null) {
  72. throw new Error('"crowi" is null. Init User model with "crowi" argument first.');
  73. }
  74. }
  75. function decideUserStatusOnRegistration() {
  76. validateCrowi();
  77. const { configManager, aclService } = crowi;
  78. const isInstalled = configManager.getConfig('crowi', 'app:installed');
  79. if (!isInstalled) {
  80. return STATUS_ACTIVE; // is this ok?
  81. }
  82. // status decided depends on registrationMode
  83. const registrationMode = configManager.getConfig('crowi', 'security:registrationMode');
  84. switch (registrationMode) {
  85. case aclService.labels.SECURITY_REGISTRATION_MODE_OPEN:
  86. return STATUS_ACTIVE;
  87. case aclService.labels.SECURITY_REGISTRATION_MODE_RESTRICTED:
  88. case aclService.labels.SECURITY_REGISTRATION_MODE_CLOSED: // 一応
  89. return STATUS_REGISTERED;
  90. default:
  91. return STATUS_ACTIVE; // どっちにすんのがいいんだろうな
  92. }
  93. }
  94. function generateRandomEmail() {
  95. const randomstr = generateRandomTempPassword();
  96. return `change-it-${randomstr}@example.com`;
  97. }
  98. function generateRandomTempPassword() {
  99. const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!=-_';
  100. let password = '';
  101. const len = 12;
  102. for (let i = 0; i < len; i++) {
  103. const randomPoz = Math.floor(Math.random() * chars.length);
  104. password += chars.substring(randomPoz, randomPoz + 1);
  105. }
  106. return password;
  107. }
  108. function generatePassword(password) {
  109. validateCrowi();
  110. const hasher = crypto.createHash('sha256');
  111. hasher.update(crowi.env.PASSWORD_SEED + password);
  112. return hasher.digest('hex');
  113. }
  114. function generateApiToken(user) {
  115. const hasher = crypto.createHash('sha256');
  116. hasher.update((new Date()).getTime() + user._id);
  117. return hasher.digest('base64');
  118. }
  119. userSchema.methods.isPasswordSet = function() {
  120. if (this.password) {
  121. return true;
  122. }
  123. return false;
  124. };
  125. userSchema.methods.isPasswordValid = function(password) {
  126. return this.password === generatePassword(password);
  127. };
  128. userSchema.methods.setPassword = function(password) {
  129. this.password = generatePassword(password);
  130. return this;
  131. };
  132. userSchema.methods.isEmailSet = function() {
  133. if (this.email) {
  134. return true;
  135. }
  136. return false;
  137. };
  138. userSchema.methods.updateLastLoginAt = function(lastLoginAt, callback) {
  139. this.lastLoginAt = lastLoginAt;
  140. this.save((err, userData) => {
  141. return callback(err, userData);
  142. });
  143. };
  144. userSchema.methods.updateIsGravatarEnabled = async function(isGravatarEnabled) {
  145. this.isGravatarEnabled = isGravatarEnabled;
  146. await this.updateImageUrlCached();
  147. const userData = await this.save();
  148. return userData;
  149. };
  150. userSchema.methods.updatePassword = async function(password) {
  151. this.setPassword(password);
  152. const userData = await this.save();
  153. return userData;
  154. };
  155. userSchema.methods.updateApiToken = async function() {
  156. const self = this;
  157. self.apiToken = generateApiToken(this);
  158. const userData = await self.save();
  159. return userData;
  160. };
  161. // TODO: create UserService and transplant this method because image uploading depends on AttachmentService
  162. userSchema.methods.updateImage = async function(attachment) {
  163. this.imageAttachment = attachment;
  164. await this.updateImageUrlCached();
  165. return this.save();
  166. };
  167. // TODO: create UserService and transplant this method because image deletion depends on AttachmentService
  168. userSchema.methods.deleteImage = async function() {
  169. validateCrowi();
  170. // the 'image' field became DEPRECATED in v3.3.8
  171. this.image = undefined;
  172. if (this.imageAttachment != null) {
  173. const { attachmentService } = crowi;
  174. attachmentService.removeAttachment(this.imageAttachment._id);
  175. }
  176. this.imageAttachment = undefined;
  177. this.updateImageUrlCached();
  178. return this.save();
  179. };
  180. userSchema.methods.updateImageUrlCached = async function() {
  181. this.imageUrlCached = await this.generateImageUrlCached();
  182. };
  183. userSchema.methods.generateImageUrlCached = async function() {
  184. if (this.isGravatarEnabled) {
  185. return generateGravatarSrc(this.email);
  186. }
  187. if (this.image != null) {
  188. return this.image;
  189. }
  190. if (this.imageAttachment != null && this.imageAttachment._id != null) {
  191. const Attachment = crowi.model('Attachment');
  192. const imageAttachment = await Attachment.findById(this.imageAttachment);
  193. return imageAttachment.filePathProxied;
  194. }
  195. return '/images/icons/user.svg';
  196. };
  197. userSchema.methods.updateGoogleId = function(googleId, callback) {
  198. this.googleId = googleId;
  199. this.save((err, userData) => {
  200. return callback(err, userData);
  201. });
  202. };
  203. userSchema.methods.deleteGoogleId = function(callback) {
  204. return this.updateGoogleId(null, callback);
  205. };
  206. userSchema.methods.activateInvitedUser = async function(username, name, password) {
  207. this.setPassword(password);
  208. this.name = name;
  209. this.username = username;
  210. this.status = STATUS_ACTIVE;
  211. this.isEmailPublished = crowi.configManager.getConfig('crowi', 'customize:isEmailPublishedForNewUser');
  212. this.save((err, userData) => {
  213. userEvent.emit('activated', userData);
  214. if (err) {
  215. throw new Error(err);
  216. }
  217. return userData;
  218. });
  219. };
  220. userSchema.methods.removeFromAdmin = async function() {
  221. logger.debug('Remove from admin', this);
  222. this.admin = 0;
  223. return this.save();
  224. };
  225. userSchema.methods.makeAdmin = async function() {
  226. logger.debug('Admin', this);
  227. this.admin = 1;
  228. return this.save();
  229. };
  230. userSchema.methods.grantReadOnly = async function() {
  231. logger.debug('Grant read only flag', this);
  232. this.readOnly = 1;
  233. return this.save();
  234. };
  235. userSchema.methods.revokeReadOnly = async function() {
  236. logger.debug('Revoke read only flag', this);
  237. this.readOnly = 0;
  238. return this.save();
  239. };
  240. userSchema.methods.asyncMakeAdmin = async function(callback) {
  241. this.admin = 1;
  242. return this.save();
  243. };
  244. userSchema.methods.statusActivate = async function() {
  245. logger.debug('Activate User', this);
  246. this.status = STATUS_ACTIVE;
  247. const userData = await this.save();
  248. return userEvent.emit('activated', userData);
  249. };
  250. userSchema.methods.statusSuspend = async function() {
  251. logger.debug('Suspend User', this);
  252. this.status = STATUS_SUSPENDED;
  253. if (this.email === undefined || this.email === null) { // migrate old data
  254. this.email = '-';
  255. }
  256. if (this.name === undefined || this.name === null) { // migrate old data
  257. this.name = `-${Date.now()}`;
  258. }
  259. if (this.username === undefined || this.usename === null) { // migrate old data
  260. this.username = '-';
  261. }
  262. return this.save();
  263. };
  264. userSchema.methods.statusDelete = async function() {
  265. logger.debug('Delete User', this);
  266. const now = new Date();
  267. const deletedLabel = `deleted_at_${now.getTime()}`;
  268. this.status = STATUS_DELETED;
  269. this.username = deletedLabel;
  270. this.password = '';
  271. this.name = '';
  272. this.email = `${deletedLabel}@deleted`;
  273. this.googleId = null;
  274. this.isGravatarEnabled = false;
  275. this.image = null;
  276. return this.save();
  277. };
  278. userSchema.statics.getUserStatusLabels = function() {
  279. const userStatus = {};
  280. userStatus[STATUS_REGISTERED] = 'Approval Pending';
  281. userStatus[STATUS_ACTIVE] = 'Active';
  282. userStatus[STATUS_SUSPENDED] = 'Suspended';
  283. userStatus[STATUS_DELETED] = 'Deleted';
  284. userStatus[STATUS_INVITED] = 'Invited';
  285. return userStatus;
  286. };
  287. userSchema.statics.isEmailValid = function(email, callback) {
  288. validateCrowi();
  289. const whitelist = crowi.configManager.getConfig('crowi', 'security:registrationWhiteList');
  290. if (Array.isArray(whitelist) && whitelist.length > 0) {
  291. return whitelist.some((allowedEmail) => {
  292. const re = new RegExp(`${allowedEmail}$`);
  293. return re.test(email);
  294. });
  295. }
  296. return true;
  297. };
  298. userSchema.statics.findUsers = function(options, callback) {
  299. const sort = options.sort || { status: 1, createdAt: 1 };
  300. this.find()
  301. .sort(sort)
  302. .skip(options.skip || 0)
  303. .limit(options.limit || 21)
  304. .exec((err, userData) => {
  305. callback(err, userData);
  306. });
  307. };
  308. userSchema.statics.findAllUsers = function(option) {
  309. // eslint-disable-next-line no-param-reassign
  310. option = option || {};
  311. const sort = option.sort || { createdAt: -1 };
  312. const fields = option.fields || {};
  313. let status = option.status || [STATUS_ACTIVE, STATUS_SUSPENDED];
  314. if (!Array.isArray(status)) {
  315. status = [status];
  316. }
  317. return this.find()
  318. .or(status.map((s) => { return { status: s } }))
  319. .select(fields)
  320. .sort(sort);
  321. };
  322. userSchema.statics.findUsersByIds = function(ids, option) {
  323. // eslint-disable-next-line no-param-reassign
  324. option = option || {};
  325. const sort = option.sort || { createdAt: -1 };
  326. const status = option.status || STATUS_ACTIVE;
  327. const fields = option.fields || {};
  328. return this.find({ _id: { $in: ids }, status })
  329. .select(fields)
  330. .sort(sort);
  331. };
  332. userSchema.statics.findAdmins = async function(option) {
  333. const sort = option?.sort ?? { createdAt: -1 };
  334. let status = option?.status ?? [STATUS_ACTIVE];
  335. if (!Array.isArray(status)) {
  336. status = [status];
  337. }
  338. return this.find({ admin: true, status: { $in: status } })
  339. .sort(sort);
  340. };
  341. userSchema.statics.findUserByUsername = function(username) {
  342. if (username == null) {
  343. return Promise.resolve(null);
  344. }
  345. return this.findOne({ username });
  346. };
  347. userSchema.statics.findUserByApiToken = function(apiToken) {
  348. if (apiToken == null) {
  349. return Promise.resolve(null);
  350. }
  351. return this.findOne({ apiToken });
  352. };
  353. userSchema.statics.findUserByGoogleId = function(googleId, callback) {
  354. if (googleId == null) {
  355. callback(null, null);
  356. }
  357. this.findOne({ googleId }, (err, userData) => {
  358. callback(err, userData);
  359. });
  360. };
  361. userSchema.statics.findUserByUsernameOrEmail = function(usernameOrEmail, password, callback) {
  362. this.findOne()
  363. .or([
  364. { username: usernameOrEmail },
  365. { email: usernameOrEmail },
  366. ])
  367. .exec((err, userData) => {
  368. callback(err, userData);
  369. });
  370. };
  371. userSchema.statics.findUserByEmailAndPassword = function(email, password, callback) {
  372. const hashedPassword = generatePassword(password);
  373. this.findOne({ email, password: hashedPassword }, (err, userData) => {
  374. callback(err, userData);
  375. });
  376. };
  377. userSchema.statics.isUserCountExceedsUpperLimit = async function() {
  378. const { configManager } = crowi;
  379. const userUpperLimit = configManager.getConfig('crowi', 'security:userUpperLimit');
  380. const activeUsers = await this.countActiveUsers();
  381. if (userUpperLimit <= activeUsers) {
  382. return true;
  383. }
  384. return false;
  385. };
  386. userSchema.statics.countActiveUsers = async function() {
  387. return this.countListByStatus(STATUS_ACTIVE);
  388. };
  389. userSchema.statics.countListByStatus = async function(status) {
  390. const User = this;
  391. const conditions = { status };
  392. // TODO count は非推奨。mongoose のバージョンアップ後に countDocuments に変更する。
  393. return User.count(conditions);
  394. };
  395. userSchema.statics.isRegisterableUsername = async function(username) {
  396. let usernameUsable = true;
  397. const userData = await this.findOne({ username });
  398. if (userData) {
  399. usernameUsable = false;
  400. }
  401. return usernameUsable;
  402. };
  403. userSchema.statics.isRegisterableEmail = async function(email) {
  404. let isEmailUsable = true;
  405. const userData = await this.findOne({ email });
  406. if (userData) {
  407. isEmailUsable = false;
  408. }
  409. return isEmailUsable;
  410. };
  411. userSchema.statics.isRegisterable = function(email, username, callback) {
  412. const User = this;
  413. let emailUsable = true;
  414. let usernameUsable = true;
  415. // username check
  416. this.findOne({ username }, (err, userData) => {
  417. if (userData) {
  418. usernameUsable = false;
  419. }
  420. // email check
  421. User.findOne({ email }, (err, userData) => {
  422. if (userData) {
  423. emailUsable = false;
  424. }
  425. if (!emailUsable || !usernameUsable) {
  426. return callback(false, { email: emailUsable, username: usernameUsable });
  427. }
  428. return callback(true, {});
  429. });
  430. });
  431. };
  432. userSchema.statics.resetPasswordByRandomString = async function(id) {
  433. const user = await this.findById(id);
  434. if (!user) {
  435. throw new Error('User not found');
  436. }
  437. const newPassword = generateRandomTempPassword();
  438. user.setPassword(newPassword);
  439. await user.save();
  440. return newPassword;
  441. };
  442. userSchema.statics.createUserByEmail = async function(email) {
  443. const configManager = crowi.configManager;
  444. const User = this;
  445. const newUser = new User();
  446. /* eslint-disable newline-per-chained-call */
  447. const tmpUsername = `temp_${Math.random().toString(36).slice(-16)}`;
  448. const password = Math.random().toString(36).slice(-16);
  449. /* eslint-enable newline-per-chained-call */
  450. newUser.username = tmpUsername;
  451. newUser.email = email;
  452. newUser.setPassword(password);
  453. newUser.status = STATUS_INVITED;
  454. const globalLang = configManager.getConfig('crowi', 'app:globalLang');
  455. if (globalLang != null) {
  456. newUser.lang = globalLang;
  457. }
  458. try {
  459. const newUserData = await newUser.save();
  460. return {
  461. email,
  462. password,
  463. user: newUserData,
  464. };
  465. }
  466. catch (err) {
  467. return {
  468. email,
  469. };
  470. }
  471. };
  472. userSchema.statics.createUsersByEmailList = async function(emailList) {
  473. const User = this;
  474. // check exists and get list of try to create
  475. const existingUserList = await User.find({ email: { $in: emailList }, userStatus: { $ne: STATUS_DELETED } });
  476. const existingEmailList = existingUserList.map((user) => { return user.email });
  477. const creationEmailList = emailList.filter((email) => { return existingEmailList.indexOf(email) === -1 });
  478. const createdUserList = [];
  479. const failedToCreateUserEmailList = [];
  480. for (const email of creationEmailList) {
  481. try {
  482. // eslint-disable-next-line no-await-in-loop
  483. const createdUser = await this.createUserByEmail(email);
  484. createdUserList.push(createdUser);
  485. }
  486. catch (err) {
  487. logger.error(err);
  488. failedToCreateUserEmailList.push({
  489. email,
  490. reason: err.message,
  491. });
  492. }
  493. }
  494. return { createdUserList, existingEmailList, failedToCreateUserEmailList };
  495. };
  496. userSchema.statics.createUserByEmailAndPasswordAndStatus = async function(name, username, email, password, lang, status, callback) {
  497. const User = this;
  498. const newUser = new User();
  499. // check user upper limit
  500. const isUserCountExceedsUpperLimit = await User.isUserCountExceedsUpperLimit();
  501. if (isUserCountExceedsUpperLimit) {
  502. const err = new UserUpperLimitException();
  503. return callback(err);
  504. }
  505. // check email duplication because email must be unique
  506. const count = await this.count({ email });
  507. if (count > 0) {
  508. // eslint-disable-next-line no-param-reassign
  509. email = generateRandomEmail();
  510. }
  511. newUser.name = name;
  512. newUser.username = username;
  513. newUser.email = email;
  514. if (password != null) {
  515. newUser.setPassword(password);
  516. }
  517. const configManager = crowi.configManager;
  518. // Default email show/hide is up to the administrator
  519. newUser.isEmailPublished = configManager.getConfig('crowi', 'customize:isEmailPublishedForNewUser');
  520. const globalLang = configManager.getConfig('crowi', 'app:globalLang');
  521. if (globalLang != null) {
  522. newUser.lang = globalLang;
  523. }
  524. if (lang != null) {
  525. newUser.lang = lang;
  526. }
  527. newUser.status = status || decideUserStatusOnRegistration();
  528. newUser.save((err, userData) => {
  529. if (err) {
  530. logger.error('createUserByEmailAndPasswordAndStatus failed: ', err);
  531. return callback(err);
  532. }
  533. if (userData.status === STATUS_ACTIVE) {
  534. userEvent.emit('activated', userData);
  535. }
  536. return callback(err, userData);
  537. });
  538. };
  539. /**
  540. * A wrapper function of createUserByEmailAndPasswordAndStatus with callback
  541. *
  542. */
  543. userSchema.statics.createUserByEmailAndPassword = function(name, username, email, password, lang, callback) {
  544. this.createUserByEmailAndPasswordAndStatus(name, username, email, password, lang, undefined, callback);
  545. };
  546. /**
  547. * A wrapper function of createUserByEmailAndPasswordAndStatus
  548. *
  549. * @return {Promise<User>}
  550. */
  551. userSchema.statics.createUser = function(name, username, email, password, lang, status) {
  552. const User = this;
  553. return new Promise((resolve, reject) => {
  554. User.createUserByEmailAndPasswordAndStatus(name, username, email, password, lang, status, (err, userData) => {
  555. if (err) {
  556. return reject(err);
  557. }
  558. return resolve(userData);
  559. });
  560. });
  561. };
  562. userSchema.statics.getUsernameByPath = function(path) {
  563. let username = null;
  564. const match = path.match(/^\/user\/([^/]+)\/?/);
  565. if (match) {
  566. username = match[1];
  567. }
  568. return username;
  569. };
  570. userSchema.statics.updateIsInvitationEmailSended = async function(id) {
  571. const user = await this.findById(id);
  572. if (user == null) {
  573. throw new Error('User not found');
  574. }
  575. if (user.status !== 5) {
  576. throw new Error('The status of the user is not "invited"');
  577. }
  578. user.isInvitationEmailSended = true;
  579. user.save();
  580. };
  581. userSchema.statics.findUserBySlackMemberId = async function(slackMemberId) {
  582. const user = this.findOne({ slackMemberId });
  583. if (user == null) {
  584. throw new Error('User not found');
  585. }
  586. return user;
  587. };
  588. userSchema.statics.findUsersBySlackMemberIds = async function(slackMemberIds) {
  589. const users = this.find({ slackMemberId: { $in: slackMemberIds } });
  590. if (users.length === 0) {
  591. throw new Error('No user found');
  592. }
  593. return users;
  594. };
  595. userSchema.statics.findUserByUsernameRegexWithTotalCount = async function(username, status, option) {
  596. const opt = option || {};
  597. const sortOpt = opt.sortOpt || { username: 1 };
  598. const offset = opt.offset || 0;
  599. const limit = opt.limit || 10;
  600. const conditions = { username: { $regex: username, $options: 'i' }, status: { $in: status } };
  601. const users = await this.find(conditions)
  602. .sort(sortOpt)
  603. .skip(offset)
  604. .limit(limit);
  605. const totalCount = (await this.find(conditions).distinct('username')).length;
  606. return { users, totalCount };
  607. };
  608. userSchema.methods.updateIsQuestionnaireEnabled = async function(value) {
  609. this.isQuestionnaireEnabled = value;
  610. return this.save();
  611. };
  612. class UserUpperLimitException {
  613. constructor() {
  614. this.name = this.constructor.name;
  615. }
  616. }
  617. userSchema.statics.STATUS_REGISTERED = STATUS_REGISTERED;
  618. userSchema.statics.STATUS_ACTIVE = STATUS_ACTIVE;
  619. userSchema.statics.STATUS_SUSPENDED = STATUS_SUSPENDED;
  620. userSchema.statics.STATUS_DELETED = STATUS_DELETED;
  621. userSchema.statics.STATUS_INVITED = STATUS_INVITED;
  622. userSchema.statics.USER_FIELDS_EXCEPT_CONFIDENTIAL = USER_FIELDS_EXCEPT_CONFIDENTIAL;
  623. userSchema.statics.PAGE_ITEMS = PAGE_ITEMS;
  624. return mongoose.model('User', userSchema);
  625. };