user.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  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. import { Attachment } from './attachment';
  7. const crypto = require('crypto');
  8. const mongoose = require('mongoose');
  9. const mongoosePaginate = require('mongoose-paginate-v2');
  10. const uniqueValidator = require('mongoose-unique-validator');
  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: mongoose.Schema.Types.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, index: true },
  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, index: true },
  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 imageAttachment = await Attachment.findById(this.imageAttachment);
  206. return imageAttachment.filePathProxied;
  207. }
  208. return '/images/icons/user.svg';
  209. };
  210. userSchema.methods.updateGoogleId = function(googleId, callback) {
  211. this.googleId = googleId;
  212. this.save((err, userData) => {
  213. return callback(err, userData);
  214. });
  215. };
  216. userSchema.methods.deleteGoogleId = function(callback) {
  217. return this.updateGoogleId(null, callback);
  218. };
  219. userSchema.methods.activateInvitedUser = async function(username, name, password) {
  220. this.setPassword(password);
  221. this.name = name;
  222. this.username = username;
  223. this.status = STATUS_ACTIVE;
  224. this.isEmailPublished = crowi.configManager.getConfig('crowi', 'customize:isEmailPublishedForNewUser');
  225. this.save((err, userData) => {
  226. userEvent.emit('activated', userData);
  227. if (err) {
  228. throw new Error(err);
  229. }
  230. return userData;
  231. });
  232. };
  233. userSchema.methods.grantAdmin = async function() {
  234. logger.debug('Grant Admin', this);
  235. this.admin = 1;
  236. return this.save();
  237. };
  238. userSchema.methods.revokeAdmin = async function() {
  239. logger.debug('Revove admin', this);
  240. this.admin = 0;
  241. return this.save();
  242. };
  243. userSchema.methods.grantReadOnly = async function() {
  244. logger.debug('Grant read only access', this);
  245. this.readOnly = 1;
  246. return this.save();
  247. };
  248. userSchema.methods.revokeReadOnly = async function() {
  249. logger.debug('Revoke read only access', this);
  250. this.readOnly = 0;
  251. return this.save();
  252. };
  253. userSchema.methods.asyncGrantAdmin = async function(callback) {
  254. this.admin = 1;
  255. return this.save();
  256. };
  257. userSchema.methods.statusActivate = async function() {
  258. logger.debug('Activate User', this);
  259. this.status = STATUS_ACTIVE;
  260. const userData = await this.save();
  261. return userEvent.emit('activated', userData);
  262. };
  263. userSchema.methods.statusSuspend = async function() {
  264. logger.debug('Suspend User', this);
  265. this.status = STATUS_SUSPENDED;
  266. if (this.email === undefined || this.email === null) { // migrate old data
  267. this.email = '-';
  268. }
  269. if (this.name === undefined || this.name === null) { // migrate old data
  270. this.name = `-${Date.now()}`;
  271. }
  272. if (this.username === undefined || this.usename === null) { // migrate old data
  273. this.username = '-';
  274. }
  275. return this.save();
  276. };
  277. userSchema.methods.statusDelete = async function() {
  278. logger.debug('Delete User', this);
  279. const now = new Date();
  280. const deletedLabel = `deleted_at_${now.getTime()}`;
  281. this.status = STATUS_DELETED;
  282. this.username = deletedLabel;
  283. this.password = '';
  284. this.name = '';
  285. this.email = `${deletedLabel}@deleted`;
  286. this.googleId = null;
  287. this.isGravatarEnabled = false;
  288. this.image = null;
  289. return this.save();
  290. };
  291. userSchema.statics.getUserStatusLabels = function() {
  292. const userStatus = {};
  293. userStatus[STATUS_REGISTERED] = 'Approval Pending';
  294. userStatus[STATUS_ACTIVE] = 'Active';
  295. userStatus[STATUS_SUSPENDED] = 'Suspended';
  296. userStatus[STATUS_DELETED] = 'Deleted';
  297. userStatus[STATUS_INVITED] = 'Invited';
  298. return userStatus;
  299. };
  300. userSchema.statics.isEmailValid = function(email, callback) {
  301. validateCrowi();
  302. const whitelist = crowi.configManager.getConfig('crowi', 'security:registrationWhitelist');
  303. if (Array.isArray(whitelist) && whitelist.length > 0) {
  304. return whitelist.some((allowedEmail) => {
  305. const re = new RegExp(`${allowedEmail}$`);
  306. return re.test(email);
  307. });
  308. }
  309. return true;
  310. };
  311. userSchema.statics.findUsers = function(options, callback) {
  312. const sort = options.sort || { status: 1, createdAt: 1 };
  313. this.find()
  314. .sort(sort)
  315. .skip(options.skip || 0)
  316. .limit(options.limit || 21)
  317. .exec((err, userData) => {
  318. callback(err, userData);
  319. });
  320. };
  321. userSchema.statics.findAllUsers = function(option) {
  322. // eslint-disable-next-line no-param-reassign
  323. option = option || {};
  324. const sort = option.sort || { createdAt: -1 };
  325. const fields = option.fields || {};
  326. let status = option.status || [STATUS_ACTIVE, STATUS_SUSPENDED];
  327. if (!Array.isArray(status)) {
  328. status = [status];
  329. }
  330. return this.find()
  331. .or(status.map((s) => { return { status: s } }))
  332. .select(fields)
  333. .sort(sort);
  334. };
  335. userSchema.statics.findUsersByIds = function(ids, option) {
  336. // eslint-disable-next-line no-param-reassign
  337. option = option || {};
  338. const sort = option.sort || { createdAt: -1 };
  339. const status = option.status || STATUS_ACTIVE;
  340. const fields = option.fields || {};
  341. return this.find({ _id: { $in: ids }, status })
  342. .select(fields)
  343. .sort(sort);
  344. };
  345. userSchema.statics.findAdmins = async function(option) {
  346. const sort = option?.sort ?? { createdAt: -1 };
  347. let status = option?.status ?? [STATUS_ACTIVE];
  348. if (!Array.isArray(status)) {
  349. status = [status];
  350. }
  351. return this.find({ admin: true, status: { $in: status } })
  352. .sort(sort);
  353. };
  354. userSchema.statics.findUserByUsername = function(username) {
  355. if (username == null) {
  356. return Promise.resolve(null);
  357. }
  358. return this.findOne({ username });
  359. };
  360. userSchema.statics.findUserByApiToken = function(apiToken) {
  361. if (apiToken == null) {
  362. return Promise.resolve(null);
  363. }
  364. return this.findOne({ apiToken });
  365. };
  366. userSchema.statics.findUserByGoogleId = function(googleId, callback) {
  367. if (googleId == null) {
  368. callback(null, null);
  369. }
  370. this.findOne({ googleId }, (err, userData) => {
  371. callback(err, userData);
  372. });
  373. };
  374. userSchema.statics.findUserByUsernameOrEmail = function(usernameOrEmail, password, callback) {
  375. this.findOne()
  376. .or([
  377. { username: usernameOrEmail },
  378. { email: usernameOrEmail },
  379. ])
  380. .exec((err, userData) => {
  381. callback(err, userData);
  382. });
  383. };
  384. userSchema.statics.findUserByEmailAndPassword = function(email, password, callback) {
  385. const hashedPassword = generatePassword(password);
  386. this.findOne({ email, password: hashedPassword }, (err, userData) => {
  387. callback(err, userData);
  388. });
  389. };
  390. userSchema.statics.isUserCountExceedsUpperLimit = async function() {
  391. const { configManager } = crowi;
  392. const userUpperLimit = configManager.getConfig('crowi', 'security:userUpperLimit');
  393. const activeUsers = await this.countActiveUsers();
  394. if (userUpperLimit <= activeUsers) {
  395. return true;
  396. }
  397. return false;
  398. };
  399. userSchema.statics.countActiveUsers = async function() {
  400. return this.countListByStatus(STATUS_ACTIVE);
  401. };
  402. userSchema.statics.countListByStatus = async function(status) {
  403. const User = this;
  404. const conditions = { status };
  405. // TODO count は非推奨。mongoose のバージョンアップ後に countDocuments に変更する。
  406. return User.count(conditions);
  407. };
  408. userSchema.statics.isRegisterableUsername = async function(username) {
  409. let usernameUsable = true;
  410. const userData = await this.findOne({ username });
  411. if (userData) {
  412. usernameUsable = false;
  413. }
  414. return usernameUsable;
  415. };
  416. userSchema.statics.isRegisterableEmail = async function(email) {
  417. let isEmailUsable = true;
  418. const userData = await this.findOne({ email });
  419. if (userData) {
  420. isEmailUsable = false;
  421. }
  422. return isEmailUsable;
  423. };
  424. userSchema.statics.isRegisterable = function(email, username, callback) {
  425. const User = this;
  426. let emailUsable = true;
  427. let usernameUsable = true;
  428. // username check
  429. this.findOne({ username }, (err, userData) => {
  430. if (userData) {
  431. usernameUsable = false;
  432. }
  433. // email check
  434. User.findOne({ email }, (err, userData) => {
  435. if (userData) {
  436. emailUsable = false;
  437. }
  438. if (!emailUsable || !usernameUsable) {
  439. return callback(false, { email: emailUsable, username: usernameUsable });
  440. }
  441. return callback(true, {});
  442. });
  443. });
  444. };
  445. userSchema.statics.resetPasswordByRandomString = async function(id) {
  446. const user = await this.findById(id);
  447. if (!user) {
  448. throw new Error('User not found');
  449. }
  450. const newPassword = generateRandomTempPassword();
  451. user.setPassword(newPassword);
  452. await user.save();
  453. return newPassword;
  454. };
  455. userSchema.statics.createUserByEmail = async function(email) {
  456. const configManager = crowi.configManager;
  457. const User = this;
  458. const newUser = new User();
  459. /* eslint-disable newline-per-chained-call */
  460. const tmpUsername = `temp_${Math.random().toString(36).slice(-16)}`;
  461. const password = Math.random().toString(36).slice(-16);
  462. /* eslint-enable newline-per-chained-call */
  463. newUser.username = tmpUsername;
  464. newUser.email = email;
  465. newUser.setPassword(password);
  466. newUser.status = STATUS_INVITED;
  467. const globalLang = configManager.getConfig('crowi', 'app:globalLang');
  468. if (globalLang != null) {
  469. newUser.lang = globalLang;
  470. }
  471. try {
  472. const newUserData = await newUser.save();
  473. return {
  474. email,
  475. password,
  476. user: newUserData,
  477. };
  478. }
  479. catch (err) {
  480. return {
  481. email,
  482. };
  483. }
  484. };
  485. userSchema.statics.createUsersByEmailList = async function(emailList) {
  486. const User = this;
  487. // check exists and get list of try to create
  488. const existingUserList = await User.find({ email: { $in: emailList }, userStatus: { $ne: STATUS_DELETED } });
  489. const existingEmailList = existingUserList.map((user) => { return user.email });
  490. const creationEmailList = emailList.filter((email) => { return existingEmailList.indexOf(email) === -1 });
  491. const createdUserList = [];
  492. const failedToCreateUserEmailList = [];
  493. for (const email of creationEmailList) {
  494. try {
  495. // eslint-disable-next-line no-await-in-loop
  496. const createdUser = await this.createUserByEmail(email);
  497. createdUserList.push(createdUser);
  498. }
  499. catch (err) {
  500. logger.error(err);
  501. failedToCreateUserEmailList.push({
  502. email,
  503. reason: err.message,
  504. });
  505. }
  506. }
  507. return { createdUserList, existingEmailList, failedToCreateUserEmailList };
  508. };
  509. userSchema.statics.createUserByEmailAndPasswordAndStatus = async function(name, username, email, password, lang, status, callback) {
  510. const User = this;
  511. const newUser = new User();
  512. // check user upper limit
  513. const isUserCountExceedsUpperLimit = await User.isUserCountExceedsUpperLimit();
  514. if (isUserCountExceedsUpperLimit) {
  515. const err = new UserUpperLimitException();
  516. return callback(err);
  517. }
  518. // check email duplication because email must be unique
  519. const count = await this.count({ email });
  520. if (count > 0) {
  521. // eslint-disable-next-line no-param-reassign
  522. email = generateRandomEmail();
  523. }
  524. newUser.name = name;
  525. newUser.username = username;
  526. newUser.email = email;
  527. if (password != null) {
  528. newUser.setPassword(password);
  529. }
  530. const configManager = crowi.configManager;
  531. // Default email show/hide is up to the administrator
  532. newUser.isEmailPublished = configManager.getConfig('crowi', 'customize:isEmailPublishedForNewUser');
  533. const globalLang = configManager.getConfig('crowi', 'app:globalLang');
  534. if (globalLang != null) {
  535. newUser.lang = globalLang;
  536. }
  537. if (lang != null) {
  538. newUser.lang = lang;
  539. }
  540. newUser.status = status || decideUserStatusOnRegistration();
  541. newUser.save((err, userData) => {
  542. if (err) {
  543. logger.error('createUserByEmailAndPasswordAndStatus failed: ', err);
  544. return callback(err);
  545. }
  546. if (userData.status === STATUS_ACTIVE) {
  547. userEvent.emit('activated', userData);
  548. }
  549. return callback(err, userData);
  550. });
  551. };
  552. /**
  553. * A wrapper function of createUserByEmailAndPasswordAndStatus with callback
  554. *
  555. */
  556. userSchema.statics.createUserByEmailAndPassword = function(name, username, email, password, lang, callback) {
  557. this.createUserByEmailAndPasswordAndStatus(name, username, email, password, lang, undefined, callback);
  558. };
  559. /**
  560. * A wrapper function of createUserByEmailAndPasswordAndStatus
  561. *
  562. * @return {Promise<User>}
  563. */
  564. userSchema.statics.createUser = function(name, username, email, password, lang, status) {
  565. const User = this;
  566. return new Promise((resolve, reject) => {
  567. User.createUserByEmailAndPasswordAndStatus(name, username, email, password, lang, status, (err, userData) => {
  568. if (err) {
  569. return reject(err);
  570. }
  571. return resolve(userData);
  572. });
  573. });
  574. };
  575. userSchema.statics.isExistUserByUserPagePath = async function(path) {
  576. const username = pagePathUtils.getUsernameByPath(path);
  577. if (username == null) {
  578. return false;
  579. }
  580. const user = await this.exists({ username });
  581. return user != null;
  582. };
  583. userSchema.statics.updateIsInvitationEmailSended = async function(id) {
  584. const user = await this.findById(id);
  585. if (user == null) {
  586. throw new Error('User not found');
  587. }
  588. if (user.status !== 5) {
  589. throw new Error('The status of the user is not "invited"');
  590. }
  591. user.isInvitationEmailSended = true;
  592. user.save();
  593. };
  594. userSchema.statics.findUserBySlackMemberId = async function(slackMemberId) {
  595. const user = this.findOne({ slackMemberId });
  596. if (user == null) {
  597. throw new Error('User not found');
  598. }
  599. return user;
  600. };
  601. userSchema.statics.findUsersBySlackMemberIds = async function(slackMemberIds) {
  602. const users = this.find({ slackMemberId: { $in: slackMemberIds } });
  603. if (users.length === 0) {
  604. throw new Error('No user found');
  605. }
  606. return users;
  607. };
  608. userSchema.statics.findUserByUsernameRegexWithTotalCount = async function(username, status, option) {
  609. const opt = option || {};
  610. const sortOpt = opt.sortOpt || { username: 1 };
  611. const offset = opt.offset || 0;
  612. const limit = opt.limit || 10;
  613. const conditions = { username: { $regex: username, $options: 'i' }, status: { $in: status } };
  614. const users = await this.find(conditions)
  615. .sort(sortOpt)
  616. .skip(offset)
  617. .limit(limit);
  618. const totalCount = (await this.find(conditions).distinct('username')).length;
  619. return { users, totalCount };
  620. };
  621. userSchema.methods.updateIsQuestionnaireEnabled = async function(value) {
  622. this.isQuestionnaireEnabled = value;
  623. return this.save();
  624. };
  625. class UserUpperLimitException {
  626. constructor() {
  627. this.name = this.constructor.name;
  628. }
  629. }
  630. userSchema.statics.STATUS_REGISTERED = STATUS_REGISTERED;
  631. userSchema.statics.STATUS_ACTIVE = STATUS_ACTIVE;
  632. userSchema.statics.STATUS_SUSPENDED = STATUS_SUSPENDED;
  633. userSchema.statics.STATUS_DELETED = STATUS_DELETED;
  634. userSchema.statics.STATUS_INVITED = STATUS_INVITED;
  635. userSchema.statics.USER_FIELDS_EXCEPT_CONFIDENTIAL = USER_FIELDS_EXCEPT_CONFIDENTIAL;
  636. userSchema.statics.PAGE_ITEMS = PAGE_ITEMS;
  637. return mongoose.model('User', userSchema);
  638. };