user.js 18 KB

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