user.js 24 KB

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