user.js 19 KB

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