user.js 23 KB

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