user.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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.findUserByApiToken = function(apiToken) {
  248. var self = this;
  249. return new Promise(function(resolve, reject) {
  250. self.findOne({apiToken: apiToken}, function (err, userData) {
  251. if (err) {
  252. return reject(err);
  253. } else {
  254. return resolve(userData);
  255. }
  256. });
  257. });
  258. };
  259. userSchema.statics.findUserByFacebookId = function(fbId, callback) {
  260. this.findOne({userId: fbId}, function (err, userData) {
  261. callback(err, userData);
  262. });
  263. };
  264. userSchema.statics.findUserByGoogleId = function(googleId, callback) {
  265. this.findOne({googleId: googleId}, function (err, userData) {
  266. callback(err, userData);
  267. });
  268. };
  269. userSchema.statics.findUserByEmailAndPassword = function(email, password, callback) {
  270. var hashedPassword = generatePassword(password);
  271. this.findOne({email: email, password: hashedPassword}, function (err, userData) {
  272. callback(err, userData);
  273. });
  274. };
  275. userSchema.statics.isRegisterableUsername = function(username, callback) {
  276. var User = this;
  277. var usernameUsable = true;
  278. this.findOne({username: username}, function (err, userData) {
  279. if (userData) {
  280. usernameUsable = false;
  281. }
  282. return callback(usernameUsable);
  283. });
  284. };
  285. userSchema.statics.isRegisterable = function(email, username, callback) {
  286. var User = this;
  287. var emailUsable = true;
  288. var usernameUsable = true;
  289. // username check
  290. this.findOne({username: username}, function (err, userData) {
  291. if (userData) {
  292. usernameUsable = false;
  293. }
  294. // email check
  295. User.findOne({email: email}, function (err, userData) {
  296. if (userData) {
  297. emailUsable = false;
  298. }
  299. if (!emailUsable || !usernameUsable) {
  300. return callback(false, {email: emailUsable, username: usernameUsable});
  301. }
  302. return callback(true, {});
  303. });
  304. });
  305. };
  306. userSchema.statics.removeCompletelyById = function(id, callback) {
  307. var User = this;
  308. User.findById(id, function (err, userData) {
  309. if (!userData) {
  310. return callback(err, null);
  311. }
  312. debug('Removing user:', userData);
  313. // 物理削除可能なのは、招待中ユーザーのみ
  314. // 利用を一度開始したユーザーは論理削除のみ可能
  315. if (userData.status !== STATUS_INVITED) {
  316. return callback(new Error('Cannot remove completely the user whoes status is not INVITED'), null);
  317. }
  318. userData.remove(function(err) {
  319. if (err) {
  320. return callback(err, null);
  321. }
  322. return callback(null, 1);
  323. });
  324. });
  325. };
  326. userSchema.statics.createUsersByInvitation = function(emailList, toSendEmail, callback) {
  327. var User = this
  328. , createdUserList = []
  329. , config = crowi.getConfig()
  330. , mailer = crowi.getMailer()
  331. ;
  332. if (!Array.isArray(emailList)) {
  333. debug('emailList is not array');
  334. }
  335. async.each(
  336. emailList,
  337. function(email, next) {
  338. var newUser = new User()
  339. ,password;
  340. email = email.trim();
  341. // email check
  342. // TODO: 削除済みはチェック対象から外そう〜
  343. User.findOne({email: email}, function (err, userData) {
  344. // The user is exists
  345. if (userData) {
  346. createdUserList.push({
  347. email: email,
  348. password: null,
  349. user: null,
  350. });
  351. return next();
  352. }
  353. password = Math.random().toString(36).slice(-16);
  354. newUser.email = email;
  355. newUser.setPassword(password);
  356. newUser.createdAt = Date.now();
  357. newUser.status = STATUS_INVITED;
  358. newUser.save(function(err, userData) {
  359. if (err) {
  360. createdUserList.push({
  361. email: email,
  362. password: null,
  363. user: null,
  364. });
  365. debug('save failed!! ', email);
  366. } else {
  367. createdUserList.push({
  368. email: email,
  369. password: password,
  370. user: userData,
  371. });
  372. debug('saved!', email);
  373. }
  374. next();
  375. });
  376. });
  377. },
  378. function(err) {
  379. if (err) {
  380. debug('error occured while iterate email list');
  381. }
  382. if (toSendEmail) {
  383. // TODO: メール送信部分のロジックをサービス化する
  384. async.each(
  385. createdUserList,
  386. function(user, next) {
  387. if (user.password === null) {
  388. return next();
  389. }
  390. mailer.send({
  391. to: user.email,
  392. subject: 'Invitation to ' + config.crowi['app:title'],
  393. template: 'admin/userInvitation.txt',
  394. vars: {
  395. email: user.email,
  396. password: user.password,
  397. url: config.crowi['app:url'],
  398. appTitle: config.crowi['app:title'],
  399. }
  400. },
  401. function (err, s) {
  402. debug('completed to send email: ', err, s);
  403. next();
  404. }
  405. );
  406. },
  407. function(err) {
  408. debug('Sending invitation email completed.', err);
  409. }
  410. );
  411. }
  412. debug('createdUserList!!! ', createdUserList);
  413. return callback(null, createdUserList);
  414. }
  415. );
  416. };
  417. userSchema.statics.createUserByEmailAndPassword = function(name, username, email, password, callback) {
  418. var User = this
  419. , newUser = new User();
  420. newUser.name = name;
  421. newUser.username = username;
  422. newUser.email = email;
  423. newUser.setPassword(password);
  424. newUser.createdAt = Date.now();
  425. newUser.status = decideUserStatusOnRegistration();
  426. newUser.save(function(err, userData) {
  427. return callback(err, userData);
  428. });
  429. };
  430. userSchema.statics.createUserByFacebook = function(fbUserInfo, callback) {
  431. var User = this
  432. , newUser = new User();
  433. newUser.userId = fbUserInfo.id;
  434. newUser.image = '//graph.facebook.com/' + fbUserInfo.id + '/picture?size=square';
  435. newUser.name = fbUserInfo.name || '';
  436. newUser.username = fbUserInfo.username || '';
  437. newUser.email = fbUserInfo.email || '';
  438. newUser.createdAt = Date.now();
  439. newUser.status = decideUserStatusOnRegistration();
  440. newUser.save(function(err, userData) {
  441. return callback(err, userData);
  442. });
  443. };
  444. userSchema.statics.createUserPictureFilePath = function(user, name) {
  445. var ext = '.' + name.match(/(.*)(?:\.([^.]+$))/)[2];
  446. return 'user/' + user._id + ext;
  447. };
  448. userSchema.statics.STATUS_REGISTERED = STATUS_REGISTERED;
  449. userSchema.statics.STATUS_ACTIVE = STATUS_ACTIVE;
  450. userSchema.statics.STATUS_SUSPENDED = STATUS_SUSPENDED;
  451. userSchema.statics.STATUS_DELETED = STATUS_DELETED;
  452. userSchema.statics.STATUS_INVITED = STATUS_INVITED;
  453. return mongoose.model('User', userSchema);
  454. };