2
0

user.js 21 KB

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