user.js 20 KB

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