user.js 22 KB

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