user.js 20 KB

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