user.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. module.exports = function(app, models) {
  2. var mongoose = require('mongoose')
  3. , mongoosePaginate = require('mongoose-paginate')
  4. , debug = require('debug')('crowi:models:user')
  5. , crypto = require('crypto')
  6. , async = require('async')
  7. , config = app.set('config')
  8. , ObjectId = mongoose.Schema.Types.ObjectId
  9. , mailer = app.set('mailer')
  10. , STATUS_REGISTERED = 1
  11. , STATUS_ACTIVE = 2
  12. , STATUS_SUSPENDED = 3
  13. , STATUS_DELETED = 4
  14. , STATUS_INVITED = 5
  15. , PAGE_ITEMS = 20
  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 },
  24. email: { type: String, required: true },
  25. password: String,
  26. status: { type: Number, required: true, default: STATUS_ACTIVE },
  27. createdAt: { type: Date, default: Date.now },
  28. admin: { type: Boolean, default: 0 }
  29. });
  30. userSchema.plugin(mongoosePaginate);
  31. function decideUserStatusOnRegistration () {
  32. var Config = models.Config;
  33. // status decided depends on registrationMode
  34. switch (config.crowi['security:registrationMode']) {
  35. case Config.SECURITY_REGISTRATION_MODE_OPEN:
  36. return STATUS_ACTIVE;
  37. case Config.SECURITY_REGISTRATION_MODE_RESTRICTED:
  38. case Config.SECURITY_REGISTRATION_MODE_CLOSED: // 一応
  39. return STATUS_REGISTERED;
  40. default:
  41. return STATUS_ACTIVE; // どっちにすんのがいいんだろうな
  42. }
  43. }
  44. function generatePassword (password) {
  45. var hasher = crypto.createHash('sha256');
  46. hasher.update(process.env.PASSWORD_SEED + password);
  47. return hasher.digest('hex');
  48. }
  49. userSchema.methods.isPasswordSet = function() {
  50. if (this.password) {
  51. return true;
  52. }
  53. return false;
  54. };
  55. userSchema.methods.isPasswordValid = function(password) {
  56. return this.password == generatePassword(password);
  57. };
  58. userSchema.methods.setPassword = function(password) {
  59. return this.password == generatePassword(password);
  60. };
  61. userSchema.methods.setPassword = function(password) {
  62. this.password = generatePassword(password);
  63. return this;
  64. };
  65. userSchema.methods.isEmailSet = function() {
  66. if (this.email) {
  67. return true;
  68. }
  69. return false;
  70. };
  71. userSchema.methods.update = function(name, email, callback) {
  72. this.name = name;
  73. this.email = email;
  74. this.save(function(err, userData) {
  75. return callback(err, userData);
  76. });
  77. };
  78. userSchema.methods.updatePassword = function(password, callback) {
  79. this.setPassword(password);
  80. this.save(function(err, userData) {
  81. return callback(err, userData);
  82. });
  83. };
  84. userSchema.methods.updateImage = function(image, callback) {
  85. this.image = image;
  86. this.save(function(err, userData) {
  87. return callback(err, userData);
  88. });
  89. };
  90. userSchema.methods.deleteImage = function(callback) {
  91. return this.updateImage(null, callback);
  92. };
  93. userSchema.methods.updateFacebookId = function(fbId, callback) {
  94. this.fbId = this.userId = fbId;
  95. this.save(function(err, userData) {
  96. return callback(err, userData);
  97. });
  98. };
  99. userSchema.methods.deleteFacebookId = function(callback) {
  100. return this.updateFacebookId(null, callback);
  101. };
  102. userSchema.methods.updateGoogleId = function(googleId, callback) {
  103. this.googleId = googleId;
  104. this.save(function(err, userData) {
  105. return callback(err, userData);
  106. });
  107. };
  108. userSchema.methods.deleteGoogleId = function(callback) {
  109. return this.updateGoogleId(null, callback);
  110. };
  111. userSchema.methods.activateInvitedUser = function(username, name, password, callback) {
  112. this.setPassword(password);
  113. this.name = name;
  114. this.username = username;
  115. this.status = STATUS_ACTIVE;
  116. this.save(function(err, userData) {
  117. return callback(err, userData);
  118. });
  119. };
  120. userSchema.methods.removeFromAdmin = function(callback) {
  121. debug('Remove from admin', this);
  122. this.admin = 0;
  123. this.save(function(err, userData) {
  124. return callback(err, userData);
  125. });
  126. };
  127. userSchema.methods.makeAdmin = function(callback) {
  128. debug('Admin', this);
  129. this.admin = 1;
  130. this.save(function(err, userData) {
  131. return callback(err, userData);
  132. });
  133. };
  134. userSchema.methods.statusActivate = function(callback) {
  135. debug('Activate User', this);
  136. this.status = STATUS_ACTIVE;
  137. this.save(function(err, userData) {
  138. return callback(err, userData);
  139. });
  140. };
  141. userSchema.methods.statusSuspend = function(callback) {
  142. debug('Suspend User', this);
  143. this.status = STATUS_SUSPENDED;
  144. if (this.email === undefined || this.email === null) { // migrate old data
  145. this.email = '-';
  146. }
  147. if (this.name === undefined || this.name === null) { // migrate old data
  148. this.name = '-' + Date.now();
  149. }
  150. if (this.username === undefined || this.usename === null) { // migrate old data
  151. this.username = '-';
  152. }
  153. this.save(function(err, userData) {
  154. return callback(err, userData);
  155. });
  156. };
  157. userSchema.methods.statusDelete = function(callback) {
  158. debug('Delete User', this);
  159. this.status = STATUS_DELETED;
  160. this.password = '';
  161. this.email = 'deleted@deleted';
  162. this.googleId = null;
  163. this.fbId = null;
  164. this.image = null;
  165. this.save(function(err, userData) {
  166. return callback(err, userData);
  167. });
  168. };
  169. userSchema.methods.updateGoogleIdAndFacebookId = function(googleId, facebookId, callback) {
  170. this.googleId = googleId;
  171. this.fbId = this.userId = facebookId;
  172. this.save(function(err, userData) {
  173. return callback(err, userData);
  174. });
  175. };
  176. userSchema.statics.getUserStatusLabels = function() {
  177. var userStatus = {};
  178. userStatus[STATUS_REGISTERED] = '承認待ち';
  179. userStatus[STATUS_ACTIVE] = 'Active';
  180. userStatus[STATUS_SUSPENDED] = 'Suspended';
  181. userStatus[STATUS_DELETED] = 'Deleted';
  182. userStatus[STATUS_INVITED] = '招待済み';
  183. return userStatus;
  184. };
  185. userSchema.statics.isEmailValid = function(email, callback) {
  186. var whitelist = config.crowi['security:registrationWhiteList'];
  187. if (Array.isArray(whitelist) && whitelist.length > 0) {
  188. return config.crowi['security:registrationWhiteList'].some(function(allowedEmail) {
  189. var re = new RegExp(allowedEmail + '$');
  190. return re.test(email);
  191. });
  192. }
  193. return true;
  194. };
  195. userSchema.statics.findUsers = function(options, callback) {
  196. var sort = options.sort || {status: 1, createdAt: 1};
  197. this.find()
  198. .sort(sort)
  199. .skip(options.skip || 0)
  200. .limit(options.limit || 21)
  201. .exec(function (err, userData) {
  202. callback(err, userData);
  203. });
  204. };
  205. userSchema.statics.findAdmins = function(callback) {
  206. var User = this;
  207. this.find({admin: true})
  208. .exec(function(err, admins) {
  209. debug('Admins: ', admins);
  210. callback(err, admins);
  211. });
  212. };
  213. userSchema.statics.findUsersWithPagination = function(options, callback) {
  214. var sort = options.sort || {status: 1, username: 1, createdAt: 1};
  215. this.paginate({}, options.page || 1, PAGE_ITEMS, function(err, pageCount, paginatedResults, itemCount) {
  216. if (err) {
  217. debug('Error on pagination:', err);
  218. return callback(err, null);
  219. }
  220. return callback(err, paginatedResults, pageCount, itemCount);
  221. }, { sortBy : sort });
  222. };
  223. userSchema.statics.findUserByUsername = function(username, callback) {
  224. this.findOne({username: username}, function (err, userData) {
  225. callback(err, userData);
  226. });
  227. };
  228. userSchema.statics.findUserByFacebookId = function(fbId, callback) {
  229. this.findOne({userId: fbId}, function (err, userData) {
  230. callback(err, userData);
  231. });
  232. };
  233. userSchema.statics.findUserByGoogleId = function(googleId, callback) {
  234. this.findOne({googleId: googleId}, function (err, userData) {
  235. callback(err, userData);
  236. });
  237. };
  238. userSchema.statics.findUserByEmailAndPassword = function(email, password, callback) {
  239. var hashedPassword = generatePassword(password);
  240. this.findOne({email: email, password: hashedPassword}, function (err, userData) {
  241. callback(err, userData);
  242. });
  243. };
  244. userSchema.statics.isRegisterableUsername = function(username, callback) {
  245. var User = this;
  246. var usernameUsable = true;
  247. this.findOne({username: username}, function (err, userData) {
  248. if (userData) {
  249. usernameUsable = false;
  250. }
  251. return callback(usernameUsable);
  252. });
  253. };
  254. userSchema.statics.isRegisterable = function(email, username, callback) {
  255. var User = this;
  256. var emailUsable = true;
  257. var usernameUsable = true;
  258. // username check
  259. this.findOne({username: username}, function (err, userData) {
  260. if (userData) {
  261. usernameUsable = false;
  262. }
  263. // email check
  264. User.findOne({email: email}, function (err, userData) {
  265. if (userData) {
  266. emailUsable = false;
  267. }
  268. if (!emailUsable || !usernameUsable) {
  269. return callback(false, {email: emailUsable, username: usernameUsable});
  270. }
  271. return callback(true, {});
  272. });
  273. });
  274. };
  275. userSchema.statics.removeCompletelyById = function(id, callback) {
  276. var User = this;
  277. User.findById(id, function (err, userData) {
  278. if (!userData) {
  279. return callback(err, null);
  280. }
  281. debug('Removing user:', userData);
  282. // 物理削除可能なのは、招待中ユーザーのみ
  283. // 利用を一度開始したユーザーは論理削除のみ可能
  284. if (userData.status !== STATUS_INVITED) {
  285. return callback(new Error('Cannot remove completely the user whoes status is not INVITED'), null);
  286. }
  287. userData.remove(function(err) {
  288. if (err) {
  289. return callback(err, null);
  290. }
  291. return callback(null, 1);
  292. });
  293. });
  294. };
  295. userSchema.statics.createUsersByInvitation = function(emailList, toSendEmail, callback) {
  296. var User = this
  297. , createdUserList = [];
  298. if (!Array.isArray(emailList)) {
  299. debug('emailList is not array');
  300. }
  301. async.each(
  302. emailList,
  303. function(email, next) {
  304. var newUser = new User()
  305. ,password;
  306. email = email.trim();
  307. // email check
  308. // TODO: 削除済みはチェック対象から外そう〜
  309. User.findOne({email: email}, function (err, userData) {
  310. // The user is exists
  311. if (userData) {
  312. createdUserList.push({
  313. email: email,
  314. password: null,
  315. user: null,
  316. });
  317. return next();
  318. }
  319. password = Math.random().toString(36).slice(-16);
  320. newUser.email = email;
  321. newUser.setPassword(password);
  322. newUser.createdAt = Date.now();
  323. newUser.status = STATUS_INVITED;
  324. newUser.save(function(err, userData) {
  325. if (err) {
  326. createdUserList.push({
  327. email: email,
  328. password: null,
  329. user: null,
  330. });
  331. debug('save failed!! ', email);
  332. } else {
  333. createdUserList.push({
  334. email: email,
  335. password: password,
  336. user: userData,
  337. });
  338. debug('saved!', email);
  339. }
  340. next();
  341. });
  342. });
  343. },
  344. function(err) {
  345. if (err) {
  346. debug('error occured while iterate email list');
  347. }
  348. if (toSendEmail) {
  349. // TODO: メール送信部分のロジックをサービス化する
  350. async.each(
  351. createdUserList,
  352. function(user, next) {
  353. if (user.password === null) {
  354. return next();
  355. }
  356. mailer.send({
  357. to: user.email,
  358. subject: 'Invitation to ' + config.crowi['app:title'],
  359. template: 'admin/userInvitation.txt',
  360. vars: {
  361. email: user.email,
  362. password: user.password,
  363. url: config.crowi['app:url'],
  364. appTitle: config.crowi['app:title'],
  365. }
  366. },
  367. function (err, s) {
  368. debug('completed to send email: ', err, s);
  369. next();
  370. }
  371. );
  372. },
  373. function(err) {
  374. debug('Sending invitation email completed.', err);
  375. }
  376. );
  377. }
  378. debug('createdUserList!!! ', createdUserList);
  379. return callback(null, createdUserList);
  380. }
  381. );
  382. };
  383. userSchema.statics.createUserByEmailAndPassword = function(name, username, email, password, callback) {
  384. var User = this
  385. , newUser = new User();
  386. newUser.name = name;
  387. newUser.username = username;
  388. newUser.email = email;
  389. newUser.setPassword(password);
  390. newUser.createdAt = Date.now();
  391. newUser.status = decideUserStatusOnRegistration();
  392. newUser.save(function(err, userData) {
  393. return callback(err, userData);
  394. });
  395. };
  396. userSchema.statics.createUserByFacebook = function(fbUserInfo, callback) {
  397. var User = this
  398. , newUser = new User();
  399. newUser.userId = fbUserInfo.id;
  400. newUser.image = '//graph.facebook.com/' + fbUserInfo.id + '/picture?size=square';
  401. newUser.name = fbUserInfo.name || '';
  402. newUser.username = fbUserInfo.username || '';
  403. newUser.email = fbUserInfo.email || '';
  404. newUser.createdAt = Date.now();
  405. newUser.status = decideUserStatusOnRegistration();
  406. newUser.save(function(err, userData) {
  407. return callback(err, userData);
  408. });
  409. };
  410. userSchema.statics.createUserPictureFilePath = function(user, name) {
  411. var ext = '.' + name.match(/(.*)(?:\.([^.]+$))/)[2];
  412. return 'user/' + user._id + ext;
  413. };
  414. userSchema.statics.STATUS_REGISTERED = STATUS_REGISTERED;
  415. userSchema.statics.STATUS_ACTIVE = STATUS_ACTIVE;
  416. userSchema.statics.STATUS_SUSPENDED = STATUS_SUSPENDED;
  417. userSchema.statics.STATUS_DELETED = STATUS_DELETED;
  418. userSchema.statics.STATUS_INVITED = STATUS_INVITED;
  419. models.User = mongoose.model('User', userSchema);
  420. return models.User;
  421. };