user.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  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, STATUS_SUSPENDED]
  267. , fields = option.fields || USER_PUBLIC_FIELDS
  268. ;
  269. if (!Array.isArray(status)) {
  270. status = [status];
  271. }
  272. return new Promise(function(resolve, reject) {
  273. User
  274. .find()
  275. .or(status.map(s => { return {status: s}; }))
  276. .select(fields)
  277. .sort(sort)
  278. .exec(function (err, userData) {
  279. if (err) {
  280. return reject(err);
  281. }
  282. return resolve(userData);
  283. });
  284. });
  285. };
  286. userSchema.statics.findUsersByIds = function(ids, option) {
  287. var User = this;
  288. var option = option || {}
  289. , sort = option.sort || {createdAt: -1}
  290. , status = option.status || STATUS_ACTIVE
  291. , fields = option.fields || USER_PUBLIC_FIELDS
  292. ;
  293. return new Promise(function(resolve, reject) {
  294. User
  295. .find({ _id: { $in: ids }, status: status })
  296. .select(fields)
  297. .sort(sort)
  298. .exec(function (err, userData) {
  299. if (err) {
  300. return reject(err);
  301. }
  302. return resolve(userData);
  303. });
  304. });
  305. };
  306. userSchema.statics.findAdmins = function(callback) {
  307. var User = this;
  308. this.find({admin: true})
  309. .exec(function(err, admins) {
  310. debug('Admins: ', admins);
  311. callback(err, admins);
  312. });
  313. };
  314. userSchema.statics.findUsersWithPagination = function(options, callback) {
  315. var sort = options.sort || {status: 1, username: 1, createdAt: 1};
  316. this.paginate({}, { page: options.page || 1, limit: options.limit || PAGE_ITEMS }, function(err, result) {
  317. if (err) {
  318. debug('Error on pagination:', err);
  319. return callback(err, null);
  320. }
  321. return callback(err, result);
  322. }, { sortBy : sort });
  323. };
  324. userSchema.statics.findUsersByPartOfEmail = function(emailPart, options) {
  325. const status = options.status || null;
  326. const emailPartRegExp = new RegExp(emailPart.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'));
  327. const User = this;
  328. return new Promise((resolve, reject) => {
  329. const query = User.find({ email: emailPartRegExp }, USER_PUBLIC_FIELDS);
  330. if (status) {
  331. query.and({status});
  332. }
  333. query
  334. .limit(PAGE_ITEMS + 1)
  335. .exec((err, userData) => {
  336. if (err) {
  337. return reject(err);
  338. }
  339. return resolve(userData);
  340. });
  341. });
  342. };
  343. userSchema.statics.findUserByUsername = function(username) {
  344. var User = this;
  345. return new Promise(function(resolve, reject) {
  346. User.findOne({username: username}, function (err, userData) {
  347. if (err) {
  348. return reject(err);
  349. }
  350. return resolve(userData);
  351. });
  352. });
  353. };
  354. userSchema.statics.findUserByApiToken = function(apiToken) {
  355. var self = this;
  356. return new Promise(function(resolve, reject) {
  357. self.findOne({apiToken: apiToken}, function (err, userData) {
  358. if (err) {
  359. return reject(err);
  360. } else {
  361. return resolve(userData);
  362. }
  363. });
  364. });
  365. };
  366. userSchema.statics.findUserByGoogleId = function(googleId, callback) {
  367. this.findOne({googleId: googleId}, function (err, userData) {
  368. callback(err, userData);
  369. });
  370. };
  371. userSchema.statics.findUserByEmailAndPassword = function(email, password, callback) {
  372. var hashedPassword = generatePassword(password);
  373. this.findOne({email: email, password: hashedPassword}, function (err, userData) {
  374. callback(err, userData);
  375. });
  376. };
  377. userSchema.statics.isRegisterableUsername = function(username, callback) {
  378. var User = this;
  379. var usernameUsable = true;
  380. this.findOne({username: username}, function (err, userData) {
  381. if (userData) {
  382. usernameUsable = false;
  383. }
  384. return callback(usernameUsable);
  385. });
  386. };
  387. userSchema.statics.isRegisterable = function(email, username, callback) {
  388. var User = this;
  389. var emailUsable = true;
  390. var usernameUsable = true;
  391. // username check
  392. this.findOne({username: username}, function (err, userData) {
  393. if (userData) {
  394. usernameUsable = false;
  395. }
  396. // email check
  397. User.findOne({email: email}, function (err, userData) {
  398. if (userData) {
  399. emailUsable = false;
  400. }
  401. if (!emailUsable || !usernameUsable) {
  402. return callback(false, {email: emailUsable, username: usernameUsable});
  403. }
  404. return callback(true, {});
  405. });
  406. });
  407. };
  408. userSchema.statics.removeCompletelyById = function(id, callback) {
  409. var User = this;
  410. User.findById(id, function (err, userData) {
  411. if (!userData) {
  412. return callback(err, null);
  413. }
  414. debug('Removing user:', userData);
  415. // 物理削除可能なのは、招待中ユーザーのみ
  416. // 利用を一度開始したユーザーは論理削除のみ可能
  417. if (userData.status !== STATUS_INVITED) {
  418. return callback(new Error('Cannot remove completely the user whoes status is not INVITED'), null);
  419. }
  420. userData.remove(function(err) {
  421. if (err) {
  422. return callback(err, null);
  423. }
  424. return callback(null, 1);
  425. });
  426. });
  427. };
  428. userSchema.statics.resetPasswordByRandomString = function(id) {
  429. var User = this;
  430. return new Promise(function(resolve, reject) {
  431. User.findById(id, function (err, userData) {
  432. if (!userData) {
  433. return reject(new Error('User not found'));
  434. }
  435. // is updatable check
  436. // if (userData.isUp
  437. var newPassword = generateRandomTempPassword();
  438. userData.setPassword(newPassword);
  439. userData.save(function(err, userData) {
  440. if (err) {
  441. return reject(err);
  442. }
  443. resolve({user: userData, newPassword: newPassword});
  444. });
  445. });
  446. });
  447. };
  448. userSchema.statics.createUsersByInvitation = function(emailList, toSendEmail, callback) {
  449. var User = this
  450. , createdUserList = []
  451. , config = crowi.getConfig()
  452. , mailer = crowi.getMailer()
  453. ;
  454. if (!Array.isArray(emailList)) {
  455. debug('emailList is not array');
  456. }
  457. async.each(
  458. emailList,
  459. function(email, next) {
  460. var newUser = new User()
  461. ,password;
  462. email = email.trim();
  463. // email check
  464. // TODO: 削除済みはチェック対象から外そう〜
  465. User.findOne({email: email}, function (err, userData) {
  466. // The user is exists
  467. if (userData) {
  468. createdUserList.push({
  469. email: email,
  470. password: null,
  471. user: null,
  472. });
  473. return next();
  474. }
  475. password = Math.random().toString(36).slice(-16);
  476. newUser.email = email;
  477. newUser.setPassword(password);
  478. newUser.createdAt = Date.now();
  479. newUser.status = STATUS_INVITED;
  480. newUser.save(function(err, userData) {
  481. if (err) {
  482. createdUserList.push({
  483. email: email,
  484. password: null,
  485. user: null,
  486. });
  487. debug('save failed!! ', email);
  488. } else {
  489. createdUserList.push({
  490. email: email,
  491. password: password,
  492. user: userData,
  493. });
  494. debug('saved!', email);
  495. }
  496. next();
  497. });
  498. });
  499. },
  500. function(err) {
  501. if (err) {
  502. debug('error occured while iterate email list');
  503. }
  504. if (toSendEmail) {
  505. // TODO: メール送信部分のロジックをサービス化する
  506. async.each(
  507. createdUserList,
  508. function(user, next) {
  509. if (user.password === null) {
  510. return next();
  511. }
  512. mailer.send({
  513. to: user.email,
  514. subject: 'Invitation to ' + config.crowi['app:title'],
  515. template: 'admin/userInvitation.txt',
  516. vars: {
  517. email: user.email,
  518. password: user.password,
  519. url: config.crowi['app:url'],
  520. appTitle: config.crowi['app:title'],
  521. }
  522. },
  523. function (err, s) {
  524. debug('completed to send email: ', err, s);
  525. next();
  526. }
  527. );
  528. },
  529. function(err) {
  530. debug('Sending invitation email completed.', err);
  531. }
  532. );
  533. }
  534. debug('createdUserList!!! ', createdUserList);
  535. return callback(null, createdUserList);
  536. }
  537. );
  538. };
  539. userSchema.statics.createUserByEmailAndPassword = function(name, username, email, password, lang, callback) {
  540. var User = this
  541. , newUser = new User();
  542. newUser.name = name;
  543. newUser.username = username;
  544. newUser.email = email;
  545. newUser.setPassword(password);
  546. newUser.lang = lang;
  547. newUser.createdAt = Date.now();
  548. newUser.status = decideUserStatusOnRegistration();
  549. newUser.save(function(err, userData) {
  550. if (userData.status == STATUS_ACTIVE) {
  551. userEvent.emit('activated', userData);
  552. }
  553. return callback(err, userData);
  554. });
  555. };
  556. userSchema.statics.createUserPictureFilePath = function(user, name) {
  557. var ext = '.' + name.match(/(.*)(?:\.([^.]+$))/)[2];
  558. return 'user/' + user._id + ext;
  559. };
  560. userSchema.statics.getUsernameByPath = function(path) {
  561. var username = null;
  562. if (m = path.match(/^\/user\/([^\/]+)\/?/)) {
  563. username = m[1];
  564. }
  565. return username;
  566. };
  567. userSchema.statics.STATUS_REGISTERED = STATUS_REGISTERED;
  568. userSchema.statics.STATUS_ACTIVE = STATUS_ACTIVE;
  569. userSchema.statics.STATUS_SUSPENDED = STATUS_SUSPENDED;
  570. userSchema.statics.STATUS_DELETED = STATUS_DELETED;
  571. userSchema.statics.STATUS_INVITED = STATUS_INVITED;
  572. userSchema.statics.USER_PUBLIC_FIELDS = USER_PUBLIC_FIELDS;
  573. userSchema.statics.PAGE_ITEMS = PAGE_ITEMS;
  574. userSchema.statics.LANG_EN = LANG_EN;
  575. userSchema.statics.LANG_EN_US = LANG_EN_US;
  576. userSchema.statics.LANG_EN_GB = LANG_EN_US;
  577. userSchema.statics.LANG_JA = LANG_JA;
  578. return mongoose.model('User', userSchema);
  579. };