user.js 19 KB

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