user.js 23 KB

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