2
0

user.js 18 KB

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