user.js 21 KB

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