user.js 20 KB

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