user.js 22 KB

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