user.js 15 KB

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