user.js 24 KB

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