user.js 20 KB

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