user.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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. , PAGE_ITEMS = 20
  14. , userSchema;
  15. userSchema = new mongoose.Schema({
  16. userId: String,
  17. fbId: String, // userId
  18. image: String,
  19. googleId: String,
  20. name: { type: String },
  21. username: { type: String },
  22. email: { type: String, required: true },
  23. password: String,
  24. status: { type: Number, required: true, default: STATUS_ACTIVE },
  25. createdAt: { type: Date, default: Date.now },
  26. admin: { type: Boolean, default: 0 }
  27. });
  28. userSchema.plugin(mongoosePaginate);
  29. function decideUserStatusOnRegistration () {
  30. var Config = crowi.model('Config'),
  31. config = crowi.getConfig();
  32. // status decided depends on registrationMode
  33. switch (config.crowi['security:registrationMode']) {
  34. case Config.SECURITY_REGISTRATION_MODE_OPEN:
  35. return STATUS_ACTIVE;
  36. case Config.SECURITY_REGISTRATION_MODE_RESTRICTED:
  37. case Config.SECURITY_REGISTRATION_MODE_CLOSED: // 一応
  38. return STATUS_REGISTERED;
  39. default:
  40. return STATUS_ACTIVE; // どっちにすんのがいいんだろうな
  41. }
  42. }
  43. function generatePassword (password) {
  44. var hasher = crypto.createHash('sha256');
  45. hasher.update(process.env.PASSWORD_SEED + password);
  46. return hasher.digest('hex');
  47. }
  48. userSchema.methods.isPasswordSet = function() {
  49. if (this.password) {
  50. return true;
  51. }
  52. return false;
  53. };
  54. userSchema.methods.isPasswordValid = function(password) {
  55. return this.password == generatePassword(password);
  56. };
  57. userSchema.methods.setPassword = function(password) {
  58. return this.password == generatePassword(password);
  59. };
  60. userSchema.methods.setPassword = function(password) {
  61. this.password = generatePassword(password);
  62. return this;
  63. };
  64. userSchema.methods.isEmailSet = function() {
  65. if (this.email) {
  66. return true;
  67. }
  68. return false;
  69. };
  70. userSchema.methods.update = function(name, email, callback) {
  71. this.name = name;
  72. this.email = email;
  73. this.save(function(err, userData) {
  74. return callback(err, userData);
  75. });
  76. };
  77. userSchema.methods.updatePassword = function(password, callback) {
  78. this.setPassword(password);
  79. this.save(function(err, userData) {
  80. return callback(err, userData);
  81. });
  82. };
  83. userSchema.methods.updateImage = function(image, callback) {
  84. this.image = image;
  85. this.save(function(err, userData) {
  86. return callback(err, userData);
  87. });
  88. };
  89. userSchema.methods.deleteImage = function(callback) {
  90. return this.updateImage(null, callback);
  91. };
  92. userSchema.methods.updateFacebookId = function(fbId, callback) {
  93. this.fbId = this.userId = fbId;
  94. this.save(function(err, userData) {
  95. return callback(err, userData);
  96. });
  97. };
  98. userSchema.methods.deleteFacebookId = function(callback) {
  99. return this.updateFacebookId(null, callback);
  100. };
  101. userSchema.methods.updateGoogleId = function(googleId, callback) {
  102. this.googleId = googleId;
  103. this.save(function(err, userData) {
  104. return callback(err, userData);
  105. });
  106. };
  107. userSchema.methods.deleteGoogleId = function(callback) {
  108. return this.updateGoogleId(null, callback);
  109. };
  110. userSchema.methods.activateInvitedUser = function(username, name, password, callback) {
  111. this.setPassword(password);
  112. this.name = name;
  113. this.username = username;
  114. this.status = STATUS_ACTIVE;
  115. this.save(function(err, userData) {
  116. return callback(err, userData);
  117. });
  118. };
  119. userSchema.methods.removeFromAdmin = function(callback) {
  120. debug('Remove from admin', this);
  121. this.admin = 0;
  122. this.save(function(err, userData) {
  123. return callback(err, userData);
  124. });
  125. };
  126. userSchema.methods.makeAdmin = function(callback) {
  127. debug('Admin', this);
  128. this.admin = 1;
  129. this.save(function(err, userData) {
  130. return callback(err, userData);
  131. });
  132. };
  133. userSchema.methods.statusActivate = function(callback) {
  134. debug('Activate User', this);
  135. this.status = STATUS_ACTIVE;
  136. this.save(function(err, userData) {
  137. return callback(err, userData);
  138. });
  139. };
  140. userSchema.methods.statusSuspend = function(callback) {
  141. debug('Suspend User', this);
  142. this.status = STATUS_SUSPENDED;
  143. if (this.email === undefined || this.email === null) { // migrate old data
  144. this.email = '-';
  145. }
  146. if (this.name === undefined || this.name === null) { // migrate old data
  147. this.name = '-' + Date.now();
  148. }
  149. if (this.username === undefined || this.usename === null) { // migrate old data
  150. this.username = '-';
  151. }
  152. this.save(function(err, userData) {
  153. return callback(err, userData);
  154. });
  155. };
  156. userSchema.methods.statusDelete = function(callback) {
  157. debug('Delete User', this);
  158. this.status = STATUS_DELETED;
  159. this.password = '';
  160. this.email = 'deleted@deleted';
  161. this.googleId = null;
  162. this.fbId = null;
  163. this.image = null;
  164. this.save(function(err, userData) {
  165. return callback(err, userData);
  166. });
  167. };
  168. userSchema.methods.updateGoogleIdAndFacebookId = function(googleId, facebookId, callback) {
  169. this.googleId = googleId;
  170. this.fbId = this.userId = facebookId;
  171. this.save(function(err, userData) {
  172. return callback(err, userData);
  173. });
  174. };
  175. userSchema.statics.getUserStatusLabels = function() {
  176. var userStatus = {};
  177. userStatus[STATUS_REGISTERED] = '承認待ち';
  178. userStatus[STATUS_ACTIVE] = 'Active';
  179. userStatus[STATUS_SUSPENDED] = 'Suspended';
  180. userStatus[STATUS_DELETED] = 'Deleted';
  181. userStatus[STATUS_INVITED] = '招待済み';
  182. return userStatus;
  183. };
  184. userSchema.statics.isEmailValid = function(email, callback) {
  185. var config = crowi.getConfig()
  186. , 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. , config = crowi.getConfig()
  299. , mailer = crowi.getMailer()
  300. ;
  301. if (!Array.isArray(emailList)) {
  302. debug('emailList is not array');
  303. }
  304. async.each(
  305. emailList,
  306. function(email, next) {
  307. var newUser = new User()
  308. ,password;
  309. email = email.trim();
  310. // email check
  311. // TODO: 削除済みはチェック対象から外そう〜
  312. User.findOne({email: email}, function (err, userData) {
  313. // The user is exists
  314. if (userData) {
  315. createdUserList.push({
  316. email: email,
  317. password: null,
  318. user: null,
  319. });
  320. return next();
  321. }
  322. password = Math.random().toString(36).slice(-16);
  323. newUser.email = email;
  324. newUser.setPassword(password);
  325. newUser.createdAt = Date.now();
  326. newUser.status = STATUS_INVITED;
  327. newUser.save(function(err, userData) {
  328. if (err) {
  329. createdUserList.push({
  330. email: email,
  331. password: null,
  332. user: null,
  333. });
  334. debug('save failed!! ', email);
  335. } else {
  336. createdUserList.push({
  337. email: email,
  338. password: password,
  339. user: userData,
  340. });
  341. debug('saved!', email);
  342. }
  343. next();
  344. });
  345. });
  346. },
  347. function(err) {
  348. if (err) {
  349. debug('error occured while iterate email list');
  350. }
  351. if (toSendEmail) {
  352. // TODO: メール送信部分のロジックをサービス化する
  353. async.each(
  354. createdUserList,
  355. function(user, next) {
  356. if (user.password === null) {
  357. return next();
  358. }
  359. mailer.send({
  360. to: user.email,
  361. subject: 'Invitation to ' + config.crowi['app:title'],
  362. template: 'admin/userInvitation.txt',
  363. vars: {
  364. email: user.email,
  365. password: user.password,
  366. url: config.crowi['app:url'],
  367. appTitle: config.crowi['app:title'],
  368. }
  369. },
  370. function (err, s) {
  371. debug('completed to send email: ', err, s);
  372. next();
  373. }
  374. );
  375. },
  376. function(err) {
  377. debug('Sending invitation email completed.', err);
  378. }
  379. );
  380. }
  381. debug('createdUserList!!! ', createdUserList);
  382. return callback(null, createdUserList);
  383. }
  384. );
  385. };
  386. userSchema.statics.createUserByEmailAndPassword = function(name, username, email, password, callback) {
  387. var User = this
  388. , newUser = new User();
  389. newUser.name = name;
  390. newUser.username = username;
  391. newUser.email = email;
  392. newUser.setPassword(password);
  393. newUser.createdAt = Date.now();
  394. newUser.status = decideUserStatusOnRegistration();
  395. newUser.save(function(err, userData) {
  396. return callback(err, userData);
  397. });
  398. };
  399. userSchema.statics.createUserByFacebook = function(fbUserInfo, callback) {
  400. var User = this
  401. , newUser = new User();
  402. newUser.userId = fbUserInfo.id;
  403. newUser.image = '//graph.facebook.com/' + fbUserInfo.id + '/picture?size=square';
  404. newUser.name = fbUserInfo.name || '';
  405. newUser.username = fbUserInfo.username || '';
  406. newUser.email = fbUserInfo.email || '';
  407. newUser.createdAt = Date.now();
  408. newUser.status = decideUserStatusOnRegistration();
  409. newUser.save(function(err, userData) {
  410. return callback(err, userData);
  411. });
  412. };
  413. userSchema.statics.createUserPictureFilePath = function(user, name) {
  414. var ext = '.' + name.match(/(.*)(?:\.([^.]+$))/)[2];
  415. return 'user/' + user._id + ext;
  416. };
  417. userSchema.statics.STATUS_REGISTERED = STATUS_REGISTERED;
  418. userSchema.statics.STATUS_ACTIVE = STATUS_ACTIVE;
  419. userSchema.statics.STATUS_SUSPENDED = STATUS_SUSPENDED;
  420. userSchema.statics.STATUS_DELETED = STATUS_DELETED;
  421. userSchema.statics.STATUS_INVITED = STATUS_INVITED;
  422. return mongoose.model('User', userSchema);
  423. };