user.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  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. if (Array.isArray(config.crowi['security:registrationWhiteList'])) {
  187. return config.crowi['security:registrationWhiteList'].some(function(allowedEmail) {
  188. var re = new RegExp(allowedEmail + '$');
  189. return re.test(email);
  190. });
  191. }
  192. return true;
  193. };
  194. userSchema.statics.findUsers = function(options, callback) {
  195. var sort = options.sort || {status: 1, createdAt: 1};
  196. this.find()
  197. .sort(sort)
  198. .skip(options.skip || 0)
  199. .limit(options.limit || 21)
  200. .exec(function (err, userData) {
  201. callback(err, userData);
  202. });
  203. };
  204. userSchema.statics.findUsersWithPagination = function(options, callback) {
  205. var sort = options.sort || {status: 1, username: 1, createdAt: 1};
  206. this.paginate({}, options.page || 1, PAGE_ITEMS, function(err, pageCount, paginatedResults, itemCount) {
  207. if (err) {
  208. debug('Error on pagination:', err);
  209. return callback(err, null);
  210. }
  211. return callback(err, paginatedResults, pageCount, itemCount);
  212. }, { sortBy : sort });
  213. };
  214. userSchema.statics.findUserByUsername = function(username, callback) {
  215. this.findOne({username: username}, function (err, userData) {
  216. callback(err, userData);
  217. });
  218. };
  219. userSchema.statics.findUserByFacebookId = function(fbId, callback) {
  220. this.findOne({userId: fbId}, function (err, userData) {
  221. callback(err, userData);
  222. });
  223. };
  224. userSchema.statics.findUserByGoogleId = function(googleId, callback) {
  225. this.findOne({googleId: googleId}, function (err, userData) {
  226. callback(err, userData);
  227. });
  228. };
  229. userSchema.statics.findUserByEmailAndPassword = function(email, password, callback) {
  230. var hashedPassword = generatePassword(password);
  231. this.findOne({email: email, password: hashedPassword}, function (err, userData) {
  232. callback(err, userData);
  233. });
  234. };
  235. userSchema.statics.isRegisterableUsername = function(username, callback) {
  236. var User = this;
  237. var usernameUsable = true;
  238. this.findOne({username: username}, function (err, userData) {
  239. if (userData) {
  240. usernameUsable = false;
  241. }
  242. return callback(usernameUsable);
  243. });
  244. };
  245. userSchema.statics.isRegisterable = function(email, username, callback) {
  246. var User = this;
  247. var emailUsable = true;
  248. var usernameUsable = true;
  249. // username check
  250. this.findOne({username: username}, function (err, userData) {
  251. if (userData) {
  252. usernameUsable = false;
  253. }
  254. // email check
  255. User.findOne({email: email}, function (err, userData) {
  256. if (userData) {
  257. emailUsable = false;
  258. }
  259. if (!emailUsable || !usernameUsable) {
  260. return callback(false, {email: emailUsable, username: usernameUsable});
  261. }
  262. return callback(true, {});
  263. });
  264. });
  265. };
  266. userSchema.statics.removeCompletelyById = function(id, callback) {
  267. var User = this;
  268. User.findById(id, function (err, userData) {
  269. if (!userData) {
  270. return callback(err, null);
  271. }
  272. debug('Removing user:', userData);
  273. // 物理削除可能なのは、招待中ユーザーのみ
  274. // 利用を一度開始したユーザーは論理削除のみ可能
  275. if (userData.status !== STATUS_INVITED) {
  276. return callback(new Error('Cannot remove completely the user whoes status is not INVITED'), null);
  277. }
  278. userData.remove(function(err) {
  279. if (err) {
  280. return callback(err, null);
  281. }
  282. return callback(null, 1);
  283. });
  284. });
  285. };
  286. userSchema.statics.createUsersByInvitation = function(emailList, toSendEmail, callback) {
  287. var User = this
  288. , createdUserList = [];
  289. if (!Array.isArray(emailList)) {
  290. debug('emailList is not array');
  291. }
  292. async.each(
  293. emailList,
  294. function(email, next) {
  295. var newUser = new User()
  296. ,password;
  297. email = email.trim();
  298. // email check
  299. // TODO: 削除済みはチェック対象から外そう〜
  300. User.findOne({email: email}, function (err, userData) {
  301. // The user is exists
  302. if (userData) {
  303. createdUserList.push({
  304. email: email,
  305. password: null,
  306. user: null,
  307. });
  308. return next();
  309. }
  310. password = Math.random().toString(36).slice(-16);
  311. newUser.email = email;
  312. newUser.setPassword(password);
  313. newUser.createdAt = Date.now();
  314. newUser.status = STATUS_INVITED;
  315. newUser.save(function(err, userData) {
  316. if (err) {
  317. createdUserList.push({
  318. email: email,
  319. password: null,
  320. user: null,
  321. });
  322. debug('save failed!! ', email);
  323. } else {
  324. createdUserList.push({
  325. email: email,
  326. password: password,
  327. user: userData,
  328. });
  329. debug('saved!', email);
  330. }
  331. next();
  332. });
  333. });
  334. },
  335. function(err) {
  336. if (err) {
  337. debug('error occured while iterate email list');
  338. }
  339. if (toSendEmail) {
  340. // TODO: メール送信部分のロジックをサービス化する
  341. async.each(
  342. createdUserList,
  343. function(user, next) {
  344. if (user.password === null) {
  345. next();
  346. }
  347. mailer.send({
  348. to: user.email,
  349. subject: 'Invitation to ' + config.crowi['app:title'],
  350. text: 'Hi, ' + user.email + '\n\n'
  351. + 'You are invited to our Wiki, you can log in with following account:\n\n'
  352. + 'Email: ' + user.email + '\n'
  353. + 'Password: ' + user.password
  354. + '\n (This password was auto generated. Update required at the first time you logging in)\n'
  355. + '\n'
  356. + 'We are waiting for you!\n'
  357. + config.crowi['app:url']
  358. },
  359. function (err, s) {
  360. debug('completed to send email: ', err, s);
  361. next();
  362. }
  363. );
  364. },
  365. function(err) {
  366. debug('Sending invitation email completed.', err);
  367. }
  368. );
  369. }
  370. debug('createdUserList!!! ', createdUserList);
  371. return callback(null, createdUserList);
  372. }
  373. );
  374. };
  375. userSchema.statics.createUserByEmailAndPassword = function(name, username, email, password, callback) {
  376. var User = this
  377. , newUser = new User();
  378. newUser.name = name;
  379. newUser.username = username;
  380. newUser.email = email;
  381. newUser.setPassword(password);
  382. newUser.createdAt = Date.now();
  383. newUser.status = decideUserStatusOnRegistration();
  384. newUser.save(function(err, userData) {
  385. return callback(err, userData);
  386. });
  387. };
  388. userSchema.statics.createUserByFacebook = function(fbUserInfo, callback) {
  389. var User = this
  390. , newUser = new User();
  391. newUser.userId = fbUserInfo.id;
  392. newUser.image = '//graph.facebook.com/' + fbUserInfo.id + '/picture?size=square';
  393. newUser.name = fbUserInfo.name || '';
  394. newUser.username = fbUserInfo.username || '';
  395. newUser.email = fbUserInfo.email || '';
  396. newUser.createdAt = Date.now();
  397. newUser.status = decideUserStatusOnRegistration();
  398. newUser.save(function(err, userData) {
  399. return callback(err, userData);
  400. });
  401. };
  402. userSchema.statics.createUserPictureFilePath = function(user, name) {
  403. var ext = '.' + name.match(/(.*)(?:\.([^.]+$))/)[2];
  404. return 'user/' + user._id + ext;
  405. };
  406. userSchema.statics.STATUS_REGISTERED = STATUS_REGISTERED;
  407. userSchema.statics.STATUS_ACTIVE = STATUS_ACTIVE;
  408. userSchema.statics.STATUS_SUSPENDED = STATUS_SUSPENDED;
  409. userSchema.statics.STATUS_DELETED = STATUS_DELETED;
  410. userSchema.statics.STATUS_INVITED = STATUS_INVITED;
  411. models.User = mongoose.model('User', userSchema);
  412. return models.User;
  413. };