user.js 16 KB

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