user.js 18 KB

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