user.js 16 KB

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