user.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  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. await this.updateImageUrlCached();
  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. await this.updateImageUrlCached();
  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.updateImageUrlCached();
  205. return this.save();
  206. };
  207. userSchema.methods.updateImageUrlCached = async function() {
  208. this.imageUrlCached = await this.generateImageUrlCached();
  209. };
  210. userSchema.methods.generateImageUrlCached = async function() {
  211. if (this.isGravatarEnabled) {
  212. const email = this.email || '';
  213. const hash = md5(email.trim().toLowerCase());
  214. return `https://gravatar.com/avatar/${hash}`;
  215. }
  216. if (this.image != null) {
  217. return this.image;
  218. }
  219. if (this.imageAttachment != null && this.imageAttachment._id != null) {
  220. const Attachment = crowi.model('Attachment');
  221. const imageAttachment = await Attachment.findById(this.imageAttachment);
  222. return imageAttachment.filePathProxied;
  223. }
  224. return '/images/icons/user.svg';
  225. };
  226. userSchema.methods.updateGoogleId = function(googleId, callback) {
  227. this.googleId = googleId;
  228. this.save((err, userData) => {
  229. return callback(err, userData);
  230. });
  231. };
  232. userSchema.methods.deleteGoogleId = function(callback) {
  233. return this.updateGoogleId(null, callback);
  234. };
  235. userSchema.methods.activateInvitedUser = async function(username, name, password) {
  236. this.setPassword(password);
  237. this.name = name;
  238. this.username = username;
  239. this.status = STATUS_ACTIVE;
  240. this.save((err, userData) => {
  241. userEvent.emit('activated', userData);
  242. if (err) {
  243. throw new Error(err);
  244. }
  245. return userData;
  246. });
  247. };
  248. userSchema.methods.removeFromAdmin = async function() {
  249. debug('Remove from admin', this);
  250. this.admin = 0;
  251. return this.save();
  252. };
  253. userSchema.methods.makeAdmin = async function() {
  254. debug('Admin', this);
  255. this.admin = 1;
  256. return this.save();
  257. };
  258. userSchema.methods.asyncMakeAdmin = async function(callback) {
  259. this.admin = 1;
  260. return this.save();
  261. };
  262. userSchema.methods.statusActivate = async function() {
  263. debug('Activate User', this);
  264. this.status = STATUS_ACTIVE;
  265. const userData = await this.save();
  266. return userEvent.emit('activated', userData);
  267. };
  268. userSchema.methods.statusSuspend = async function() {
  269. debug('Suspend User', this);
  270. this.status = STATUS_SUSPENDED;
  271. if (this.email === undefined || this.email === null) { // migrate old data
  272. this.email = '-';
  273. }
  274. if (this.name === undefined || this.name === null) { // migrate old data
  275. this.name = `-${Date.now()}`;
  276. }
  277. if (this.username === undefined || this.usename === null) { // migrate old data
  278. this.username = '-';
  279. }
  280. return this.save();
  281. };
  282. userSchema.methods.statusDelete = async function() {
  283. debug('Delete User', this);
  284. const now = new Date();
  285. const deletedLabel = `deleted_at_${now.getTime()}`;
  286. this.status = STATUS_DELETED;
  287. this.username = deletedLabel;
  288. this.password = '';
  289. this.name = '';
  290. this.email = `${deletedLabel}@deleted`;
  291. this.googleId = null;
  292. this.isGravatarEnabled = false;
  293. this.image = null;
  294. return this.save();
  295. };
  296. userSchema.methods.updateGoogleId = function(googleId, callback) {
  297. this.googleId = googleId;
  298. this.save((err, userData) => {
  299. return callback(err, userData);
  300. });
  301. };
  302. userSchema.statics.getLanguageLabels = getLanguageLabels;
  303. userSchema.statics.getUserStatusLabels = function() {
  304. const userStatus = {};
  305. userStatus[STATUS_REGISTERED] = 'Approval Pending';
  306. userStatus[STATUS_ACTIVE] = 'Active';
  307. userStatus[STATUS_SUSPENDED] = 'Suspended';
  308. userStatus[STATUS_DELETED] = 'Deleted';
  309. userStatus[STATUS_INVITED] = 'Invited';
  310. return userStatus;
  311. };
  312. userSchema.statics.isEmailValid = function(email, callback) {
  313. validateCrowi();
  314. const whitelist = crowi.configManager.getConfig('crowi', 'security:registrationWhiteList');
  315. if (Array.isArray(whitelist) && whitelist.length > 0) {
  316. return whitelist.some((allowedEmail) => {
  317. const re = new RegExp(`${allowedEmail}$`);
  318. return re.test(email);
  319. });
  320. }
  321. return true;
  322. };
  323. userSchema.statics.findUsers = function(options, callback) {
  324. const sort = options.sort || { status: 1, createdAt: 1 };
  325. this.find()
  326. .sort(sort)
  327. .skip(options.skip || 0)
  328. .limit(options.limit || 21)
  329. .exec((err, userData) => {
  330. callback(err, userData);
  331. });
  332. };
  333. userSchema.statics.findAllUsers = function(option) {
  334. // eslint-disable-next-line no-param-reassign
  335. option = option || {};
  336. const sort = option.sort || { createdAt: -1 };
  337. const fields = option.fields || USER_PUBLIC_FIELDS;
  338. let status = option.status || [STATUS_ACTIVE, STATUS_SUSPENDED];
  339. if (!Array.isArray(status)) {
  340. status = [status];
  341. }
  342. return this.find()
  343. .or(status.map((s) => { return { status: s } }))
  344. .select(fields)
  345. .sort(sort);
  346. };
  347. userSchema.statics.findUsersByIds = function(ids, option) {
  348. // eslint-disable-next-line no-param-reassign
  349. option = option || {};
  350. const sort = option.sort || { createdAt: -1 };
  351. const status = option.status || STATUS_ACTIVE;
  352. const fields = option.fields || USER_PUBLIC_FIELDS;
  353. return this.find({ _id: { $in: ids }, status })
  354. .select(fields)
  355. .sort(sort);
  356. };
  357. userSchema.statics.findAdmins = function(callback) {
  358. this.find({ admin: true })
  359. .exec((err, admins) => {
  360. debug('Admins: ', admins);
  361. callback(err, admins);
  362. });
  363. };
  364. userSchema.statics.findUsersByPartOfEmail = function(emailPart, options) {
  365. const status = options.status || null;
  366. const emailPartRegExp = new RegExp(emailPart.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&'));
  367. const User = this;
  368. return new Promise((resolve, reject) => {
  369. const query = User.find({ email: emailPartRegExp }, USER_PUBLIC_FIELDS);
  370. if (status) {
  371. query.and({ status });
  372. }
  373. query
  374. .limit(PAGE_ITEMS + 1)
  375. .exec((err, userData) => {
  376. if (err) {
  377. return reject(err);
  378. }
  379. return resolve(userData);
  380. });
  381. });
  382. };
  383. userSchema.statics.findUserByUsername = function(username) {
  384. if (username == null) {
  385. return Promise.resolve(null);
  386. }
  387. return this.findOne({ username });
  388. };
  389. userSchema.statics.findUserByApiToken = function(apiToken) {
  390. if (apiToken == null) {
  391. return Promise.resolve(null);
  392. }
  393. return this.findOne({ apiToken });
  394. };
  395. userSchema.statics.findUserByGoogleId = function(googleId, callback) {
  396. if (googleId == null) {
  397. callback(null, null);
  398. }
  399. this.findOne({ googleId }, (err, userData) => {
  400. callback(err, userData);
  401. });
  402. };
  403. userSchema.statics.findUserByUsernameOrEmail = function(usernameOrEmail, password, callback) {
  404. this.findOne()
  405. .or([
  406. { username: usernameOrEmail },
  407. { email: usernameOrEmail },
  408. ])
  409. .exec((err, userData) => {
  410. callback(err, userData);
  411. });
  412. };
  413. userSchema.statics.findUserByEmailAndPassword = function(email, password, callback) {
  414. const hashedPassword = generatePassword(password);
  415. this.findOne({ email, password: hashedPassword }, (err, userData) => {
  416. callback(err, userData);
  417. });
  418. };
  419. userSchema.statics.isUserCountExceedsUpperLimit = async function() {
  420. const { configManager } = crowi;
  421. const userUpperLimit = configManager.getConfig('crowi', 'security:userUpperLimit');
  422. const activeUsers = await this.countListByStatus(STATUS_ACTIVE);
  423. if (userUpperLimit <= activeUsers) {
  424. return true;
  425. }
  426. return false;
  427. };
  428. userSchema.statics.countListByStatus = async function(status) {
  429. const User = this;
  430. const conditions = { status };
  431. // TODO count は非推奨。mongoose のバージョンアップ後に countDocuments に変更する。
  432. return User.count(conditions);
  433. };
  434. userSchema.statics.isRegisterableUsername = async function(username) {
  435. let usernameUsable = true;
  436. const userData = await this.findOne({ username });
  437. if (userData) {
  438. usernameUsable = false;
  439. }
  440. return usernameUsable;
  441. };
  442. userSchema.statics.isRegisterable = function(email, username, callback) {
  443. const User = this;
  444. let emailUsable = true;
  445. let usernameUsable = true;
  446. // username check
  447. this.findOne({ username }, (err, userData) => {
  448. if (userData) {
  449. usernameUsable = false;
  450. }
  451. // email check
  452. User.findOne({ email }, (err, userData) => {
  453. if (userData) {
  454. emailUsable = false;
  455. }
  456. if (!emailUsable || !usernameUsable) {
  457. return callback(false, { email: emailUsable, username: usernameUsable });
  458. }
  459. return callback(true, {});
  460. });
  461. });
  462. };
  463. userSchema.statics.removeCompletelyById = function(id, callback) {
  464. const User = this;
  465. User.findById(id, (err, userData) => {
  466. if (!userData) {
  467. return callback(err, null);
  468. }
  469. debug('Removing user:', userData);
  470. // 物理削除可能なのは、承認待ちユーザー、招待中ユーザーのみ
  471. // 利用を一度開始したユーザーは論理削除のみ可能
  472. if (userData.status !== STATUS_REGISTERED && userData.status !== STATUS_INVITED) {
  473. return callback(new Error('Cannot remove completely the user whoes status is not INVITED'), null);
  474. }
  475. userData.remove((err) => {
  476. if (err) {
  477. return callback(err, null);
  478. }
  479. return callback(null, 1);
  480. });
  481. });
  482. };
  483. userSchema.statics.resetPasswordByRandomString = async function(id) {
  484. const user = await this.findById(id);
  485. if (!user) {
  486. throw new Error('User not found');
  487. }
  488. const newPassword = generateRandomTempPassword();
  489. user.setPassword(newPassword);
  490. await user.save();
  491. return newPassword;
  492. };
  493. userSchema.statics.createUserByEmail = async function(email) {
  494. const configManager = crowi.configManager;
  495. const User = this;
  496. const newUser = new User();
  497. /* eslint-disable newline-per-chained-call */
  498. const tmpUsername = `temp_${Math.random().toString(36).slice(-16)}`;
  499. const password = Math.random().toString(36).slice(-16);
  500. /* eslint-enable newline-per-chained-call */
  501. newUser.username = tmpUsername;
  502. newUser.email = email;
  503. newUser.setPassword(password);
  504. newUser.createdAt = Date.now();
  505. newUser.status = STATUS_INVITED;
  506. const globalLang = configManager.getConfig('crowi', 'app:globalLang');
  507. if (globalLang != null) {
  508. newUser.lang = globalLang;
  509. }
  510. try {
  511. const newUserData = await newUser.save();
  512. return {
  513. email,
  514. password,
  515. user: newUserData,
  516. };
  517. }
  518. catch (err) {
  519. return {
  520. email,
  521. };
  522. }
  523. };
  524. userSchema.statics.createUsersByEmailList = async function(emailList) {
  525. const User = this;
  526. // check exists and get list of try to create
  527. const existingUserList = await User.find({ email: { $in: emailList }, userStatus: { $ne: STATUS_DELETED } });
  528. const existingEmailList = existingUserList.map((user) => { return user.email });
  529. const creationEmailList = emailList.filter((email) => { return existingEmailList.indexOf(email) === -1 });
  530. const createdUserList = [];
  531. await Promise.all(creationEmailList.map(async(email) => {
  532. const createdEmail = await this.createUserByEmail(email);
  533. createdUserList.push(createdEmail);
  534. }));
  535. return { existingEmailList, createdUserList };
  536. };
  537. userSchema.statics.sendEmailbyUserList = async function(userList) {
  538. const mailer = crowi.getMailer();
  539. const appTitle = crowi.appService.getAppTitle();
  540. await Promise.all(userList.map(async(user) => {
  541. if (user.password == null) {
  542. return;
  543. }
  544. try {
  545. return mailer.send({
  546. to: user.email,
  547. subject: `Invitation to ${appTitle}`,
  548. template: path.join(crowi.localeDir, 'en-US/admin/userInvitation.txt'),
  549. vars: {
  550. email: user.email,
  551. password: user.password,
  552. url: crowi.appService.getSiteUrl(),
  553. appTitle,
  554. },
  555. });
  556. }
  557. catch (err) {
  558. return debug('fail to send email: ', err);
  559. }
  560. }));
  561. };
  562. userSchema.statics.createUsersByInvitation = async function(emailList, toSendEmail) {
  563. validateCrowi();
  564. if (!Array.isArray(emailList)) {
  565. debug('emailList is not array');
  566. }
  567. const afterWorkEmailList = await this.createUsersByEmailList(emailList);
  568. if (toSendEmail) {
  569. await this.sendEmailbyUserList(afterWorkEmailList.createdUserList);
  570. }
  571. return afterWorkEmailList;
  572. };
  573. userSchema.statics.createUserByEmailAndPasswordAndStatus = async function(name, username, email, password, lang, status, callback) {
  574. const User = this;
  575. const newUser = new User();
  576. // check user upper limit
  577. const isUserCountExceedsUpperLimit = await User.isUserCountExceedsUpperLimit();
  578. if (isUserCountExceedsUpperLimit) {
  579. const err = new UserUpperLimitException();
  580. return callback(err);
  581. }
  582. // check email duplication because email must be unique
  583. const count = await this.count({ email });
  584. if (count > 0) {
  585. // eslint-disable-next-line no-param-reassign
  586. email = generateRandomEmail();
  587. }
  588. newUser.name = name;
  589. newUser.username = username;
  590. newUser.email = email;
  591. if (password != null) {
  592. newUser.setPassword(password);
  593. }
  594. const configManager = crowi.configManager;
  595. const globalLang = configManager.getConfig('crowi', 'app:globalLang');
  596. if (globalLang != null) {
  597. newUser.lang = globalLang;
  598. }
  599. if (lang != null) {
  600. newUser.lang = lang;
  601. }
  602. newUser.createdAt = Date.now();
  603. newUser.status = status || decideUserStatusOnRegistration();
  604. newUser.save((err, userData) => {
  605. if (err) {
  606. logger.error('createUserByEmailAndPasswordAndStatus failed: ', err);
  607. return callback(err);
  608. }
  609. if (userData.status === STATUS_ACTIVE) {
  610. userEvent.emit('activated', userData);
  611. }
  612. return callback(err, userData);
  613. });
  614. };
  615. /**
  616. * A wrapper function of createUserByEmailAndPasswordAndStatus with callback
  617. *
  618. */
  619. userSchema.statics.createUserByEmailAndPassword = function(name, username, email, password, lang, callback) {
  620. this.createUserByEmailAndPasswordAndStatus(name, username, email, password, lang, undefined, callback);
  621. };
  622. /**
  623. * A wrapper function of createUserByEmailAndPasswordAndStatus
  624. *
  625. * @return {Promise<User>}
  626. */
  627. userSchema.statics.createUser = function(name, username, email, password, lang, status) {
  628. const User = this;
  629. return new Promise((resolve, reject) => {
  630. User.createUserByEmailAndPasswordAndStatus(name, username, email, password, lang, status, (err, userData) => {
  631. if (err) {
  632. return reject(err);
  633. }
  634. return resolve(userData);
  635. });
  636. });
  637. };
  638. userSchema.statics.getUsernameByPath = function(path) {
  639. let username = null;
  640. const match = path.match(/^\/user\/([^/]+)\/?/);
  641. if (match) {
  642. username = match[1];
  643. }
  644. return username;
  645. };
  646. class UserUpperLimitException {
  647. constructor() {
  648. this.name = this.constructor.name;
  649. }
  650. }
  651. userSchema.statics.STATUS_REGISTERED = STATUS_REGISTERED;
  652. userSchema.statics.STATUS_ACTIVE = STATUS_ACTIVE;
  653. userSchema.statics.STATUS_SUSPENDED = STATUS_SUSPENDED;
  654. userSchema.statics.STATUS_DELETED = STATUS_DELETED;
  655. userSchema.statics.STATUS_INVITED = STATUS_INVITED;
  656. userSchema.statics.USER_PUBLIC_FIELDS = USER_PUBLIC_FIELDS;
  657. userSchema.statics.IMAGE_POPULATION = IMAGE_POPULATION;
  658. userSchema.statics.PAGE_ITEMS = PAGE_ITEMS;
  659. userSchema.statics.LANG_EN = LANG_EN;
  660. userSchema.statics.LANG_EN_US = LANG_EN_US;
  661. userSchema.statics.LANG_EN_GB = LANG_EN_US;
  662. userSchema.statics.LANG_JA = LANG_JA;
  663. return mongoose.model('User', userSchema);
  664. };