user.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  1. /* eslint-disable no-use-before-define */
  2. import loggerFactory from '~/utils/logger';
  3. const debug = require('debug')('growi:models:user');
  4. const mongoose = require('mongoose');
  5. const mongoosePaginate = require('mongoose-paginate-v2');
  6. const uniqueValidator = require('mongoose-unique-validator');
  7. const md5 = require('md5');
  8. const ObjectId = mongoose.Schema.Types.ObjectId;
  9. const crypto = require('crypto');
  10. const { listLocaleIds, migrateDeprecatedLocaleId } = require('~/utils/locale-utils');
  11. const { omitInsecureAttributes } = require('./serializers/user-serializer');
  12. const logger = loggerFactory('growi:models:user');
  13. module.exports = function(crowi) {
  14. const STATUS_REGISTERED = 1;
  15. const STATUS_ACTIVE = 2;
  16. const STATUS_SUSPENDED = 3;
  17. const STATUS_DELETED = 4;
  18. const STATUS_INVITED = 5;
  19. const USER_FIELDS_EXCEPT_CONFIDENTIAL = '_id image isEmailPublished isGravatarEnabled googleId name username email introduction'
  20. + ' status lang createdAt lastLoginAt admin imageUrlCached';
  21. const PAGE_ITEMS = 50;
  22. let userEvent;
  23. // init event
  24. if (crowi != null) {
  25. userEvent = crowi.event('user');
  26. userEvent.on('activated', userEvent.onActivated);
  27. }
  28. const userSchema = new mongoose.Schema({
  29. userId: String,
  30. image: String,
  31. imageAttachment: { type: ObjectId, ref: 'Attachment' },
  32. imageUrlCached: String,
  33. isGravatarEnabled: { type: Boolean, default: false },
  34. isEmailPublished: { type: Boolean, default: true },
  35. googleId: String,
  36. name: { type: String },
  37. username: { type: String, required: true, unique: true },
  38. email: { type: String, unique: true, sparse: true },
  39. slackId: { type: String, unique: true },
  40. // === Crowi settings
  41. // username: { type: String, index: true },
  42. // email: { type: String, required: true, index: true },
  43. // === crowi-plus (>= 2.1.0, <2.3.0) settings
  44. // email: { type: String, required: true, unique: true },
  45. introduction: String,
  46. password: String,
  47. apiToken: { type: String, index: true },
  48. lang: {
  49. type: String,
  50. enum: listLocaleIds(),
  51. default: 'en_US',
  52. },
  53. status: {
  54. type: Number, required: true, default: STATUS_ACTIVE, index: true,
  55. },
  56. createdAt: { type: Date, default: Date.now },
  57. lastLoginAt: { type: Date },
  58. admin: { type: Boolean, default: 0, index: true },
  59. isInvitationEmailSended: { type: Boolean, default: false },
  60. }, {
  61. toObject: {
  62. transform: (doc, ret, opt) => {
  63. return omitInsecureAttributes(ret);
  64. },
  65. },
  66. });
  67. // eslint-disable-next-line prefer-arrow-callback
  68. userSchema.pre('validate', function() {
  69. this.lang = migrateDeprecatedLocaleId(this.lang);
  70. });
  71. userSchema.plugin(mongoosePaginate);
  72. userSchema.plugin(uniqueValidator);
  73. function validateCrowi() {
  74. if (crowi == null) {
  75. throw new Error('"crowi" is null. Init User model with "crowi" argument first.');
  76. }
  77. }
  78. function decideUserStatusOnRegistration() {
  79. validateCrowi();
  80. const { configManager, aclService } = crowi;
  81. const isInstalled = configManager.getConfig('crowi', 'app:installed');
  82. if (!isInstalled) {
  83. return STATUS_ACTIVE; // is this ok?
  84. }
  85. // status decided depends on registrationMode
  86. const registrationMode = configManager.getConfig('crowi', 'security:registrationMode');
  87. switch (registrationMode) {
  88. case aclService.labels.SECURITY_REGISTRATION_MODE_OPEN:
  89. return STATUS_ACTIVE;
  90. case aclService.labels.SECURITY_REGISTRATION_MODE_RESTRICTED:
  91. case aclService.labels.SECURITY_REGISTRATION_MODE_CLOSED: // 一応
  92. return STATUS_REGISTERED;
  93. default:
  94. return STATUS_ACTIVE; // どっちにすんのがいいんだろうな
  95. }
  96. }
  97. function generateRandomEmail() {
  98. const randomstr = generateRandomTempPassword();
  99. return `change-it-${randomstr}@example.com`;
  100. }
  101. function generateRandomTempPassword() {
  102. const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!=-_';
  103. let password = '';
  104. const len = 12;
  105. for (let i = 0; i < len; i++) {
  106. const randomPoz = Math.floor(Math.random() * chars.length);
  107. password += chars.substring(randomPoz, randomPoz + 1);
  108. }
  109. return password;
  110. }
  111. function generatePassword(password) {
  112. validateCrowi();
  113. const hasher = crypto.createHash('sha256');
  114. hasher.update(crowi.env.PASSWORD_SEED + password);
  115. return hasher.digest('hex');
  116. }
  117. function generateApiToken(user) {
  118. const hasher = crypto.createHash('sha256');
  119. hasher.update((new Date()).getTime() + user._id);
  120. return hasher.digest('base64');
  121. }
  122. userSchema.methods.isPasswordSet = function() {
  123. if (this.password) {
  124. return true;
  125. }
  126. return false;
  127. };
  128. userSchema.methods.isPasswordValid = function(password) {
  129. return this.password === generatePassword(password);
  130. };
  131. userSchema.methods.setPassword = function(password) {
  132. this.password = generatePassword(password);
  133. return this;
  134. };
  135. userSchema.methods.isEmailSet = function() {
  136. if (this.email) {
  137. return true;
  138. }
  139. return false;
  140. };
  141. userSchema.methods.updateLastLoginAt = function(lastLoginAt, callback) {
  142. this.lastLoginAt = lastLoginAt;
  143. this.save((err, userData) => {
  144. return callback(err, userData);
  145. });
  146. };
  147. userSchema.methods.updateIsGravatarEnabled = async function(isGravatarEnabled) {
  148. this.isGravatarEnabled = isGravatarEnabled;
  149. await this.updateImageUrlCached();
  150. const userData = await this.save();
  151. return userData;
  152. };
  153. userSchema.methods.updatePassword = async function(password) {
  154. this.setPassword(password);
  155. const userData = await this.save();
  156. return userData;
  157. };
  158. userSchema.methods.updateApiToken = async function() {
  159. const self = this;
  160. self.apiToken = generateApiToken(this);
  161. const userData = await self.save();
  162. return userData;
  163. };
  164. // TODO: create UserService and transplant this method because image uploading depends on AttachmentService
  165. userSchema.methods.updateImage = async function(attachment) {
  166. this.imageAttachment = attachment;
  167. await this.updateImageUrlCached();
  168. return this.save();
  169. };
  170. // TODO: create UserService and transplant this method because image deletion depends on AttachmentService
  171. userSchema.methods.deleteImage = async function() {
  172. validateCrowi();
  173. // the 'image' field became DEPRECATED in v3.3.8
  174. this.image = undefined;
  175. if (this.imageAttachment != null) {
  176. const { attachmentService } = crowi;
  177. attachmentService.removeAttachment(this.imageAttachment._id);
  178. }
  179. this.imageAttachment = undefined;
  180. this.updateImageUrlCached();
  181. return this.save();
  182. };
  183. userSchema.methods.updateImageUrlCached = async function() {
  184. this.imageUrlCached = await this.generateImageUrlCached();
  185. };
  186. userSchema.methods.generateImageUrlCached = async function() {
  187. if (this.isGravatarEnabled) {
  188. const email = this.email || '';
  189. const hash = md5(email.trim().toLowerCase());
  190. return `https://gravatar.com/avatar/${hash}`;
  191. }
  192. if (this.image != null) {
  193. return this.image;
  194. }
  195. if (this.imageAttachment != null && this.imageAttachment._id != null) {
  196. const Attachment = crowi.model('Attachment');
  197. const imageAttachment = await Attachment.findById(this.imageAttachment);
  198. return imageAttachment.filePathProxied;
  199. }
  200. return '/images/icons/user.svg';
  201. };
  202. userSchema.methods.updateGoogleId = function(googleId, callback) {
  203. this.googleId = googleId;
  204. this.save((err, userData) => {
  205. return callback(err, userData);
  206. });
  207. };
  208. userSchema.methods.deleteGoogleId = function(callback) {
  209. return this.updateGoogleId(null, callback);
  210. };
  211. userSchema.methods.activateInvitedUser = async function(username, name, password) {
  212. this.setPassword(password);
  213. this.name = name;
  214. this.username = username;
  215. this.status = STATUS_ACTIVE;
  216. this.isEmailPublished = crowi.configManager.getConfig('crowi', 'customize:isEmailPublishedForNewUser');
  217. this.save((err, userData) => {
  218. userEvent.emit('activated', userData);
  219. if (err) {
  220. throw new Error(err);
  221. }
  222. return userData;
  223. });
  224. };
  225. userSchema.methods.removeFromAdmin = async function() {
  226. debug('Remove from admin', this);
  227. this.admin = 0;
  228. return this.save();
  229. };
  230. userSchema.methods.makeAdmin = async function() {
  231. debug('Admin', this);
  232. this.admin = 1;
  233. return this.save();
  234. };
  235. userSchema.methods.asyncMakeAdmin = async function(callback) {
  236. this.admin = 1;
  237. return this.save();
  238. };
  239. userSchema.methods.statusActivate = async function() {
  240. debug('Activate User', this);
  241. this.status = STATUS_ACTIVE;
  242. const userData = await this.save();
  243. return userEvent.emit('activated', userData);
  244. };
  245. userSchema.methods.statusSuspend = async function() {
  246. debug('Suspend User', this);
  247. this.status = STATUS_SUSPENDED;
  248. if (this.email === undefined || this.email === null) { // migrate old data
  249. this.email = '-';
  250. }
  251. if (this.name === undefined || this.name === null) { // migrate old data
  252. this.name = `-${Date.now()}`;
  253. }
  254. if (this.username === undefined || this.usename === null) { // migrate old data
  255. this.username = '-';
  256. }
  257. return this.save();
  258. };
  259. userSchema.methods.statusDelete = async function() {
  260. debug('Delete User', this);
  261. const now = new Date();
  262. const deletedLabel = `deleted_at_${now.getTime()}`;
  263. this.status = STATUS_DELETED;
  264. this.username = deletedLabel;
  265. this.password = '';
  266. this.name = '';
  267. this.email = `${deletedLabel}@deleted`;
  268. this.googleId = null;
  269. this.isGravatarEnabled = false;
  270. this.image = null;
  271. return this.save();
  272. };
  273. userSchema.statics.getUserStatusLabels = function() {
  274. const userStatus = {};
  275. userStatus[STATUS_REGISTERED] = 'Approval Pending';
  276. userStatus[STATUS_ACTIVE] = 'Active';
  277. userStatus[STATUS_SUSPENDED] = 'Suspended';
  278. userStatus[STATUS_DELETED] = 'Deleted';
  279. userStatus[STATUS_INVITED] = 'Invited';
  280. return userStatus;
  281. };
  282. userSchema.statics.isEmailValid = function(email, callback) {
  283. validateCrowi();
  284. const whitelist = crowi.configManager.getConfig('crowi', 'security:registrationWhiteList');
  285. if (Array.isArray(whitelist) && whitelist.length > 0) {
  286. return whitelist.some((allowedEmail) => {
  287. const re = new RegExp(`${allowedEmail}$`);
  288. return re.test(email);
  289. });
  290. }
  291. return true;
  292. };
  293. userSchema.statics.findUsers = function(options, callback) {
  294. const sort = options.sort || { status: 1, createdAt: 1 };
  295. this.find()
  296. .sort(sort)
  297. .skip(options.skip || 0)
  298. .limit(options.limit || 21)
  299. .exec((err, userData) => {
  300. callback(err, userData);
  301. });
  302. };
  303. userSchema.statics.findAllUsers = function(option) {
  304. // eslint-disable-next-line no-param-reassign
  305. option = option || {};
  306. const sort = option.sort || { createdAt: -1 };
  307. const fields = option.fields || {};
  308. let status = option.status || [STATUS_ACTIVE, STATUS_SUSPENDED];
  309. if (!Array.isArray(status)) {
  310. status = [status];
  311. }
  312. return this.find()
  313. .or(status.map((s) => { return { status: s } }))
  314. .select(fields)
  315. .sort(sort);
  316. };
  317. userSchema.statics.findUsersByIds = function(ids, option) {
  318. // eslint-disable-next-line no-param-reassign
  319. option = option || {};
  320. const sort = option.sort || { createdAt: -1 };
  321. const status = option.status || STATUS_ACTIVE;
  322. const fields = option.fields || {};
  323. return this.find({ _id: { $in: ids }, status })
  324. .select(fields)
  325. .sort(sort);
  326. };
  327. userSchema.statics.findAdmins = async function() {
  328. return this.find({ admin: true });
  329. };
  330. userSchema.statics.findUserByUsername = function(username) {
  331. if (username == null) {
  332. return Promise.resolve(null);
  333. }
  334. return this.findOne({ username });
  335. };
  336. userSchema.statics.findUserByApiToken = function(apiToken) {
  337. if (apiToken == null) {
  338. return Promise.resolve(null);
  339. }
  340. return this.findOne({ apiToken });
  341. };
  342. userSchema.statics.findUserByGoogleId = function(googleId, callback) {
  343. if (googleId == null) {
  344. callback(null, null);
  345. }
  346. this.findOne({ googleId }, (err, userData) => {
  347. callback(err, userData);
  348. });
  349. };
  350. userSchema.statics.findUserByUsernameOrEmail = function(usernameOrEmail, password, callback) {
  351. this.findOne()
  352. .or([
  353. { username: usernameOrEmail },
  354. { email: usernameOrEmail },
  355. ])
  356. .exec((err, userData) => {
  357. callback(err, userData);
  358. });
  359. };
  360. userSchema.statics.findUserByEmailAndPassword = function(email, password, callback) {
  361. const hashedPassword = generatePassword(password);
  362. this.findOne({ email, password: hashedPassword }, (err, userData) => {
  363. callback(err, userData);
  364. });
  365. };
  366. userSchema.statics.isUserCountExceedsUpperLimit = async function() {
  367. const { configManager } = crowi;
  368. const userUpperLimit = configManager.getConfig('crowi', 'security:userUpperLimit');
  369. const activeUsers = await this.countListByStatus(STATUS_ACTIVE);
  370. if (userUpperLimit <= activeUsers) {
  371. return true;
  372. }
  373. return false;
  374. };
  375. userSchema.statics.countListByStatus = async function(status) {
  376. const User = this;
  377. const conditions = { status };
  378. // TODO count は非推奨。mongoose のバージョンアップ後に countDocuments に変更する。
  379. return User.count(conditions);
  380. };
  381. userSchema.statics.isRegisterableUsername = async function(username) {
  382. let usernameUsable = true;
  383. const userData = await this.findOne({ username });
  384. if (userData) {
  385. usernameUsable = false;
  386. }
  387. return usernameUsable;
  388. };
  389. userSchema.statics.isRegisterableEmail = async function(email) {
  390. let isEmailUsable = true;
  391. const userData = await this.findOne({ email });
  392. if (userData) {
  393. isEmailUsable = false;
  394. }
  395. return isEmailUsable;
  396. };
  397. userSchema.statics.isRegisterable = function(email, username, callback) {
  398. const User = this;
  399. let emailUsable = true;
  400. let usernameUsable = true;
  401. // username check
  402. this.findOne({ username }, (err, userData) => {
  403. if (userData) {
  404. usernameUsable = false;
  405. }
  406. // email check
  407. User.findOne({ email }, (err, userData) => {
  408. if (userData) {
  409. emailUsable = false;
  410. }
  411. if (!emailUsable || !usernameUsable) {
  412. return callback(false, { email: emailUsable, username: usernameUsable });
  413. }
  414. return callback(true, {});
  415. });
  416. });
  417. };
  418. userSchema.statics.resetPasswordByRandomString = async function(id) {
  419. const user = await this.findById(id);
  420. if (!user) {
  421. throw new Error('User not found');
  422. }
  423. const newPassword = generateRandomTempPassword();
  424. user.setPassword(newPassword);
  425. await user.save();
  426. return newPassword;
  427. };
  428. userSchema.statics.createUserByEmail = async function(email) {
  429. const configManager = crowi.configManager;
  430. const User = this;
  431. const newUser = new User();
  432. /* eslint-disable newline-per-chained-call */
  433. const tmpUsername = `temp_${Math.random().toString(36).slice(-16)}`;
  434. const password = Math.random().toString(36).slice(-16);
  435. /* eslint-enable newline-per-chained-call */
  436. newUser.username = tmpUsername;
  437. newUser.email = email;
  438. newUser.setPassword(password);
  439. newUser.createdAt = Date.now();
  440. newUser.status = STATUS_INVITED;
  441. const globalLang = configManager.getConfig('crowi', 'app:globalLang');
  442. if (globalLang != null) {
  443. newUser.lang = globalLang;
  444. }
  445. try {
  446. const newUserData = await newUser.save();
  447. return {
  448. email,
  449. password,
  450. user: newUserData,
  451. };
  452. }
  453. catch (err) {
  454. return {
  455. email,
  456. };
  457. }
  458. };
  459. userSchema.statics.createUsersByEmailList = async function(emailList) {
  460. const User = this;
  461. // check exists and get list of try to create
  462. const existingUserList = await User.find({ email: { $in: emailList }, userStatus: { $ne: STATUS_DELETED } });
  463. const existingEmailList = existingUserList.map((user) => { return user.email });
  464. const creationEmailList = emailList.filter((email) => { return existingEmailList.indexOf(email) === -1 });
  465. const createdUserList = [];
  466. const failedToCreateUserEmailList = [];
  467. for (const email of creationEmailList) {
  468. try {
  469. // eslint-disable-next-line no-await-in-loop
  470. const createdUser = await this.createUserByEmail(email);
  471. createdUserList.push(createdUser);
  472. }
  473. catch (err) {
  474. logger.error(err);
  475. failedToCreateUserEmailList.push({
  476. email,
  477. reason: err.message,
  478. });
  479. }
  480. }
  481. return { createdUserList, existingEmailList, failedToCreateUserEmailList };
  482. };
  483. userSchema.statics.createUserByEmailAndPasswordAndStatus = async function(name, username, email, password, lang, status, callback) {
  484. const User = this;
  485. const newUser = new User();
  486. // check user upper limit
  487. const isUserCountExceedsUpperLimit = await User.isUserCountExceedsUpperLimit();
  488. if (isUserCountExceedsUpperLimit) {
  489. const err = new UserUpperLimitException();
  490. return callback(err);
  491. }
  492. // check email duplication because email must be unique
  493. const count = await this.count({ email });
  494. if (count > 0) {
  495. // eslint-disable-next-line no-param-reassign
  496. email = generateRandomEmail();
  497. }
  498. newUser.name = name;
  499. newUser.username = username;
  500. newUser.email = email;
  501. if (password != null) {
  502. newUser.setPassword(password);
  503. }
  504. const configManager = crowi.configManager;
  505. // Default email show/hide is up to the administrator
  506. newUser.isEmailPublished = configManager.getConfig('crowi', 'customize:isEmailPublishedForNewUser');
  507. const globalLang = configManager.getConfig('crowi', 'app:globalLang');
  508. if (globalLang != null) {
  509. newUser.lang = globalLang;
  510. }
  511. if (lang != null) {
  512. newUser.lang = lang;
  513. }
  514. newUser.createdAt = Date.now();
  515. newUser.status = status || decideUserStatusOnRegistration();
  516. newUser.save((err, userData) => {
  517. if (err) {
  518. logger.error('createUserByEmailAndPasswordAndStatus failed: ', err);
  519. return callback(err);
  520. }
  521. if (userData.status === STATUS_ACTIVE) {
  522. userEvent.emit('activated', userData);
  523. }
  524. return callback(err, userData);
  525. });
  526. };
  527. /**
  528. * A wrapper function of createUserByEmailAndPasswordAndStatus with callback
  529. *
  530. */
  531. userSchema.statics.createUserByEmailAndPassword = function(name, username, email, password, lang, callback) {
  532. this.createUserByEmailAndPasswordAndStatus(name, username, email, password, lang, undefined, callback);
  533. };
  534. /**
  535. * A wrapper function of createUserByEmailAndPasswordAndStatus
  536. *
  537. * @return {Promise<User>}
  538. */
  539. userSchema.statics.createUser = function(name, username, email, password, lang, status) {
  540. const User = this;
  541. return new Promise((resolve, reject) => {
  542. User.createUserByEmailAndPasswordAndStatus(name, username, email, password, lang, status, (err, userData) => {
  543. if (err) {
  544. return reject(err);
  545. }
  546. return resolve(userData);
  547. });
  548. });
  549. };
  550. userSchema.statics.getUsernameByPath = function(path) {
  551. let username = null;
  552. const match = path.match(/^\/user\/([^/]+)\/?/);
  553. if (match) {
  554. username = match[1];
  555. }
  556. return username;
  557. };
  558. userSchema.statics.updateIsInvitationEmailSended = async function(id) {
  559. const user = await this.findById(id);
  560. if (user == null) {
  561. throw new Error('User not found');
  562. }
  563. if (user.status !== 5) {
  564. throw new Error('The status of the user is not "invited"');
  565. }
  566. user.isInvitationEmailSended = true;
  567. user.save();
  568. };
  569. userSchema.statics.findUserBySlackId = async function(slackId) {
  570. const user = this.findOne({ slackId });
  571. if (user == null) {
  572. throw new Error('User not found');
  573. }
  574. return user;
  575. };
  576. userSchema.statics.findUsersBySlackIds = async function(slackIds) {
  577. const users = this.find({ slackId: { $in: slackIds } });
  578. if (users.length === 0) {
  579. throw new Error('No user found');
  580. }
  581. return users;
  582. };
  583. class UserUpperLimitException {
  584. constructor() {
  585. this.name = this.constructor.name;
  586. }
  587. }
  588. userSchema.statics.STATUS_REGISTERED = STATUS_REGISTERED;
  589. userSchema.statics.STATUS_ACTIVE = STATUS_ACTIVE;
  590. userSchema.statics.STATUS_SUSPENDED = STATUS_SUSPENDED;
  591. userSchema.statics.STATUS_DELETED = STATUS_DELETED;
  592. userSchema.statics.STATUS_INVITED = STATUS_INVITED;
  593. userSchema.statics.USER_FIELDS_EXCEPT_CONFIDENTIAL = USER_FIELDS_EXCEPT_CONFIDENTIAL;
  594. userSchema.statics.PAGE_ITEMS = PAGE_ITEMS;
  595. return mongoose.model('User', userSchema);
  596. };