user.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  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 fbId image googleId name username email status createdAt' // TODO: どこか別の場所へ...
  14. , PAGE_ITEMS = 20
  15. , userEvent = crowi.event('user')
  16. , userSchema;
  17. userSchema = new mongoose.Schema({
  18. userId: String,
  19. fbId: String, // userId
  20. image: String,
  21. googleId: String,
  22. name: { type: String },
  23. username: { type: String, index: true },
  24. email: { type: String, required: true, index: true },
  25. introduction: { type: String },
  26. password: String,
  27. apiToken: String,
  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 generatePassword (password) {
  52. var hasher = crypto.createHash('sha256');
  53. hasher.update(crowi.env.PASSWORD_SEED + password);
  54. return hasher.digest('hex');
  55. }
  56. function generateApiToken (user) {
  57. var hasher = crypto.createHash('sha256');
  58. hasher.update((new Date).getTime() + user._id);
  59. return hasher.digest('base64');
  60. }
  61. userSchema.methods.isPasswordSet = function() {
  62. if (this.password) {
  63. return true;
  64. }
  65. return false;
  66. };
  67. userSchema.methods.isPasswordValid = function(password) {
  68. return this.password == generatePassword(password);
  69. };
  70. userSchema.methods.setPassword = function(password) {
  71. this.password = generatePassword(password);
  72. return this;
  73. };
  74. userSchema.methods.isEmailSet = function() {
  75. if (this.email) {
  76. return true;
  77. }
  78. return false;
  79. };
  80. userSchema.methods.update = function(name, email, callback) {
  81. this.name = name;
  82. this.email = email;
  83. this.save(function(err, userData) {
  84. return callback(err, userData);
  85. });
  86. };
  87. userSchema.methods.updatePassword = function(password, callback) {
  88. this.setPassword(password);
  89. this.save(function(err, userData) {
  90. return callback(err, userData);
  91. });
  92. };
  93. userSchema.methods.updateApiToken = function(callback) {
  94. var self = this;
  95. self.apiToken = generateApiToken(this);
  96. return new Promise(function(resolve, reject) {
  97. self.save(function(err, userData) {
  98. if (err) {
  99. return reject(err);
  100. } else {
  101. return resolve(userData);
  102. }
  103. });
  104. });
  105. };
  106. userSchema.methods.updateImage = function(image, callback) {
  107. this.image = image;
  108. this.save(function(err, userData) {
  109. return callback(err, userData);
  110. });
  111. };
  112. userSchema.methods.deleteImage = function(callback) {
  113. return this.updateImage(null, callback);
  114. };
  115. userSchema.methods.updateFacebookId = function(fbId, callback) {
  116. this.fbId = this.userId = fbId;
  117. this.save(function(err, userData) {
  118. return callback(err, userData);
  119. });
  120. };
  121. userSchema.methods.deleteFacebookId = function(callback) {
  122. return this.updateFacebookId(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.fbId = null;
  188. this.image = null;
  189. this.save(function(err, userData) {
  190. return callback(err, userData);
  191. });
  192. };
  193. userSchema.methods.updateGoogleIdAndFacebookId = function(googleId, facebookId, callback) {
  194. this.googleId = googleId;
  195. this.fbId = this.userId = facebookId;
  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.findUsers = function(options, callback) {
  221. var sort = options.sort || {status: 1, createdAt: 1};
  222. this.find()
  223. .sort(sort)
  224. .skip(options.skip || 0)
  225. .limit(options.limit || 21)
  226. .exec(function (err, userData) {
  227. callback(err, userData);
  228. });
  229. };
  230. userSchema.statics.findUsersByIds = function(ids, option) {
  231. var User = this;
  232. var option = option || {}
  233. , sort = option.sort || {createdAt: -1}
  234. , status = option.status || STATUS_ACTIVE
  235. , fields = option.fields || USER_PUBLIC_FIELDS
  236. ;
  237. return new Promise(function(resolve, reject) {
  238. User
  239. .find({ _id: { $in: ids }, status: status })
  240. .select(fields)
  241. .sort(sort)
  242. .exec(function (err, userData) {
  243. if (err) {
  244. return reject(err);
  245. }
  246. return resolve(userData);
  247. });
  248. });
  249. };
  250. userSchema.statics.findAdmins = function(callback) {
  251. var User = this;
  252. this.find({admin: true})
  253. .exec(function(err, admins) {
  254. debug('Admins: ', admins);
  255. callback(err, admins);
  256. });
  257. };
  258. userSchema.statics.findUsersWithPagination = function(options, callback) {
  259. var sort = options.sort || {status: 1, username: 1, createdAt: 1};
  260. this.paginate({}, { page: options.page || 1, limit: PAGE_ITEMS }, function(err, paginatedResults, pageCount, itemCount) {
  261. if (err) {
  262. debug('Error on pagination:', err);
  263. return callback(err, null);
  264. }
  265. return callback(err, paginatedResults, pageCount, itemCount);
  266. }, { sortBy : sort });
  267. };
  268. userSchema.statics.findUserByUsername = function(username) {
  269. var User = this;
  270. return new Promise(function(resolve, reject) {
  271. User.findOne({username: username}, function (err, userData) {
  272. if (err) {
  273. return reject(err);
  274. }
  275. return resolve(userData);
  276. });
  277. });
  278. };
  279. userSchema.statics.findUserByApiToken = function(apiToken) {
  280. var self = this;
  281. return new Promise(function(resolve, reject) {
  282. self.findOne({apiToken: apiToken}, function (err, userData) {
  283. if (err) {
  284. return reject(err);
  285. } else {
  286. return resolve(userData);
  287. }
  288. });
  289. });
  290. };
  291. userSchema.statics.findUserByFacebookId = function(fbId, callback) {
  292. this.findOne({userId: fbId}, function (err, userData) {
  293. callback(err, userData);
  294. });
  295. };
  296. userSchema.statics.findUserByGoogleId = function(googleId, callback) {
  297. this.findOne({googleId: googleId}, function (err, userData) {
  298. callback(err, userData);
  299. });
  300. };
  301. userSchema.statics.findUserByEmailAndPassword = function(email, password, callback) {
  302. var hashedPassword = generatePassword(password);
  303. this.findOne({email: email, password: hashedPassword}, function (err, userData) {
  304. callback(err, userData);
  305. });
  306. };
  307. userSchema.statics.isRegisterableUsername = function(username, callback) {
  308. var User = this;
  309. var usernameUsable = true;
  310. this.findOne({username: username}, function (err, userData) {
  311. if (userData) {
  312. usernameUsable = false;
  313. }
  314. return callback(usernameUsable);
  315. });
  316. };
  317. userSchema.statics.isRegisterable = function(email, username, callback) {
  318. var User = this;
  319. var emailUsable = true;
  320. var usernameUsable = true;
  321. // username check
  322. this.findOne({username: username}, function (err, userData) {
  323. if (userData) {
  324. usernameUsable = false;
  325. }
  326. // email check
  327. User.findOne({email: email}, function (err, userData) {
  328. if (userData) {
  329. emailUsable = false;
  330. }
  331. if (!emailUsable || !usernameUsable) {
  332. return callback(false, {email: emailUsable, username: usernameUsable});
  333. }
  334. return callback(true, {});
  335. });
  336. });
  337. };
  338. userSchema.statics.removeCompletelyById = function(id, callback) {
  339. var User = this;
  340. User.findById(id, function (err, userData) {
  341. if (!userData) {
  342. return callback(err, null);
  343. }
  344. debug('Removing user:', userData);
  345. // 物理削除可能なのは、招待中ユーザーのみ
  346. // 利用を一度開始したユーザーは論理削除のみ可能
  347. if (userData.status !== STATUS_INVITED) {
  348. return callback(new Error('Cannot remove completely the user whoes status is not INVITED'), null);
  349. }
  350. userData.remove(function(err) {
  351. if (err) {
  352. return callback(err, null);
  353. }
  354. return callback(null, 1);
  355. });
  356. });
  357. };
  358. userSchema.statics.createUsersByInvitation = function(emailList, toSendEmail, callback) {
  359. var User = this
  360. , createdUserList = []
  361. , config = crowi.getConfig()
  362. , mailer = crowi.getMailer()
  363. ;
  364. if (!Array.isArray(emailList)) {
  365. debug('emailList is not array');
  366. }
  367. async.each(
  368. emailList,
  369. function(email, next) {
  370. var newUser = new User()
  371. ,password;
  372. email = email.trim();
  373. // email check
  374. // TODO: 削除済みはチェック対象から外そう〜
  375. User.findOne({email: email}, function (err, userData) {
  376. // The user is exists
  377. if (userData) {
  378. createdUserList.push({
  379. email: email,
  380. password: null,
  381. user: null,
  382. });
  383. return next();
  384. }
  385. password = Math.random().toString(36).slice(-16);
  386. newUser.email = email;
  387. newUser.setPassword(password);
  388. newUser.createdAt = Date.now();
  389. newUser.status = STATUS_INVITED;
  390. newUser.save(function(err, userData) {
  391. if (err) {
  392. createdUserList.push({
  393. email: email,
  394. password: null,
  395. user: null,
  396. });
  397. debug('save failed!! ', email);
  398. } else {
  399. createdUserList.push({
  400. email: email,
  401. password: password,
  402. user: userData,
  403. });
  404. debug('saved!', email);
  405. }
  406. next();
  407. });
  408. });
  409. },
  410. function(err) {
  411. if (err) {
  412. debug('error occured while iterate email list');
  413. }
  414. if (toSendEmail) {
  415. // TODO: メール送信部分のロジックをサービス化する
  416. async.each(
  417. createdUserList,
  418. function(user, next) {
  419. if (user.password === null) {
  420. return next();
  421. }
  422. mailer.send({
  423. to: user.email,
  424. subject: 'Invitation to ' + config.crowi['app:title'],
  425. template: 'admin/userInvitation.txt',
  426. vars: {
  427. email: user.email,
  428. password: user.password,
  429. url: config.crowi['app:url'],
  430. appTitle: config.crowi['app:title'],
  431. }
  432. },
  433. function (err, s) {
  434. debug('completed to send email: ', err, s);
  435. next();
  436. }
  437. );
  438. },
  439. function(err) {
  440. debug('Sending invitation email completed.', err);
  441. }
  442. );
  443. }
  444. debug('createdUserList!!! ', createdUserList);
  445. return callback(null, createdUserList);
  446. }
  447. );
  448. };
  449. userSchema.statics.createUserByEmailAndPassword = function(name, username, email, password, callback) {
  450. var User = this
  451. , newUser = new User();
  452. newUser.name = name;
  453. newUser.username = username;
  454. newUser.email = email;
  455. newUser.setPassword(password);
  456. newUser.createdAt = Date.now();
  457. newUser.status = decideUserStatusOnRegistration();
  458. newUser.save(function(err, userData) {
  459. if (userData.status == STATUS_ACTIVE) {
  460. userEvent.emit('activated', userData);
  461. }
  462. return callback(err, userData);
  463. });
  464. };
  465. userSchema.statics.createUserByFacebook = function(fbUserInfo, callback) {
  466. var User = this
  467. , newUser = new User();
  468. newUser.userId = fbUserInfo.id;
  469. newUser.image = '//graph.facebook.com/' + fbUserInfo.id + '/picture?size=square';
  470. newUser.name = fbUserInfo.name || '';
  471. newUser.username = fbUserInfo.username || '';
  472. newUser.email = fbUserInfo.email || '';
  473. newUser.createdAt = Date.now();
  474. newUser.status = decideUserStatusOnRegistration();
  475. newUser.save(function(err, userData) {
  476. if (userData.status == STATUS_ACTIVE) {
  477. userEvent.emit('activated', userData);
  478. }
  479. return callback(err, userData);
  480. });
  481. };
  482. userSchema.statics.createUserPictureFilePath = function(user, name) {
  483. var ext = '.' + name.match(/(.*)(?:\.([^.]+$))/)[2];
  484. return 'user/' + user._id + ext;
  485. };
  486. userSchema.statics.getUsernameByPath = function(path) {
  487. var username = null;
  488. if (m = path.match(/^\/user\/([^\/]+)\/?/)) {
  489. username = m[1];
  490. }
  491. return username;
  492. };
  493. userSchema.statics.STATUS_REGISTERED = STATUS_REGISTERED;
  494. userSchema.statics.STATUS_ACTIVE = STATUS_ACTIVE;
  495. userSchema.statics.STATUS_SUSPENDED = STATUS_SUSPENDED;
  496. userSchema.statics.STATUS_DELETED = STATUS_DELETED;
  497. userSchema.statics.STATUS_INVITED = STATUS_INVITED;
  498. userSchema.statics.USER_PUBLIC_FIELDS = USER_PUBLIC_FIELDS;
  499. return mongoose.model('User', userSchema);
  500. };