user.js 24 KB

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