2
0

user.js 22 KB

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