user.js 18 KB

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