user.js 16 KB

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