user.js 14 KB

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