user.js 23 KB

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