user.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843
  1. module.exports = function(crowi) {
  2. const debug = require('debug')('growi:models:user')
  3. , logger = require('@alias/logger')('growi:models:user')
  4. , path = require('path')
  5. , mongoose = require('mongoose')
  6. , mongoosePaginate = require('mongoose-paginate')
  7. , uniqueValidator = require('mongoose-unique-validator')
  8. , crypto = require('crypto')
  9. , async = require('async')
  10. , STATUS_REGISTERED = 1
  11. , STATUS_ACTIVE = 2
  12. , STATUS_SUSPENDED = 3
  13. , STATUS_DELETED = 4
  14. , STATUS_INVITED = 5
  15. , USER_PUBLIC_FIELDS = '_id image isEmailPublished isGravatarEnabled googleId name username email introduction status lang createdAt admin' // TODO: どこか別の場所へ...
  16. , LANG_EN = 'en'
  17. , LANG_EN_US = 'en-US'
  18. , LANG_EN_GB = 'en-GB'
  19. , LANG_JA = 'ja'
  20. , PAGE_ITEMS = 50
  21. let userSchema;
  22. let userEvent;
  23. // init event
  24. if (crowi != null) {
  25. userEvent = crowi.event('user');
  26. userEvent.on('activated', userEvent.onActivated);
  27. }
  28. userSchema = new mongoose.Schema({
  29. userId: String,
  30. image: String,
  31. isGravatarEnabled: { type: Boolean, default: false },
  32. isEmailPublished: { type: Boolean, default: true },
  33. googleId: String,
  34. name: { type: String },
  35. username: { type: String, required: true, unique: true },
  36. email: { type: String, unique: true, sparse: true },
  37. //// The official settings
  38. // username: { type: String, index: true },
  39. // email: { type: String, required: true, index: true },
  40. //// crowi-plus (>= 2.1.0, <2.3.0) settings
  41. // email: { type: String, required: true, unique: true },
  42. introduction: { type: String },
  43. password: String,
  44. apiToken: String,
  45. lang: {
  46. type: String,
  47. enum: Object.keys(getLanguageLabels()).map((k) => eval(k)),
  48. default: LANG_EN_US
  49. },
  50. status: { type: Number, required: true, default: STATUS_ACTIVE, index: true },
  51. createdAt: { type: Date, default: Date.now },
  52. lastLoginAt: { type: Date },
  53. admin: { type: Boolean, default: 0, index: true }
  54. });
  55. userSchema.plugin(mongoosePaginate);
  56. userSchema.plugin(uniqueValidator);
  57. function validateCrowi() {
  58. if (crowi == null) {
  59. throw new Error('"crowi" is null. Init User model with "crowi" argument first.');
  60. }
  61. }
  62. function decideUserStatusOnRegistration() {
  63. validateCrowi();
  64. var Config = crowi.model('Config'),
  65. config = crowi.getConfig();
  66. if (!config.crowi) {
  67. return STATUS_ACTIVE; // is this ok?
  68. }
  69. // status decided depends on registrationMode
  70. switch (config.crowi['security:registrationMode']) {
  71. case Config.SECURITY_REGISTRATION_MODE_OPEN:
  72. return STATUS_ACTIVE;
  73. case Config.SECURITY_REGISTRATION_MODE_RESTRICTED:
  74. case Config.SECURITY_REGISTRATION_MODE_CLOSED: // 一応
  75. return STATUS_REGISTERED;
  76. default:
  77. return STATUS_ACTIVE; // どっちにすんのがいいんだろうな
  78. }
  79. }
  80. function generateRandomEmail() {
  81. const randomstr = generateRandomTempPassword();
  82. return `change-it-${randomstr}@example.com`;
  83. }
  84. function generateRandomTempPassword() {
  85. var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!=-_';
  86. var password = '';
  87. var len = 12;
  88. for (var i = 0; i < len; i++) {
  89. var randomPoz = Math.floor(Math.random() * chars.length);
  90. password += chars.substring(randomPoz, randomPoz+1);
  91. }
  92. return password;
  93. }
  94. function generatePassword(password) {
  95. validateCrowi();
  96. var hasher = crypto.createHash('sha256');
  97. hasher.update(crowi.env.PASSWORD_SEED + password);
  98. return hasher.digest('hex');
  99. }
  100. function generateApiToken(user) {
  101. var hasher = crypto.createHash('sha256');
  102. hasher.update((new Date).getTime() + user._id);
  103. return hasher.digest('base64');
  104. }
  105. function getLanguageLabels() {
  106. var lang = {};
  107. lang.LANG_EN = LANG_EN;
  108. lang.LANG_EN_US = LANG_EN_US;
  109. lang.LANG_EN_GB = LANG_EN_GB;
  110. lang.LANG_JA = LANG_JA;
  111. return lang;
  112. }
  113. userSchema.methods.isPasswordSet = function() {
  114. if (this.password) {
  115. return true;
  116. }
  117. return false;
  118. };
  119. userSchema.methods.isPasswordValid = function(password) {
  120. return this.password == generatePassword(password);
  121. };
  122. userSchema.methods.setPassword = function(password) {
  123. this.password = generatePassword(password);
  124. return this;
  125. };
  126. userSchema.methods.isEmailSet = function() {
  127. if (this.email) {
  128. return true;
  129. }
  130. return false;
  131. };
  132. userSchema.methods.updateLastLoginAt = function(lastLoginAt, callback) {
  133. this.lastLoginAt = lastLoginAt;
  134. this.save(function(err, userData) {
  135. return callback(err, userData);
  136. });
  137. };
  138. userSchema.methods.updateIsGravatarEnabled = function(isGravatarEnabled, callback) {
  139. this.isGravatarEnabled = isGravatarEnabled;
  140. this.save(function(err, userData) {
  141. return callback(err, userData);
  142. });
  143. };
  144. userSchema.methods.updateIsEmailPublished = function(isEmailPublished, callback) {
  145. this.isEmailPublished = isEmailPublished;
  146. this.save(function(err, userData) {
  147. return callback(err, userData);
  148. });
  149. };
  150. userSchema.methods.updatePassword = function(password, callback) {
  151. this.setPassword(password);
  152. this.save(function(err, userData) {
  153. return callback(err, userData);
  154. });
  155. };
  156. userSchema.methods.updateApiToken = function(callback) {
  157. var self = this;
  158. self.apiToken = generateApiToken(this);
  159. return new Promise(function(resolve, reject) {
  160. self.save(function(err, userData) {
  161. if (err) {
  162. return reject(err);
  163. }
  164. else {
  165. return resolve(userData);
  166. }
  167. });
  168. });
  169. };
  170. userSchema.methods.updateImage = function(image, callback) {
  171. this.image = image;
  172. this.save(function(err, userData) {
  173. return callback(err, userData);
  174. });
  175. };
  176. userSchema.methods.deleteImage = function(callback) {
  177. return this.updateImage(null, callback);
  178. };
  179. userSchema.methods.updateGoogleId = function(googleId, callback) {
  180. this.googleId = googleId;
  181. this.save(function(err, userData) {
  182. return callback(err, userData);
  183. });
  184. };
  185. userSchema.methods.deleteGoogleId = function(callback) {
  186. return this.updateGoogleId(null, callback);
  187. };
  188. userSchema.methods.activateInvitedUser = async function(username, name, password) {
  189. this.setPassword(password);
  190. this.name = name;
  191. this.username = username;
  192. this.status = STATUS_ACTIVE;
  193. this.save(function(err, userData) {
  194. userEvent.emit('activated', userData);
  195. if (err) {
  196. throw new Error(err);
  197. }
  198. return userData;
  199. });
  200. };
  201. userSchema.methods.removeFromAdmin = function(callback) {
  202. debug('Remove from admin', this);
  203. this.admin = 0;
  204. this.save(function(err, userData) {
  205. return callback(err, userData);
  206. });
  207. };
  208. userSchema.methods.makeAdmin = function(callback) {
  209. debug('Admin', this);
  210. this.admin = 1;
  211. this.save(function(err, userData) {
  212. return callback(err, userData);
  213. });
  214. };
  215. userSchema.methods.statusActivate = function(callback) {
  216. debug('Activate User', this);
  217. this.status = STATUS_ACTIVE;
  218. this.save(function(err, userData) {
  219. userEvent.emit('activated', userData);
  220. return callback(err, userData);
  221. });
  222. };
  223. userSchema.methods.statusSuspend = function(callback) {
  224. debug('Suspend User', this);
  225. this.status = STATUS_SUSPENDED;
  226. if (this.email === undefined || this.email === null) { // migrate old data
  227. this.email = '-';
  228. }
  229. if (this.name === undefined || this.name === null) { // migrate old data
  230. this.name = '-' + Date.now();
  231. }
  232. if (this.username === undefined || this.usename === null) { // migrate old data
  233. this.username = '-';
  234. }
  235. this.save(function(err, userData) {
  236. return callback(err, userData);
  237. });
  238. };
  239. userSchema.methods.statusDelete = function(callback) {
  240. debug('Delete User', this);
  241. const now = new Date();
  242. const deletedLabel = `deleted_at_${now.getTime()}`;
  243. this.status = STATUS_DELETED;
  244. this.username = deletedLabel;
  245. this.password = '';
  246. this.name = '';
  247. this.email = `${deletedLabel}@deleted`;
  248. this.googleId = null;
  249. this.isGravatarEnabled = false;
  250. this.image = null;
  251. this.save(function(err, userData) {
  252. return callback(err, userData);
  253. });
  254. };
  255. userSchema.methods.updateGoogleId = function(googleId, callback) {
  256. this.googleId = googleId;
  257. this.save(function(err, userData) {
  258. return callback(err, userData);
  259. });
  260. };
  261. userSchema.statics.getLanguageLabels = getLanguageLabels;
  262. userSchema.statics.getUserStatusLabels = function() {
  263. var userStatus = {};
  264. userStatus[STATUS_REGISTERED] = '承認待ち';
  265. userStatus[STATUS_ACTIVE] = 'Active';
  266. userStatus[STATUS_SUSPENDED] = 'Suspended';
  267. userStatus[STATUS_DELETED] = 'Deleted';
  268. userStatus[STATUS_INVITED] = '招待済み';
  269. return userStatus;
  270. };
  271. userSchema.statics.isEmailValid = function(email, callback) {
  272. validateCrowi();
  273. var config = crowi.getConfig()
  274. , whitelist = config.crowi['security:registrationWhiteList'];
  275. if (Array.isArray(whitelist) && whitelist.length > 0) {
  276. return config.crowi['security:registrationWhiteList'].some(function(allowedEmail) {
  277. var re = new RegExp(allowedEmail + '$');
  278. return re.test(email);
  279. });
  280. }
  281. return true;
  282. };
  283. userSchema.statics.filterToPublicFields = function(user) {
  284. debug('User is', typeof user, user);
  285. if (typeof user !== 'object' || !user._id) {
  286. return user;
  287. }
  288. var filteredUser = {};
  289. var fields = USER_PUBLIC_FIELDS.split(' ');
  290. for (var i = 0; i < fields.length; i++) {
  291. var key = fields[i];
  292. if (user[key]) {
  293. filteredUser[key] = user[key];
  294. }
  295. }
  296. return filteredUser;
  297. };
  298. userSchema.statics.findUsers = function(options, callback) {
  299. var sort = options.sort || {status: 1, createdAt: 1};
  300. this.find()
  301. .sort(sort)
  302. .skip(options.skip || 0)
  303. .limit(options.limit || 21)
  304. .exec(function(err, userData) {
  305. callback(err, userData);
  306. });
  307. };
  308. userSchema.statics.findAllUsers = function(option) {
  309. var User = this;
  310. var option = option || {}
  311. , sort = option.sort || {createdAt: -1}
  312. , status = option.status || [STATUS_ACTIVE, STATUS_SUSPENDED]
  313. , fields = option.fields || USER_PUBLIC_FIELDS
  314. ;
  315. if (!Array.isArray(status)) {
  316. status = [status];
  317. }
  318. return new Promise(function(resolve, reject) {
  319. User
  320. .find()
  321. .or(status.map(s => { return {status: s} }))
  322. .select(fields)
  323. .sort(sort)
  324. .exec(function(err, userData) {
  325. if (err) {
  326. return reject(err);
  327. }
  328. return resolve(userData);
  329. });
  330. });
  331. };
  332. userSchema.statics.findUsersByIds = function(ids, option) {
  333. var User = this;
  334. var option = option || {}
  335. , sort = option.sort || {createdAt: -1}
  336. , status = option.status || STATUS_ACTIVE
  337. , fields = option.fields || USER_PUBLIC_FIELDS
  338. ;
  339. return new Promise(function(resolve, reject) {
  340. User
  341. .find({ _id: { $in: ids }, status: status })
  342. .select(fields)
  343. .sort(sort)
  344. .exec(function(err, userData) {
  345. if (err) {
  346. return reject(err);
  347. }
  348. return resolve(userData);
  349. });
  350. });
  351. };
  352. userSchema.statics.findAdmins = function(callback) {
  353. var User = this;
  354. this.find({admin: true})
  355. .exec(function(err, admins) {
  356. debug('Admins: ', admins);
  357. callback(err, admins);
  358. });
  359. };
  360. userSchema.statics.findUsersWithPagination = async function(options) {
  361. var sort = options.sort || {status: 1, username: 1, createdAt: 1};
  362. return await this.paginate({status: { $ne: STATUS_DELETED }}, { page: options.page || 1, limit: options.limit || PAGE_ITEMS }, function(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}, function(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. var hashedPassword = generatePassword(password);
  421. this.findOne({email: email, password: hashedPassword}, function(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: status};
  440. // TODO count は非推奨。mongoose のバージョンアップ後に countDocuments に変更する。
  441. return User.count(conditions);
  442. };
  443. userSchema.statics.isRegisterableUsername = async function(username) {
  444. var User = this;
  445. var usernameUsable = true;
  446. const userData = await this.findOne({username: username});
  447. if (userData) {
  448. usernameUsable = false;
  449. }
  450. return usernameUsable;
  451. };
  452. userSchema.statics.isRegisterable = function(email, username, callback) {
  453. var User = this;
  454. var emailUsable = true;
  455. var usernameUsable = true;
  456. // username check
  457. this.findOne({username: username}, function(err, userData) {
  458. if (userData) {
  459. usernameUsable = false;
  460. }
  461. // email check
  462. User.findOne({email: email}, function(err, userData) {
  463. if (userData) {
  464. emailUsable = false;
  465. }
  466. if (!emailUsable || !usernameUsable) {
  467. return callback(false, {email: emailUsable, username: usernameUsable});
  468. }
  469. return callback(true, {});
  470. });
  471. });
  472. };
  473. userSchema.statics.removeCompletelyById = function(id, callback) {
  474. var User = this;
  475. User.findById(id, function(err, userData) {
  476. if (!userData) {
  477. return callback(err, null);
  478. }
  479. debug('Removing user:', userData);
  480. // 物理削除可能なのは、承認待ちユーザー、招待中ユーザーのみ
  481. // 利用を一度開始したユーザーは論理削除のみ可能
  482. if (userData.status !== STATUS_REGISTERED && userData.status !== STATUS_INVITED) {
  483. return callback(new Error('Cannot remove completely the user whoes status is not INVITED'), null);
  484. }
  485. userData.remove(function(err) {
  486. if (err) {
  487. return callback(err, null);
  488. }
  489. return callback(null, 1);
  490. });
  491. });
  492. };
  493. userSchema.statics.resetPasswordByRandomString = function(id) {
  494. var User = this;
  495. return new Promise(function(resolve, reject) {
  496. User.findById(id, function(err, userData) {
  497. if (!userData) {
  498. return reject(new Error('User not found'));
  499. }
  500. // is updatable check
  501. // if (userData.isUp
  502. var newPassword = generateRandomTempPassword();
  503. userData.setPassword(newPassword);
  504. userData.save(function(err, userData) {
  505. if (err) {
  506. return reject(err);
  507. }
  508. resolve({user: userData, newPassword: newPassword});
  509. });
  510. });
  511. });
  512. };
  513. userSchema.statics.createUsersByInvitation = function(emailList, toSendEmail, callback) {
  514. validateCrowi();
  515. var User = this
  516. , createdUserList = []
  517. , Config = crowi.model('Config')
  518. , config = crowi.getConfig()
  519. , mailer = crowi.getMailer()
  520. ;
  521. if (!Array.isArray(emailList)) {
  522. debug('emailList is not array');
  523. }
  524. async.each(
  525. emailList,
  526. function(email, next) {
  527. var newUser = new User()
  528. , tmpUsername, password;
  529. email = email.trim();
  530. // email check
  531. // TODO: 削除済みはチェック対象から外そう〜
  532. User.findOne({email: email}, function(err, userData) {
  533. // The user is exists
  534. if (userData) {
  535. createdUserList.push({
  536. email: email,
  537. password: null,
  538. user: null,
  539. });
  540. return next();
  541. }
  542. tmpUsername = 'temp_' + Math.random().toString(36).slice(-16);
  543. password = Math.random().toString(36).slice(-16);
  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(function(err, userData) {
  554. if (err) {
  555. createdUserList.push({
  556. email: email,
  557. password: null,
  558. user: null,
  559. });
  560. debug('save failed!! ', err);
  561. }
  562. else {
  563. createdUserList.push({
  564. email: email,
  565. password: password,
  566. user: userData,
  567. });
  568. debug('saved!', email);
  569. }
  570. next();
  571. });
  572. });
  573. },
  574. function(err) {
  575. if (err) {
  576. debug('error occured while iterate email list');
  577. }
  578. if (toSendEmail) {
  579. // TODO: メール送信部分のロジックをサービス化する
  580. async.each(
  581. createdUserList,
  582. function(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. function(err, s) {
  598. debug('completed to send email: ', err, s);
  599. next();
  600. }
  601. );
  602. },
  603. function(err) {
  604. debug('Sending invitation email completed.', err);
  605. }
  606. );
  607. }
  608. debug('createdUserList!!! ', createdUserList);
  609. return callback(null, createdUserList);
  610. }
  611. );
  612. };
  613. userSchema.statics.createUserByEmailAndPasswordAndStatus = async function(name, username, email, password, lang, status, callback) {
  614. const User = this
  615. , newUser = new User();
  616. // check user upper limit
  617. const isUserCountExceedsUpperLimit = await User.isUserCountExceedsUpperLimit();
  618. if (isUserCountExceedsUpperLimit) {
  619. const err = new UserUpperLimitException();
  620. return callback(err);
  621. }
  622. // check email duplication because email must be unique
  623. const count = await this.count({ email });
  624. if (count > 0) {
  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(function(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.createUserPictureFilePath = function(user, name) {
  679. var ext = '.' + name.match(/(.*)(?:\.([^.]+$))/)[2];
  680. return 'user/' + user._id + ext;
  681. };
  682. userSchema.statics.getUsernameByPath = function(path) {
  683. var username = null;
  684. if (m = path.match(/^\/user\/([^\/]+)\/?/)) {
  685. username = m[1];
  686. }
  687. return username;
  688. };
  689. class UserUpperLimitException {
  690. constructor() {
  691. this.name = this.constructor.name;
  692. }
  693. }
  694. userSchema.statics.STATUS_REGISTERED = STATUS_REGISTERED;
  695. userSchema.statics.STATUS_ACTIVE = STATUS_ACTIVE;
  696. userSchema.statics.STATUS_SUSPENDED = STATUS_SUSPENDED;
  697. userSchema.statics.STATUS_DELETED = STATUS_DELETED;
  698. userSchema.statics.STATUS_INVITED = STATUS_INVITED;
  699. userSchema.statics.USER_PUBLIC_FIELDS = USER_PUBLIC_FIELDS;
  700. userSchema.statics.PAGE_ITEMS = PAGE_ITEMS;
  701. userSchema.statics.LANG_EN = LANG_EN;
  702. userSchema.statics.LANG_EN_US = LANG_EN_US;
  703. userSchema.statics.LANG_EN_GB = LANG_EN_US;
  704. userSchema.statics.LANG_JA = LANG_JA;
  705. return mongoose.model('User', userSchema);
  706. };