2
0

user.js 19 KB

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