user.js 14 KB

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