user.js 18 KB

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