user.js 15 KB

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