user.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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.removeFromAdmin = function(callback) {
  112. debug('Remove from admin', this);
  113. this.admin = 0;
  114. this.save(function(err, userData) {
  115. return callback(err, userData);
  116. });
  117. };
  118. userSchema.methods.makeAdmin = function(callback) {
  119. debug('Admin', this);
  120. this.admin = 1;
  121. this.save(function(err, userData) {
  122. return callback(err, userData);
  123. });
  124. };
  125. userSchema.methods.statusActivate = function(callback) {
  126. debug('Activate User', this);
  127. this.status = STATUS_ACTIVE;
  128. this.save(function(err, userData) {
  129. return callback(err, userData);
  130. });
  131. };
  132. userSchema.methods.statusSuspend = function(callback) {
  133. debug('Suspend User', this);
  134. this.status = STATUS_SUSPENDED;
  135. if (this.email === undefined || this.email === null) { // migrate old data
  136. this.email = '-';
  137. }
  138. if (this.name === undefined || this.name === null) { // migrate old data
  139. this.name = '-' + Date.now();
  140. }
  141. if (this.username === undefined || this.usename === null) { // migrate old data
  142. this.username = '-';
  143. }
  144. this.save(function(err, userData) {
  145. return callback(err, userData);
  146. });
  147. };
  148. userSchema.methods.statusDelete = function(callback) {
  149. debug('Delete User', this);
  150. this.status = STATUS_DELETED;
  151. this.password = '';
  152. this.email = 'deleted@deleted';
  153. this.googleId = null;
  154. this.fbId = null;
  155. this.image = null;
  156. this.save(function(err, userData) {
  157. return callback(err, userData);
  158. });
  159. };
  160. userSchema.methods.updateGoogleIdAndFacebookId = function(googleId, facebookId, callback) {
  161. this.googleId = googleId;
  162. this.fbId = this.userId = facebookId;
  163. this.save(function(err, userData) {
  164. return callback(err, userData);
  165. });
  166. };
  167. userSchema.statics.getUserStatusLabels = function() {
  168. var userStatus = {};
  169. userStatus[STATUS_REGISTERED] = '承認待ち';
  170. userStatus[STATUS_ACTIVE] = 'Active';
  171. userStatus[STATUS_SUSPENDED] = 'Suspended';
  172. userStatus[STATUS_DELETED] = 'Deleted';
  173. userStatus[STATUS_INVITED] = '招待済み';
  174. return userStatus;
  175. };
  176. userSchema.statics.isEmailValid = function(email, callback) {
  177. if (Array.isArray(config.crowi['security:registrationWhiteList'])) {
  178. return config.crowi['security:registrationWhiteList'].some(function(allowedEmail) {
  179. var re = new RegExp(allowedEmail + '$');
  180. return re.test(email);
  181. });
  182. }
  183. return true;
  184. };
  185. userSchema.statics.findUsers = function(options, callback) {
  186. var sort = options.sort || {status: 1, createdAt: 1};
  187. this.find()
  188. .sort(sort)
  189. .skip(options.skip || 0)
  190. .limit(options.limit || 21)
  191. .exec(function (err, userData) {
  192. callback(err, userData);
  193. });
  194. };
  195. userSchema.statics.findUsersWithPagination = function(options, callback) {
  196. var sort = options.sort || {status: 1, username: 1, createdAt: 1};
  197. this.paginate({}, options.page || 1, PAGE_ITEMS, function(err, pageCount, paginatedResults, itemCount) {
  198. if (err) {
  199. debug('Error on pagination:', err);
  200. return callback(err, null);
  201. }
  202. return callback(err, paginatedResults, pageCount, itemCount);
  203. }, { sortBy : sort });
  204. };
  205. userSchema.statics.findUserByUsername = function(username, callback) {
  206. this.findOne({username: username}, function (err, userData) {
  207. callback(err, userData);
  208. });
  209. };
  210. userSchema.statics.findUserByFacebookId = function(fbId, callback) {
  211. this.findOne({userId: fbId}, function (err, userData) {
  212. callback(err, userData);
  213. });
  214. };
  215. userSchema.statics.findUserByGoogleId = function(googleId, callback) {
  216. this.findOne({googleId: googleId}, function (err, userData) {
  217. callback(err, userData);
  218. });
  219. };
  220. userSchema.statics.findUserByEmailAndPassword = function(email, password, callback) {
  221. var hashedPassword = generatePassword(password);
  222. this.findOne({email: email, password: hashedPassword}, function (err, userData) {
  223. callback(err, userData);
  224. });
  225. };
  226. userSchema.statics.isRegisterable = function(email, username, callback) {
  227. var User = this;
  228. var emailUsable = true;
  229. var usernameUsable = true;
  230. // username check
  231. this.findOne({username: username}, function (err, userData) {
  232. if (userData) {
  233. usernameUsable = false;
  234. }
  235. // email check
  236. User.findOne({email: email}, function (err, userData) {
  237. if (userData) {
  238. emailUsable = false;
  239. }
  240. if (!emailUsable || !usernameUsable) {
  241. return callback(false, {email: emailUsable, username: usernameUsable});
  242. }
  243. return callback(true, {});
  244. });
  245. });
  246. };
  247. userSchema.statics.removeCompletelyById = function(id, callback) {
  248. var User = this;
  249. User.findById(id, function (err, userData) {
  250. if (!userData) {
  251. return callback(err, null);
  252. }
  253. debug('Removing user:', userData);
  254. // 物理削除可能なのは、招待中ユーザーのみ
  255. // 利用を一度開始したユーザーは論理削除のみ可能
  256. if (userData.status !== STATUS_INVITED) {
  257. return callback(new Error('Cannot remove completely the user whoes status is not INVITED'), null);
  258. }
  259. userData.remove(function(err) {
  260. if (err) {
  261. return callback(err, null);
  262. }
  263. return callback(null, 1);
  264. });
  265. });
  266. };
  267. userSchema.statics.createUsersByInvitation = function(emailList, toSendEmail, callback) {
  268. var User = this
  269. , createdUserList = [];
  270. if (!Array.isArray(emailList)) {
  271. debug('emailList is not array');
  272. }
  273. async.each(
  274. emailList,
  275. function(email, next) {
  276. var newUser = new User()
  277. ,password;
  278. email = email.trim();
  279. // email check
  280. // TODO: 削除済みはチェック対象から外そう〜
  281. User.findOne({email: email}, function (err, userData) {
  282. // The user is exists
  283. if (userData) {
  284. createdUserList.push({
  285. email: email,
  286. password: null,
  287. user: null,
  288. });
  289. return next();
  290. }
  291. password = Math.random().toString(36).slice(-16);
  292. newUser.email = email;
  293. newUser.setPassword(password);
  294. newUser.createdAt = Date.now();
  295. newUser.status = STATUS_INVITED;
  296. newUser.save(function(err, userData) {
  297. if (err) {
  298. createdUserList.push({
  299. email: email,
  300. password: null,
  301. user: null,
  302. });
  303. debug('save failed!! ', email);
  304. } else {
  305. createdUserList.push({
  306. email: email,
  307. password: password,
  308. user: userData,
  309. });
  310. debug('saved!', email);
  311. }
  312. next();
  313. });
  314. });
  315. },
  316. function(err) {
  317. if (err) {
  318. debug('error occured while iterate email list');
  319. }
  320. if (toSendEmail) {
  321. // TODO: メール送信部分のロジックをサービス化する
  322. async.each(
  323. createdUserList,
  324. function(user, next) {
  325. if (user.password === null) {
  326. next();
  327. }
  328. mailer.send({
  329. to: user.email,
  330. subject: 'Invitation to ' + config.crowi['app:title'],
  331. text: 'Hi, ' + user.email + '\n\n'
  332. + 'You are invited to our Wiki, you can log in with following account:\n\n'
  333. + 'Email: ' + user.email + '\n'
  334. + 'Password: ' + user.password
  335. + '\n (This password was auto generated. Update required at the first time you logging in)\n'
  336. + '\n'
  337. + 'We are waiting for you!\n'
  338. + config.crowi['app:url']
  339. },
  340. function (err, s) {
  341. debug('completed to send email: ', err, s);
  342. next();
  343. }
  344. );
  345. },
  346. function(err) {
  347. debug('Sending invitation email completed.', err);
  348. }
  349. );
  350. }
  351. debug('createdUserList!!! ', createdUserList);
  352. return callback(null, createdUserList);
  353. }
  354. );
  355. };
  356. userSchema.statics.createUserByEmailAndPassword = function(name, username, email, password, callback) {
  357. var User = this
  358. , newUser = new User();
  359. newUser.name = name;
  360. newUser.username = username;
  361. newUser.email = email;
  362. newUser.setPassword(password);
  363. newUser.createdAt = Date.now();
  364. newUser.status = decideUserStatusOnRegistration();
  365. newUser.save(function(err, userData) {
  366. return callback(err, userData);
  367. });
  368. };
  369. userSchema.statics.createUserByFacebook = function(fbUserInfo, callback) {
  370. var User = this
  371. , newUser = new User();
  372. newUser.userId = fbUserInfo.id;
  373. newUser.image = '//graph.facebook.com/' + fbUserInfo.id + '/picture?size=square';
  374. newUser.name = fbUserInfo.name || '';
  375. newUser.username = fbUserInfo.username || '';
  376. newUser.email = fbUserInfo.email || '';
  377. newUser.createdAt = Date.now();
  378. newUser.status = decideUserStatusOnRegistration();
  379. newUser.save(function(err, userData) {
  380. return callback(err, userData);
  381. });
  382. };
  383. userSchema.statics.createUserPictureFilePath = function(user, name) {
  384. var ext = '.' + name.match(/(.*)(?:\.([^.]+$))/)[2];
  385. return 'user/' + user._id + ext;
  386. };
  387. userSchema.statics.STATUS_REGISTERED = STATUS_REGISTERED;
  388. userSchema.statics.STATUS_ACTIVE = STATUS_ACTIVE;
  389. userSchema.statics.STATUS_SUSPENDED = STATUS_SUSPENDED;
  390. userSchema.statics.STATUS_DELETED = STATUS_DELETED;
  391. userSchema.statics.STATUS_INVITED = STATUS_INVITED;
  392. models.User = mongoose.model('User', userSchema);
  393. return models.User;
  394. };