user.js 20 KB

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