user.js 23 KB

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