user.js 19 KB

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