user.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  1. module.exports = function(crowi) {
  2. var debug = require('debug')('crowi:models:user')
  3. , mongoose = require('mongoose')
  4. , mongoosePaginate = require('mongoose-paginate')
  5. , uniqueValidator = require('mongoose-unique-validator')
  6. , crypto = require('crypto')
  7. , async = require('async')
  8. , ObjectId = mongoose.Schema.Types.ObjectId
  9. , STATUS_REGISTERED = 1
  10. , STATUS_ACTIVE = 2
  11. , STATUS_SUSPENDED = 3
  12. , STATUS_DELETED = 4
  13. , STATUS_INVITED = 5
  14. , USER_PUBLIC_FIELDS = '_id image isGravatarEnabled googleId name username email introduction status lang createdAt admin' // TODO: どこか別の場所へ...
  15. , LANG_EN = 'en'
  16. , LANG_EN_US = 'en-US'
  17. , LANG_EN_GB = 'en-GB'
  18. , LANG_JA = 'ja'
  19. , PAGE_ITEMS = 50
  20. , userEvent = crowi.event('user')
  21. , userSchema;
  22. userSchema = new mongoose.Schema({
  23. userId: String,
  24. image: String,
  25. isGravatarEnabled: { type: Boolean, default: false },
  26. googleId: String,
  27. name: { type: String },
  28. username: { type: String, required: true, unique: true },
  29. email: { type: String, unique: true, sparse: true },
  30. //// The official settings
  31. // username: { type: String, index: true },
  32. // email: { type: String, required: true, index: true },
  33. //// crowi-plus (>= 2.1.0, <2.3.0) settings
  34. // email: { type: String, required: true, unique: true },
  35. introduction: { type: String },
  36. password: String,
  37. apiToken: String,
  38. lang: {
  39. type: String,
  40. enum: Object.keys(getLanguageLabels()).map((k) => eval(k)),
  41. default: LANG_EN_US
  42. },
  43. status: { type: Number, required: true, default: STATUS_ACTIVE, index: true },
  44. createdAt: { type: Date, default: Date.now },
  45. lastLoginAt: { type: Date },
  46. admin: { type: Boolean, default: 0, index: true }
  47. });
  48. userSchema.plugin(mongoosePaginate);
  49. userSchema.plugin(uniqueValidator);
  50. userEvent.on('activated', userEvent.onActivated);
  51. function decideUserStatusOnRegistration () {
  52. var Config = crowi.model('Config'),
  53. config = crowi.getConfig();
  54. if (!config.crowi) {
  55. return STATUS_ACTIVE; // is this ok?
  56. }
  57. // status decided depends on registrationMode
  58. switch (config.crowi['security:registrationMode']) {
  59. case Config.SECURITY_REGISTRATION_MODE_OPEN:
  60. return STATUS_ACTIVE;
  61. case Config.SECURITY_REGISTRATION_MODE_RESTRICTED:
  62. case Config.SECURITY_REGISTRATION_MODE_CLOSED: // 一応
  63. return STATUS_REGISTERED;
  64. default:
  65. return STATUS_ACTIVE; // どっちにすんのがいいんだろうな
  66. }
  67. }
  68. function generateRandomEmail() {
  69. const randomstr = generateRandomTempPassword();
  70. return `change-it-${randomstr}@example.com`
  71. }
  72. function generateRandomTempPassword () {
  73. var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!=-_';
  74. var password = '';
  75. var len = 12;
  76. for (var i = 0; i < len; i++) {
  77. var randomPoz = Math.floor(Math.random() * chars.length);
  78. password += chars.substring(randomPoz, randomPoz+1);
  79. }
  80. return password;
  81. }
  82. function generatePassword (password) {
  83. var hasher = crypto.createHash('sha256');
  84. hasher.update(crowi.env.PASSWORD_SEED + password);
  85. return hasher.digest('hex');
  86. }
  87. function generateApiToken (user) {
  88. var hasher = crypto.createHash('sha256');
  89. hasher.update((new Date).getTime() + user._id);
  90. return hasher.digest('base64');
  91. }
  92. function getLanguageLabels() {
  93. var lang = {};
  94. lang.LANG_EN = LANG_EN;
  95. lang.LANG_EN_US = LANG_EN_US;
  96. lang.LANG_EN_GB = LANG_EN_GB;
  97. lang.LANG_JA = LANG_JA;
  98. return lang;
  99. }
  100. userSchema.methods.isPasswordSet = function() {
  101. if (this.password) {
  102. return true;
  103. }
  104. return false;
  105. };
  106. userSchema.methods.isPasswordValid = function(password) {
  107. return this.password == generatePassword(password);
  108. };
  109. userSchema.methods.setPassword = function(password) {
  110. this.password = generatePassword(password);
  111. return this;
  112. };
  113. userSchema.methods.isEmailSet = function() {
  114. if (this.email) {
  115. return true;
  116. }
  117. return false;
  118. };
  119. userSchema.methods.updateLastLoginAt = function(lastLoginAt, callback) {
  120. this.lastLoginAt = lastLoginAt;
  121. this.save(function(err, userData) {
  122. return callback(err, userData);
  123. });
  124. };
  125. userSchema.methods.updateIsGravatarEnabled = function(isGravatarEnabled, callback) {
  126. this.isGravatarEnabled = isGravatarEnabled;
  127. this.save(function(err, userData) {
  128. return callback(err, userData);
  129. });
  130. };
  131. userSchema.methods.updatePassword = function(password, callback) {
  132. this.setPassword(password);
  133. this.save(function(err, userData) {
  134. return callback(err, userData);
  135. });
  136. };
  137. userSchema.methods.updateApiToken = function(callback) {
  138. var self = this;
  139. self.apiToken = generateApiToken(this);
  140. return new Promise(function(resolve, reject) {
  141. self.save(function(err, userData) {
  142. if (err) {
  143. return reject(err);
  144. } else {
  145. return resolve(userData);
  146. }
  147. });
  148. });
  149. };
  150. userSchema.methods.updateImage = function(image, callback) {
  151. this.image = image;
  152. this.save(function(err, userData) {
  153. return callback(err, userData);
  154. });
  155. };
  156. userSchema.methods.deleteImage = function(callback) {
  157. return this.updateImage(null, callback);
  158. };
  159. userSchema.methods.updateGoogleId = function(googleId, callback) {
  160. this.googleId = googleId;
  161. this.save(function(err, userData) {
  162. return callback(err, userData);
  163. });
  164. };
  165. userSchema.methods.deleteGoogleId = function(callback) {
  166. return this.updateGoogleId(null, callback);
  167. };
  168. userSchema.methods.activateInvitedUser = function(username, name, password, callback) {
  169. this.setPassword(password);
  170. this.name = name;
  171. this.username = username;
  172. this.status = STATUS_ACTIVE;
  173. this.save(function(err, userData) {
  174. userEvent.emit('activated', userData);
  175. return callback(err, userData);
  176. });
  177. };
  178. userSchema.methods.removeFromAdmin = function(callback) {
  179. debug('Remove from admin', this);
  180. this.admin = 0;
  181. this.save(function(err, userData) {
  182. return callback(err, userData);
  183. });
  184. };
  185. userSchema.methods.makeAdmin = function(callback) {
  186. debug('Admin', this);
  187. this.admin = 1;
  188. this.save(function(err, userData) {
  189. return callback(err, userData);
  190. });
  191. };
  192. userSchema.methods.statusActivate = function(callback) {
  193. debug('Activate User', this);
  194. this.status = STATUS_ACTIVE;
  195. this.save(function(err, userData) {
  196. userEvent.emit('activated', userData);
  197. return callback(err, userData);
  198. });
  199. };
  200. userSchema.methods.statusSuspend = function(callback) {
  201. debug('Suspend User', this);
  202. this.status = STATUS_SUSPENDED;
  203. if (this.email === undefined || this.email === null) { // migrate old data
  204. this.email = '-';
  205. }
  206. if (this.name === undefined || this.name === null) { // migrate old data
  207. this.name = '-' + Date.now();
  208. }
  209. if (this.username === undefined || this.usename === null) { // migrate old data
  210. this.username = '-';
  211. }
  212. this.save(function(err, userData) {
  213. return callback(err, userData);
  214. });
  215. };
  216. userSchema.methods.statusDelete = function(callback) {
  217. debug('Delete User', this);
  218. const now = new Date();
  219. const deletedLabel = `deleted_at_${now.getTime()}`;
  220. this.status = STATUS_DELETED;
  221. this.username = deletedLabel;
  222. this.password = '';
  223. this.name = '';
  224. this.email = `${deletedLabel}@deleted`;
  225. this.googleId = null;
  226. this.isGravatarEnabled = false;
  227. this.image = null;
  228. this.save(function(err, userData) {
  229. return callback(err, userData);
  230. });
  231. };
  232. userSchema.methods.updateGoogleId = function(googleId, callback) {
  233. this.googleId = googleId;
  234. this.save(function(err, userData) {
  235. return callback(err, userData);
  236. });
  237. };
  238. userSchema.statics.getLanguageLabels = getLanguageLabels;
  239. userSchema.statics.getUserStatusLabels = function() {
  240. var userStatus = {};
  241. userStatus[STATUS_REGISTERED] = '承認待ち';
  242. userStatus[STATUS_ACTIVE] = 'Active';
  243. userStatus[STATUS_SUSPENDED] = 'Suspended';
  244. userStatus[STATUS_DELETED] = 'Deleted';
  245. userStatus[STATUS_INVITED] = '招待済み';
  246. return userStatus;
  247. };
  248. userSchema.statics.isEmailValid = function(email, callback) {
  249. var config = crowi.getConfig()
  250. , whitelist = config.crowi['security:registrationWhiteList'];
  251. if (Array.isArray(whitelist) && whitelist.length > 0) {
  252. return config.crowi['security:registrationWhiteList'].some(function(allowedEmail) {
  253. var re = new RegExp(allowedEmail + '$');
  254. return re.test(email);
  255. });
  256. }
  257. return true;
  258. };
  259. userSchema.statics.filterToPublicFields = function(user) {
  260. debug('User is', typeof user, user);
  261. if (typeof user !== 'object' || !user._id) {
  262. return user;
  263. }
  264. var filteredUser = {};
  265. var fields = USER_PUBLIC_FIELDS.split(' ');
  266. for (var i = 0; i < fields.length; i++) {
  267. var key = fields[i];
  268. if (user[key]) {
  269. filteredUser[key] = user[key];
  270. }
  271. }
  272. return filteredUser;
  273. };
  274. userSchema.statics.findUsers = function(options, callback) {
  275. var sort = options.sort || {status: 1, createdAt: 1};
  276. this.find()
  277. .sort(sort)
  278. .skip(options.skip || 0)
  279. .limit(options.limit || 21)
  280. .exec(function (err, userData) {
  281. callback(err, userData);
  282. });
  283. };
  284. userSchema.statics.findAllUsers = function(option) {
  285. var User = this;
  286. var option = option || {}
  287. , sort = option.sort || {createdAt: -1}
  288. , status = option.status || [STATUS_ACTIVE, STATUS_SUSPENDED]
  289. , fields = option.fields || USER_PUBLIC_FIELDS
  290. ;
  291. if (!Array.isArray(status)) {
  292. status = [status];
  293. }
  294. return new Promise(function(resolve, reject) {
  295. User
  296. .find()
  297. .or(status.map(s => { return {status: s}; }))
  298. .select(fields)
  299. .sort(sort)
  300. .exec(function (err, userData) {
  301. if (err) {
  302. return reject(err);
  303. }
  304. return resolve(userData);
  305. });
  306. });
  307. };
  308. userSchema.statics.findUsersByIds = function(ids, option) {
  309. var User = this;
  310. var option = option || {}
  311. , sort = option.sort || {createdAt: -1}
  312. , status = option.status || STATUS_ACTIVE
  313. , fields = option.fields || USER_PUBLIC_FIELDS
  314. ;
  315. return new Promise(function(resolve, reject) {
  316. User
  317. .find({ _id: { $in: ids }, status: status })
  318. .select(fields)
  319. .sort(sort)
  320. .exec(function (err, userData) {
  321. if (err) {
  322. return reject(err);
  323. }
  324. return resolve(userData);
  325. });
  326. });
  327. };
  328. userSchema.statics.findAdmins = function(callback) {
  329. var User = this;
  330. this.find({admin: true})
  331. .exec(function(err, admins) {
  332. debug('Admins: ', admins);
  333. callback(err, admins);
  334. });
  335. };
  336. userSchema.statics.findUsersWithPagination = function(options, callback) {
  337. var sort = options.sort || {status: 1, username: 1, createdAt: 1};
  338. this.paginate({status: { $ne: STATUS_DELETED }}, { page: options.page || 1, limit: options.limit || PAGE_ITEMS }, function(err, result) {
  339. if (err) {
  340. debug('Error on pagination:', err);
  341. return callback(err, null);
  342. }
  343. return callback(err, result);
  344. }, { sortBy : sort });
  345. };
  346. userSchema.statics.findUsersByPartOfEmail = function(emailPart, options) {
  347. const status = options.status || null;
  348. const emailPartRegExp = new RegExp(emailPart.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'));
  349. const User = this;
  350. return new Promise((resolve, reject) => {
  351. const query = User.find({ email: emailPartRegExp }, USER_PUBLIC_FIELDS);
  352. if (status) {
  353. query.and({status});
  354. }
  355. query
  356. .limit(PAGE_ITEMS + 1)
  357. .exec((err, userData) => {
  358. if (err) {
  359. return reject(err);
  360. }
  361. return resolve(userData);
  362. });
  363. });
  364. };
  365. userSchema.statics.findUserByUsername = function(username) {
  366. if (username == null) {
  367. return Promise.resolve(null);
  368. }
  369. return this.findOne({username});
  370. };
  371. userSchema.statics.findUserByApiToken = function(apiToken) {
  372. if (apiToken == null) {
  373. return Promise.resolve(null);
  374. }
  375. return this.findOne({apiToken});
  376. };
  377. userSchema.statics.findUserByGoogleId = function(googleId, callback) {
  378. if (googleId == null) {
  379. callback(null, null);
  380. }
  381. this.findOne({googleId}, function (err, userData) {
  382. callback(err, userData);
  383. });
  384. };
  385. userSchema.statics.findUserByUsernameOrEmail = function(usernameOrEmail, password, callback) {
  386. this.findOne()
  387. .or([
  388. {username: usernameOrEmail},
  389. {email: usernameOrEmail},
  390. ])
  391. .exec((err, userData) => {
  392. callback(err, userData);
  393. });
  394. };
  395. userSchema.statics.findUserByEmailAndPassword = function(email, password, callback) {
  396. var hashedPassword = generatePassword(password);
  397. this.findOne({email: email, password: hashedPassword}, function (err, userData) {
  398. callback(err, userData);
  399. });
  400. };
  401. userSchema.statics.isRegisterableUsername = function(username, callback) {
  402. var User = this;
  403. var usernameUsable = true;
  404. this.findOne({username: username}, function (err, userData) {
  405. if (userData) {
  406. usernameUsable = false;
  407. }
  408. return callback(usernameUsable);
  409. });
  410. };
  411. userSchema.statics.isRegisterable = function(email, username, callback) {
  412. var User = this;
  413. var emailUsable = true;
  414. var usernameUsable = true;
  415. // username check
  416. this.findOne({username: username}, function (err, userData) {
  417. if (userData) {
  418. usernameUsable = false;
  419. }
  420. // email check
  421. User.findOne({email: email}, function (err, userData) {
  422. if (userData) {
  423. emailUsable = false;
  424. }
  425. if (!emailUsable || !usernameUsable) {
  426. return callback(false, {email: emailUsable, username: usernameUsable});
  427. }
  428. return callback(true, {});
  429. });
  430. });
  431. };
  432. userSchema.statics.removeCompletelyById = function(id, callback) {
  433. var User = this;
  434. User.findById(id, function (err, userData) {
  435. if (!userData) {
  436. return callback(err, null);
  437. }
  438. debug('Removing user:', userData);
  439. // 物理削除可能なのは、承認待ちユーザー、招待中ユーザーのみ
  440. // 利用を一度開始したユーザーは論理削除のみ可能
  441. if (userData.status !== STATUS_REGISTERED && userData.status !== STATUS_INVITED) {
  442. return callback(new Error('Cannot remove completely the user whoes status is not INVITED'), null);
  443. }
  444. userData.remove(function(err) {
  445. if (err) {
  446. return callback(err, null);
  447. }
  448. return callback(null, 1);
  449. });
  450. });
  451. };
  452. userSchema.statics.resetPasswordByRandomString = function(id) {
  453. var User = this;
  454. return new Promise(function(resolve, reject) {
  455. User.findById(id, function (err, userData) {
  456. if (!userData) {
  457. return reject(new Error('User not found'));
  458. }
  459. // is updatable check
  460. // if (userData.isUp
  461. var newPassword = generateRandomTempPassword();
  462. userData.setPassword(newPassword);
  463. userData.save(function(err, userData) {
  464. if (err) {
  465. return reject(err);
  466. }
  467. resolve({user: userData, newPassword: newPassword});
  468. });
  469. });
  470. });
  471. };
  472. userSchema.statics.createUsersByInvitation = function(emailList, toSendEmail, callback) {
  473. var User = this
  474. , createdUserList = []
  475. , config = crowi.getConfig()
  476. , mailer = crowi.getMailer()
  477. ;
  478. if (!Array.isArray(emailList)) {
  479. debug('emailList is not array');
  480. }
  481. async.each(
  482. emailList,
  483. function(email, next) {
  484. var newUser = new User()
  485. ,tmpUsername, password;
  486. email = email.trim();
  487. // email check
  488. // TODO: 削除済みはチェック対象から外そう〜
  489. User.findOne({email: email}, function (err, userData) {
  490. // The user is exists
  491. if (userData) {
  492. createdUserList.push({
  493. email: email,
  494. password: null,
  495. user: null,
  496. });
  497. return next();
  498. }
  499. tmpUsername = 'temp_' + Math.random().toString(36).slice(-16);
  500. password = Math.random().toString(36).slice(-16);
  501. newUser.username = tmpUsername;
  502. newUser.email = email;
  503. newUser.setPassword(password);
  504. newUser.createdAt = Date.now();
  505. newUser.status = STATUS_INVITED;
  506. newUser.save(function(err, userData) {
  507. if (err) {
  508. createdUserList.push({
  509. email: email,
  510. password: null,
  511. user: null,
  512. });
  513. debug('save failed!! ', err);
  514. } else {
  515. createdUserList.push({
  516. email: email,
  517. password: password,
  518. user: userData,
  519. });
  520. debug('saved!', email);
  521. }
  522. next();
  523. });
  524. });
  525. },
  526. function(err) {
  527. if (err) {
  528. debug('error occured while iterate email list');
  529. }
  530. if (toSendEmail) {
  531. // TODO: メール送信部分のロジックをサービス化する
  532. async.each(
  533. createdUserList,
  534. function(user, next) {
  535. if (user.password === null) {
  536. return next();
  537. }
  538. mailer.send({
  539. to: user.email,
  540. subject: 'Invitation to ' + config.crowi['app:title'],
  541. template: 'admin/userInvitation.txt',
  542. vars: {
  543. email: user.email,
  544. password: user.password,
  545. url: config.crowi['app:url'],
  546. appTitle: config.crowi['app:title'],
  547. }
  548. },
  549. function (err, s) {
  550. debug('completed to send email: ', err, s);
  551. next();
  552. }
  553. );
  554. },
  555. function(err) {
  556. debug('Sending invitation email completed.', err);
  557. }
  558. );
  559. }
  560. debug('createdUserList!!! ', createdUserList);
  561. return callback(null, createdUserList);
  562. }
  563. );
  564. };
  565. userSchema.statics.createUserByEmailAndPasswordAndStatus = function(name, username, email, password, lang, status, callback) {
  566. var User = this
  567. , newUser = new User();
  568. newUser.name = name;
  569. newUser.username = username;
  570. newUser.email = email || generateRandomEmail(); // don't set undefined for backward compatibility -- 2017.12.27 Yuki Takei
  571. if (password != null) {
  572. newUser.setPassword(password);
  573. }
  574. if (lang != null) {
  575. newUser.lang = lang;
  576. }
  577. newUser.createdAt = Date.now();
  578. newUser.status = status || decideUserStatusOnRegistration();
  579. newUser.save(function(err, userData) {
  580. if (err) {
  581. debug('createUserByEmailAndPassword failed: ', err);
  582. return callback(err);
  583. }
  584. if (userData.status == STATUS_ACTIVE) {
  585. userEvent.emit('activated', userData);
  586. }
  587. return callback(err, userData);
  588. });
  589. }
  590. /**
  591. * A wrapper function of createUserByEmailAndPasswordAndStatus
  592. *
  593. * @return {Promise<User>}
  594. */
  595. userSchema.statics.createUserByEmailAndPassword = function(name, username, email, password, lang, callback) {
  596. this.createUserByEmailAndPasswordAndStatus(name, username, email, password, lang, undefined, callback);
  597. };
  598. /**
  599. * A wrapper function of createUserByEmailAndPasswordAndStatus
  600. *
  601. * @return {Promise<User>}
  602. */
  603. userSchema.statics.createUser = function(name, username, email, password, lang, status) {
  604. const User = this;
  605. return new Promise((resolve, reject) => {
  606. User.createUserByEmailAndPasswordAndStatus(name, username, email, password, lang, status, (err, userData) => {
  607. if (err) {
  608. return reject(err);
  609. }
  610. return resolve(userData);
  611. });
  612. });
  613. }
  614. userSchema.statics.createUserPictureFilePath = function(user, name) {
  615. var ext = '.' + name.match(/(.*)(?:\.([^.]+$))/)[2];
  616. return 'user/' + user._id + ext;
  617. };
  618. userSchema.statics.getUsernameByPath = function(path) {
  619. var username = null;
  620. if (m = path.match(/^\/user\/([^\/]+)\/?/)) {
  621. username = m[1];
  622. }
  623. return username;
  624. };
  625. userSchema.statics.STATUS_REGISTERED = STATUS_REGISTERED;
  626. userSchema.statics.STATUS_ACTIVE = STATUS_ACTIVE;
  627. userSchema.statics.STATUS_SUSPENDED = STATUS_SUSPENDED;
  628. userSchema.statics.STATUS_DELETED = STATUS_DELETED;
  629. userSchema.statics.STATUS_INVITED = STATUS_INVITED;
  630. userSchema.statics.USER_PUBLIC_FIELDS = USER_PUBLIC_FIELDS;
  631. userSchema.statics.PAGE_ITEMS = PAGE_ITEMS;
  632. userSchema.statics.LANG_EN = LANG_EN;
  633. userSchema.statics.LANG_EN_US = LANG_EN_US;
  634. userSchema.statics.LANG_EN_GB = LANG_EN_US;
  635. userSchema.statics.LANG_JA = LANG_JA;
  636. return mongoose.model('User', userSchema);
  637. };