user.js 23 KB

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