user.js 15 KB

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