user.js 23 KB

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