user.js 22 KB

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