user.js 22 KB

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