user.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829
  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 uniqueValidator = require('mongoose-unique-validator');
  6. const mongoosePaginate = require('mongoose-paginate');
  7. const ObjectId = mongoose.Schema.Types.ObjectId;
  8. const crypto = require('crypto');
  9. module.exports = function(crowi) {
  10. const STATUS_REGISTERED = 1;
  11. const STATUS_ACTIVE = 2;
  12. const STATUS_SUSPENDED = 3;
  13. const STATUS_DELETED = 4;
  14. const STATUS_INVITED = 5;
  15. const USER_PUBLIC_FIELDS = '_id image isEmailPublished isGravatarEnabled googleId name username email introduction status lang createdAt lastLoginAt admin';
  16. const IMAGE_POPULATION = { path: 'imageAttachment', select: 'filePathProxied' };
  17. const LANG_EN = 'en';
  18. const LANG_EN_US = 'en-US';
  19. const LANG_EN_GB = 'en-GB';
  20. const LANG_JA = 'ja';
  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. isGravatarEnabled: { type: Boolean, default: false },
  33. isEmailPublished: { type: Boolean, default: true },
  34. googleId: String,
  35. name: { type: String },
  36. username: { type: String, required: true, unique: true },
  37. email: { type: String, unique: true, sparse: true },
  38. // === The official settings
  39. // username: { type: String, index: true },
  40. // email: { type: String, required: true, index: true },
  41. // === crowi-plus (>= 2.1.0, <2.3.0) settings
  42. // email: { type: String, required: true, unique: true },
  43. introduction: { type: String },
  44. password: String,
  45. apiToken: String,
  46. lang: {
  47. type: String,
  48. // eslint-disable-next-line no-eval
  49. enum: Object.keys(getLanguageLabels()).map((k) => { return eval(k) }),
  50. default: LANG_EN_US,
  51. },
  52. status: {
  53. type: Number, required: true, default: STATUS_ACTIVE, index: true,
  54. },
  55. createdAt: { type: Date, default: Date.now },
  56. lastLoginAt: { type: Date },
  57. admin: { type: Boolean, default: 0, index: true },
  58. }, {
  59. toObject: {
  60. transform: (doc, ret, opt) => {
  61. // omit password
  62. delete ret.password;
  63. // omit email
  64. if (!doc.isEmailPublished) {
  65. delete ret.email;
  66. }
  67. return ret;
  68. },
  69. },
  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. function getLanguageLabels() {
  123. const lang = {};
  124. lang.LANG_EN = LANG_EN;
  125. lang.LANG_EN_US = LANG_EN_US;
  126. lang.LANG_EN_GB = LANG_EN_GB;
  127. lang.LANG_JA = LANG_JA;
  128. return lang;
  129. }
  130. userSchema.methods.populateImage = async function() {
  131. // eslint-disable-next-line no-return-await
  132. return await this.populate(IMAGE_POPULATION);
  133. };
  134. userSchema.methods.isPasswordSet = function() {
  135. if (this.password) {
  136. return true;
  137. }
  138. return false;
  139. };
  140. userSchema.methods.isPasswordValid = function(password) {
  141. return this.password === generatePassword(password);
  142. };
  143. userSchema.methods.setPassword = function(password) {
  144. this.password = generatePassword(password);
  145. return this;
  146. };
  147. userSchema.methods.isEmailSet = function() {
  148. if (this.email) {
  149. return true;
  150. }
  151. return false;
  152. };
  153. userSchema.methods.updateLastLoginAt = function(lastLoginAt, callback) {
  154. this.lastLoginAt = lastLoginAt;
  155. this.save((err, userData) => {
  156. return callback(err, userData);
  157. });
  158. };
  159. userSchema.methods.updateIsGravatarEnabled = function(isGravatarEnabled, callback) {
  160. this.isGravatarEnabled = isGravatarEnabled;
  161. this.save((err, userData) => {
  162. return callback(err, userData);
  163. });
  164. };
  165. userSchema.methods.updateIsEmailPublished = function(isEmailPublished, callback) {
  166. this.isEmailPublished = isEmailPublished;
  167. this.save((err, userData) => {
  168. return callback(err, userData);
  169. });
  170. };
  171. userSchema.methods.updatePassword = function(password, callback) {
  172. this.setPassword(password);
  173. this.save((err, userData) => {
  174. return callback(err, userData);
  175. });
  176. };
  177. userSchema.methods.canDeleteCompletely = function(creatorId) {
  178. const pageCompleteDeletionAuthority = crowi.configManager.getConfig('crowi', 'security:pageCompleteDeletionAuthority');
  179. if (this.admin) {
  180. return true;
  181. }
  182. if (pageCompleteDeletionAuthority === 'anyOne' || pageCompleteDeletionAuthority == null) {
  183. return true;
  184. }
  185. if (pageCompleteDeletionAuthority === 'adminAndAuthor') {
  186. return (this._id.equals(creatorId));
  187. }
  188. return false;
  189. };
  190. userSchema.methods.updateApiToken = function(callback) {
  191. const self = this;
  192. self.apiToken = generateApiToken(this);
  193. return new Promise(((resolve, reject) => {
  194. self.save((err, userData) => {
  195. if (err) {
  196. return reject(err);
  197. }
  198. return resolve(userData);
  199. });
  200. }));
  201. };
  202. userSchema.methods.updateImage = async function(attachment) {
  203. this.imageAttachment = attachment;
  204. return this.save();
  205. };
  206. userSchema.methods.deleteImage = async function() {
  207. validateCrowi();
  208. const Attachment = crowi.model('Attachment');
  209. // the 'image' field became DEPRECATED in v3.3.8
  210. this.image = undefined;
  211. if (this.imageAttachment != null) {
  212. Attachment.removeWithSubstanceById(this.imageAttachment._id);
  213. }
  214. this.imageAttachment = undefined;
  215. return this.save();
  216. };
  217. userSchema.methods.updateGoogleId = function(googleId, callback) {
  218. this.googleId = googleId;
  219. this.save((err, userData) => {
  220. return callback(err, userData);
  221. });
  222. };
  223. userSchema.methods.deleteGoogleId = function(callback) {
  224. return this.updateGoogleId(null, callback);
  225. };
  226. userSchema.methods.activateInvitedUser = async function(username, name, password) {
  227. this.setPassword(password);
  228. this.name = name;
  229. this.username = username;
  230. this.status = STATUS_ACTIVE;
  231. this.save((err, userData) => {
  232. userEvent.emit('activated', userData);
  233. if (err) {
  234. throw new Error(err);
  235. }
  236. return userData;
  237. });
  238. };
  239. userSchema.methods.removeFromAdmin = function(callback) {
  240. debug('Remove from admin', this);
  241. this.admin = 0;
  242. this.save((err, userData) => {
  243. return callback(err, userData);
  244. });
  245. };
  246. userSchema.methods.makeAdmin = function(callback) {
  247. debug('Admin', this);
  248. this.admin = 1;
  249. this.save((err, userData) => {
  250. return callback(err, userData);
  251. });
  252. };
  253. userSchema.methods.asyncMakeAdmin = async function(callback) {
  254. this.admin = 1;
  255. return this.save();
  256. };
  257. userSchema.methods.statusActivate = function(callback) {
  258. debug('Activate User', this);
  259. this.status = STATUS_ACTIVE;
  260. this.save((err, userData) => {
  261. userEvent.emit('activated', userData);
  262. return callback(err, userData);
  263. });
  264. };
  265. userSchema.methods.statusSuspend = function(callback) {
  266. debug('Suspend User', this);
  267. this.status = STATUS_SUSPENDED;
  268. if (this.email === undefined || this.email === null) { // migrate old data
  269. this.email = '-';
  270. }
  271. if (this.name === undefined || this.name === null) { // migrate old data
  272. this.name = `-${Date.now()}`;
  273. }
  274. if (this.username === undefined || this.usename === null) { // migrate old data
  275. this.username = '-';
  276. }
  277. this.save((err, userData) => {
  278. return callback(err, userData);
  279. });
  280. };
  281. userSchema.methods.statusDelete = function(callback) {
  282. debug('Delete User', this);
  283. const now = new Date();
  284. const deletedLabel = `deleted_at_${now.getTime()}`;
  285. this.status = STATUS_DELETED;
  286. this.username = deletedLabel;
  287. this.password = '';
  288. this.name = '';
  289. this.email = `${deletedLabel}@deleted`;
  290. this.googleId = null;
  291. this.isGravatarEnabled = false;
  292. this.image = null;
  293. this.save((err, userData) => {
  294. return callback(err, userData);
  295. });
  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.findUsersWithPagination = async function(options) {
  366. const defaultOptions = {
  367. sort: { status: 1, username: 1, createdAt: 1 },
  368. page: 1,
  369. limit: PAGE_ITEMS,
  370. };
  371. const mergedOptions = Object.assign(defaultOptions, options);
  372. return this.paginate({ status: { $ne: STATUS_DELETED } }, mergedOptions);
  373. };
  374. userSchema.statics.findUsersByPartOfEmail = function(emailPart, options) {
  375. const status = options.status || null;
  376. const emailPartRegExp = new RegExp(emailPart.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&'));
  377. const User = this;
  378. return new Promise((resolve, reject) => {
  379. const query = User.find({ email: emailPartRegExp }, USER_PUBLIC_FIELDS);
  380. if (status) {
  381. query.and({ status });
  382. }
  383. query
  384. .limit(PAGE_ITEMS + 1)
  385. .exec((err, userData) => {
  386. if (err) {
  387. return reject(err);
  388. }
  389. return resolve(userData);
  390. });
  391. });
  392. };
  393. userSchema.statics.findUserByUsername = function(username) {
  394. if (username == null) {
  395. return Promise.resolve(null);
  396. }
  397. return this.findOne({ username });
  398. };
  399. userSchema.statics.findUserByApiToken = function(apiToken) {
  400. if (apiToken == null) {
  401. return Promise.resolve(null);
  402. }
  403. return this.findOne({ apiToken });
  404. };
  405. userSchema.statics.findUserByGoogleId = function(googleId, callback) {
  406. if (googleId == null) {
  407. callback(null, null);
  408. }
  409. this.findOne({ googleId }, (err, userData) => {
  410. callback(err, userData);
  411. });
  412. };
  413. userSchema.statics.findUserByUsernameOrEmail = function(usernameOrEmail, password, callback) {
  414. this.findOne()
  415. .or([
  416. { username: usernameOrEmail },
  417. { email: usernameOrEmail },
  418. ])
  419. .exec((err, userData) => {
  420. callback(err, userData);
  421. });
  422. };
  423. userSchema.statics.findUserByEmailAndPassword = function(email, password, callback) {
  424. const hashedPassword = generatePassword(password);
  425. this.findOne({ email, password: hashedPassword }, (err, userData) => {
  426. callback(err, userData);
  427. });
  428. };
  429. userSchema.statics.isUserCountExceedsUpperLimit = async function() {
  430. const { aclService } = crowi;
  431. const userUpperLimit = aclService.userUpperLimit();
  432. if (userUpperLimit === 0) {
  433. return false;
  434. }
  435. const activeUsers = await this.countListByStatus(STATUS_ACTIVE);
  436. if (userUpperLimit !== 0 && userUpperLimit <= activeUsers) {
  437. return true;
  438. }
  439. return false;
  440. };
  441. userSchema.statics.countListByStatus = async function(status) {
  442. const User = this;
  443. const conditions = { status };
  444. // TODO count は非推奨。mongoose のバージョンアップ後に countDocuments に変更する。
  445. return User.count(conditions);
  446. };
  447. userSchema.statics.isRegisterableUsername = async function(username) {
  448. let usernameUsable = true;
  449. const userData = await this.findOne({ username });
  450. if (userData) {
  451. usernameUsable = false;
  452. }
  453. return usernameUsable;
  454. };
  455. userSchema.statics.isRegisterable = function(email, username, callback) {
  456. const User = this;
  457. let emailUsable = true;
  458. let usernameUsable = true;
  459. // username check
  460. this.findOne({ username }, (err, userData) => {
  461. if (userData) {
  462. usernameUsable = false;
  463. }
  464. // email check
  465. User.findOne({ email }, (err, userData) => {
  466. if (userData) {
  467. emailUsable = false;
  468. }
  469. if (!emailUsable || !usernameUsable) {
  470. return callback(false, { email: emailUsable, username: usernameUsable });
  471. }
  472. return callback(true, {});
  473. });
  474. });
  475. };
  476. userSchema.statics.removeCompletelyById = function(id, callback) {
  477. const User = this;
  478. User.findById(id, (err, userData) => {
  479. if (!userData) {
  480. return callback(err, null);
  481. }
  482. debug('Removing user:', userData);
  483. // 物理削除可能なのは、承認待ちユーザー、招待中ユーザーのみ
  484. // 利用を一度開始したユーザーは論理削除のみ可能
  485. if (userData.status !== STATUS_REGISTERED && userData.status !== STATUS_INVITED) {
  486. return callback(new Error('Cannot remove completely the user whoes status is not INVITED'), null);
  487. }
  488. userData.remove((err) => {
  489. if (err) {
  490. return callback(err, null);
  491. }
  492. return callback(null, 1);
  493. });
  494. });
  495. };
  496. userSchema.statics.resetPasswordByRandomString = async function(id) {
  497. const user = await this.findById(id);
  498. if (!user) {
  499. throw new Error('User not found');
  500. }
  501. const newPassword = generateRandomTempPassword();
  502. user.setPassword(newPassword);
  503. await user.save();
  504. return newPassword;
  505. };
  506. userSchema.statics.createUsersByInvitation = async function(emailList, toSendEmail) {
  507. validateCrowi();
  508. const configManager = crowi.configManager;
  509. const User = this;
  510. const createdUserList = [];
  511. // TODO GW-206 move to anothor function
  512. // const mailer = crowi.getMailer();
  513. if (!Array.isArray(emailList)) {
  514. debug('emailList is not array');
  515. }
  516. const createUser = async(email) => {
  517. const newUser = new User();
  518. // eslint-disable-next-line no-param-reassign
  519. email = email.trim();
  520. // email check
  521. const userData = await User.findOne({ email, userStatus: !STATUS_DELETED });
  522. // The user is exists
  523. if (userData != null) {
  524. return createdUserList.push({
  525. email,
  526. password: null,
  527. user: null,
  528. });
  529. }
  530. /* eslint-disable newline-per-chained-call */
  531. const tmpUsername = `temp_${Math.random().toString(36).slice(-16)}`;
  532. const password = Math.random().toString(36).slice(-16);
  533. /* eslint-enable newline-per-chained-call */
  534. newUser.username = tmpUsername;
  535. newUser.email = email;
  536. newUser.setPassword(password);
  537. newUser.createdAt = Date.now();
  538. newUser.status = STATUS_INVITED;
  539. const globalLang = configManager.getConfig('crowi', 'app:globalLang');
  540. if (globalLang != null) {
  541. newUser.lang = globalLang;
  542. }
  543. try {
  544. const newUserData = await newUser.save();
  545. return createdUserList.push({
  546. email,
  547. password,
  548. user: newUserData,
  549. });
  550. }
  551. catch (err) {
  552. return createdUserList.push({
  553. email,
  554. password: null,
  555. user: null,
  556. });
  557. }
  558. };
  559. await Promise.all(emailList.map((email) => { return createUser(email) }));
  560. };
  561. // TODO GW-206 Independence as function
  562. // if (toSendEmail) {
  563. // // TODO: メール送信部分のロジックをサービス化する
  564. // async.each(
  565. // createdUserList,
  566. // (user, next) => {
  567. // if (user.password === null) {
  568. // return next();
  569. // }
  570. // const appTitle = crowi.appService.getAppTitle();
  571. // mailer.send({
  572. // to: user.email,
  573. // subject: `Invitation to ${appTitle}`,
  574. // template: path.join(crowi.localeDir, 'en-US/admin/userInvitation.txt'),
  575. // vars: {
  576. // email: user.email,
  577. // password: user.password,
  578. // url: crowi.appService.getSiteUrl(),
  579. // appTitle,
  580. // },
  581. // },
  582. // (err, s) => {
  583. // debug('completed to send email: ', err, s);
  584. // next();
  585. // });
  586. // },
  587. // (err) => {
  588. // debug('Sending invitation email completed.', err);
  589. // },
  590. // );
  591. // }
  592. // debug('createdUserList!!! ', createdUserList);
  593. // },
  594. // );
  595. userSchema.statics.createUserByEmailAndPasswordAndStatus = async function(name, username, email, password, lang, status, callback) {
  596. const User = this;
  597. const newUser = new User();
  598. // check user upper limit
  599. const isUserCountExceedsUpperLimit = await User.isUserCountExceedsUpperLimit();
  600. if (isUserCountExceedsUpperLimit) {
  601. const err = new UserUpperLimitException();
  602. return callback(err);
  603. }
  604. // check email duplication because email must be unique
  605. const count = await this.count({ email });
  606. if (count > 0) {
  607. // eslint-disable-next-line no-param-reassign
  608. email = generateRandomEmail();
  609. }
  610. newUser.name = name;
  611. newUser.username = username;
  612. newUser.email = email;
  613. if (password != null) {
  614. newUser.setPassword(password);
  615. }
  616. const configManager = crowi.configManager;
  617. const globalLang = configManager.getConfig('crowi', 'app:globalLang');
  618. if (globalLang != null) {
  619. newUser.lang = globalLang;
  620. }
  621. if (lang != null) {
  622. newUser.lang = lang;
  623. }
  624. newUser.createdAt = Date.now();
  625. newUser.status = status || decideUserStatusOnRegistration();
  626. newUser.save((err, userData) => {
  627. if (err) {
  628. logger.error('createUserByEmailAndPasswordAndStatus failed: ', err);
  629. return callback(err);
  630. }
  631. if (userData.status === STATUS_ACTIVE) {
  632. userEvent.emit('activated', userData);
  633. }
  634. return callback(err, userData);
  635. });
  636. };
  637. /**
  638. * A wrapper function of createUserByEmailAndPasswordAndStatus with callback
  639. *
  640. */
  641. userSchema.statics.createUserByEmailAndPassword = function(name, username, email, password, lang, callback) {
  642. this.createUserByEmailAndPasswordAndStatus(name, username, email, password, lang, undefined, callback);
  643. };
  644. /**
  645. * A wrapper function of createUserByEmailAndPasswordAndStatus
  646. *
  647. * @return {Promise<User>}
  648. */
  649. userSchema.statics.createUser = function(name, username, email, password, lang, status) {
  650. const User = this;
  651. return new Promise((resolve, reject) => {
  652. User.createUserByEmailAndPasswordAndStatus(name, username, email, password, lang, status, (err, userData) => {
  653. if (err) {
  654. return reject(err);
  655. }
  656. return resolve(userData);
  657. });
  658. });
  659. };
  660. userSchema.statics.getUsernameByPath = function(path) {
  661. let username = null;
  662. const match = path.match(/^\/user\/([^/]+)\/?/);
  663. if (match) {
  664. username = match[1];
  665. }
  666. return username;
  667. };
  668. class UserUpperLimitException {
  669. constructor() {
  670. this.name = this.constructor.name;
  671. }
  672. }
  673. userSchema.statics.STATUS_REGISTERED = STATUS_REGISTERED;
  674. userSchema.statics.STATUS_ACTIVE = STATUS_ACTIVE;
  675. userSchema.statics.STATUS_SUSPENDED = STATUS_SUSPENDED;
  676. userSchema.statics.STATUS_DELETED = STATUS_DELETED;
  677. userSchema.statics.STATUS_INVITED = STATUS_INVITED;
  678. userSchema.statics.USER_PUBLIC_FIELDS = USER_PUBLIC_FIELDS;
  679. userSchema.statics.IMAGE_POPULATION = IMAGE_POPULATION;
  680. userSchema.statics.PAGE_ITEMS = PAGE_ITEMS;
  681. userSchema.statics.LANG_EN = LANG_EN;
  682. userSchema.statics.LANG_EN_US = LANG_EN_US;
  683. userSchema.statics.LANG_EN_GB = LANG_EN_US;
  684. userSchema.statics.LANG_JA = LANG_JA;
  685. return mongoose.model('User', userSchema);
  686. };