user.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  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 randomIndex = crypto.randomInt(0, chars.length);
  122. password += chars[randomIndex];
  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.readOnly = configManager.getConfig('app:isReadOnlyForNewUser');
  252. this.save((err, userData) => {
  253. userEvent.emit('activated', userData);
  254. if (err) {
  255. throw new Error(err);
  256. }
  257. return userData;
  258. });
  259. };
  260. userSchema.methods.grantAdmin = async function () {
  261. logger.debug('Grant Admin', this);
  262. this.admin = 1;
  263. return this.save();
  264. };
  265. userSchema.methods.revokeAdmin = async function () {
  266. logger.debug('Revove admin', this);
  267. this.admin = 0;
  268. return this.save();
  269. };
  270. userSchema.methods.grantReadOnly = async function () {
  271. logger.debug('Grant read only access', this);
  272. this.readOnly = 1;
  273. return this.save();
  274. };
  275. userSchema.methods.revokeReadOnly = async function () {
  276. logger.debug('Revoke read only access', this);
  277. this.readOnly = 0;
  278. return this.save();
  279. };
  280. userSchema.methods.asyncGrantAdmin = async function (callback) {
  281. this.admin = 1;
  282. return this.save();
  283. };
  284. userSchema.methods.statusActivate = async function () {
  285. logger.debug('Activate User', this);
  286. this.status = STATUS_ACTIVE;
  287. const userData = await this.save();
  288. return userEvent.emit('activated', userData);
  289. };
  290. userSchema.methods.statusSuspend = async function () {
  291. logger.debug('Suspend User', this);
  292. this.status = STATUS_SUSPENDED;
  293. if (this.email === undefined || this.email === null) {
  294. // migrate old data
  295. this.email = '-';
  296. }
  297. if (this.name === undefined || this.name === null) {
  298. // migrate old data
  299. this.name = `-${Date.now()}`;
  300. }
  301. if (this.username === undefined || this.usename === null) {
  302. // migrate old data
  303. this.username = '-';
  304. }
  305. return this.save();
  306. };
  307. userSchema.methods.statusDelete = async function () {
  308. logger.debug('Delete User', this);
  309. const now = new Date();
  310. const deletedLabel = `deleted_at_${now.getTime()}`;
  311. this.status = STATUS_DELETED;
  312. this.username = deletedLabel;
  313. this.password = '';
  314. this.name = '';
  315. this.email = `${deletedLabel}@deleted`;
  316. this.googleId = null;
  317. this.isGravatarEnabled = false;
  318. this.image = null;
  319. return this.save();
  320. };
  321. userSchema.statics.getUserStatusLabels = () => {
  322. const userStatus = {};
  323. userStatus[STATUS_REGISTERED] = 'Approval Pending';
  324. userStatus[STATUS_ACTIVE] = 'Active';
  325. userStatus[STATUS_SUSPENDED] = 'Suspended';
  326. userStatus[STATUS_DELETED] = 'Deleted';
  327. userStatus[STATUS_INVITED] = 'Invited';
  328. return userStatus;
  329. };
  330. userSchema.statics.isEmailValid = (email, callback) => {
  331. validateCrowi();
  332. const whitelist = configManager.getConfig('security:registrationWhitelist');
  333. if (Array.isArray(whitelist) && whitelist.length > 0) {
  334. return whitelist.some((allowedEmail) => {
  335. const re = new RegExp(`${allowedEmail}$`);
  336. return re.test(email);
  337. });
  338. }
  339. return true;
  340. };
  341. userSchema.statics.findUsers = function (options, callback) {
  342. const sort = options.sort || { status: 1, createdAt: 1 };
  343. this.find()
  344. .sort(sort)
  345. .skip(options.skip || 0)
  346. .limit(options.limit || 21)
  347. .exec((err, userData) => {
  348. callback(err, userData);
  349. });
  350. };
  351. userSchema.statics.findAllUsers = function (option) {
  352. // eslint-disable-next-line no-param-reassign
  353. option = option || {};
  354. const sort = option.sort || { createdAt: -1 };
  355. const fields = option.fields || {};
  356. let status = option.status || [STATUS_ACTIVE, STATUS_SUSPENDED];
  357. if (!Array.isArray(status)) {
  358. status = [status];
  359. }
  360. return this.find()
  361. .or(
  362. status.map((s) => {
  363. return { status: s };
  364. }),
  365. )
  366. .select(fields)
  367. .sort(sort);
  368. };
  369. userSchema.statics.findUsersByIds = function (ids, option) {
  370. // eslint-disable-next-line no-param-reassign
  371. option = option || {};
  372. const sort = option.sort || { createdAt: -1 };
  373. const status = option.status || STATUS_ACTIVE;
  374. const fields = option.fields || {};
  375. return this.find({ _id: { $in: ids }, status })
  376. .select(fields)
  377. .sort(sort);
  378. };
  379. userSchema.statics.findAdmins = async function (option) {
  380. const sort = option?.sort ?? { createdAt: -1 };
  381. let status = option?.status ?? [STATUS_ACTIVE];
  382. if (!Array.isArray(status)) {
  383. status = [status];
  384. }
  385. return this.find({ admin: true, status: { $in: status } }).sort(sort);
  386. };
  387. userSchema.statics.findUserByUsername = function (username) {
  388. if (username == null) {
  389. return Promise.resolve(null);
  390. }
  391. return this.findOne({ username });
  392. };
  393. userSchema.statics.findUserByApiToken = function (apiToken) {
  394. if (apiToken == null) {
  395. return Promise.resolve(null);
  396. }
  397. return this.findOne({ apiToken }).lean();
  398. };
  399. userSchema.statics.findUserByGoogleId = function (googleId, callback) {
  400. if (googleId == null) {
  401. callback(null, null);
  402. }
  403. this.findOne({ googleId }, (err, userData) => {
  404. callback(err, userData);
  405. });
  406. };
  407. userSchema.statics.findUserByUsernameOrEmail = function (
  408. usernameOrEmail,
  409. password,
  410. callback,
  411. ) {
  412. this.findOne()
  413. .or([{ username: usernameOrEmail }, { email: usernameOrEmail }])
  414. .exec((err, userData) => {
  415. callback(err, userData);
  416. });
  417. };
  418. userSchema.statics.findUserByEmailAndPassword = function (
  419. email,
  420. password,
  421. callback,
  422. ) {
  423. const hashedPassword = generatePassword(password);
  424. this.findOne({ email, password: hashedPassword }, (err, userData) => {
  425. callback(err, userData);
  426. });
  427. };
  428. userSchema.statics.isUserCountExceedsUpperLimit = async function () {
  429. const userUpperLimit = configManager.getConfig('security:userUpperLimit');
  430. const activeUsers = await this.countActiveUsers();
  431. if (userUpperLimit <= activeUsers) {
  432. return true;
  433. }
  434. return false;
  435. };
  436. userSchema.statics.countActiveUsers = async function () {
  437. return this.countListByStatus(STATUS_ACTIVE);
  438. };
  439. userSchema.statics.countListByStatus = async function (status) {
  440. // biome-ignore lint/complexity/noUselessThisAlias: ignore
  441. const User = this;
  442. const conditions = { status };
  443. // TODO count は非推奨。mongoose のバージョンアップ後に countDocuments に変更する。
  444. return User.count(conditions);
  445. };
  446. userSchema.statics.isRegisterableUsername = async function (username) {
  447. let usernameUsable = true;
  448. const userData = await this.findOne({ username });
  449. if (userData) {
  450. usernameUsable = false;
  451. }
  452. return usernameUsable;
  453. };
  454. userSchema.statics.isRegisterableEmail = async function (email) {
  455. let isEmailUsable = true;
  456. const userData = await this.findOne({ email });
  457. if (userData) {
  458. isEmailUsable = false;
  459. }
  460. return isEmailUsable;
  461. };
  462. userSchema.statics.isRegisterable = function (email, username, callback) {
  463. // biome-ignore lint/complexity/noUselessThisAlias: ignore
  464. const User = this;
  465. let emailUsable = true;
  466. let usernameUsable = true;
  467. // username check
  468. User.findOne({ username }, (err, userData) => {
  469. if (userData) {
  470. usernameUsable = false;
  471. }
  472. // email check
  473. User.findOne({ email }, (err, userData) => {
  474. if (userData) {
  475. emailUsable = false;
  476. }
  477. if (!emailUsable || !usernameUsable) {
  478. return callback(false, {
  479. email: emailUsable,
  480. username: usernameUsable,
  481. });
  482. }
  483. return callback(true, {});
  484. });
  485. });
  486. };
  487. userSchema.statics.resetPasswordByRandomString = async function (id) {
  488. const user = await this.findById(id);
  489. if (!user) {
  490. throw new Error('User not found');
  491. }
  492. const newPassword = generateRandomTempPassword();
  493. user.setPassword(newPassword);
  494. await user.save();
  495. return newPassword;
  496. };
  497. userSchema.statics.createUserByEmail = async function (email) {
  498. // biome-ignore lint/complexity/noUselessThisAlias: ignore
  499. const User = this;
  500. const newUser = new User();
  501. /* eslint-disable newline-per-chained-call */
  502. const tmpUsername = `temp_${crypto.randomBytes(8).toString('hex')}`;
  503. const password = crypto.randomBytes(12).toString('hex');
  504. /* eslint-enable newline-per-chained-call */
  505. newUser.username = tmpUsername;
  506. newUser.email = email;
  507. newUser.setPassword(password);
  508. newUser.status = STATUS_INVITED;
  509. const globalLang = configManager.getConfig('app:globalLang');
  510. if (globalLang != null) {
  511. newUser.lang = globalLang;
  512. }
  513. newUser.readOnly = configManager.getConfig('app:isReadOnlyForNewUser');
  514. try {
  515. const newUserData = await newUser.save();
  516. return {
  517. email,
  518. password,
  519. user: newUserData,
  520. };
  521. } catch (err) {
  522. return {
  523. email,
  524. };
  525. }
  526. };
  527. userSchema.statics.createUsersByEmailList = async function (emailList) {
  528. // biome-ignore lint/complexity/noUselessThisAlias: ignore
  529. const User = this;
  530. // check exists and get list of try to create
  531. const existingUserList = await User.find({
  532. email: { $in: emailList },
  533. userStatus: { $ne: STATUS_DELETED },
  534. });
  535. const existingEmailList = existingUserList.map((user) => {
  536. return user.email;
  537. });
  538. const creationEmailList = emailList.filter((email) => {
  539. return existingEmailList.indexOf(email) === -1;
  540. });
  541. const createdUserList = [];
  542. const failedToCreateUserEmailList = [];
  543. for (const email of creationEmailList) {
  544. try {
  545. // eslint-disable-next-line no-await-in-loop
  546. const createdUser = await this.createUserByEmail(email);
  547. createdUserList.push(createdUser);
  548. } catch (err) {
  549. logger.error(err);
  550. failedToCreateUserEmailList.push({
  551. email,
  552. reason: err.message,
  553. });
  554. }
  555. }
  556. return { createdUserList, existingEmailList, failedToCreateUserEmailList };
  557. };
  558. userSchema.statics.createUserByEmailAndPasswordAndStatus = async function (
  559. name,
  560. username,
  561. email,
  562. password,
  563. lang,
  564. status,
  565. callback,
  566. ) {
  567. // biome-ignore lint/complexity/noUselessThisAlias: ignore
  568. const User = this;
  569. const newUser = new User();
  570. // check user upper limit
  571. const isUserCountExceedsUpperLimit =
  572. await User.isUserCountExceedsUpperLimit();
  573. if (isUserCountExceedsUpperLimit) {
  574. const err = new UserUpperLimitException();
  575. return callback(err);
  576. }
  577. // check email duplication because email must be unique
  578. const count = await this.count({ email });
  579. if (count > 0) {
  580. // eslint-disable-next-line no-param-reassign
  581. email = generateRandomEmail();
  582. }
  583. newUser.name = name;
  584. newUser.username = username;
  585. newUser.email = email;
  586. if (password != null) {
  587. newUser.setPassword(password);
  588. }
  589. // Default email show/hide is up to the administrator
  590. newUser.isEmailPublished = configManager.getConfig(
  591. 'customize:isEmailPublishedForNewUser',
  592. );
  593. newUser.readOnly = configManager.getConfig('app:isReadOnlyForNewUser');
  594. const globalLang = configManager.getConfig('app:globalLang');
  595. if (globalLang != null) {
  596. newUser.lang = globalLang;
  597. }
  598. if (lang != null) {
  599. newUser.lang = lang;
  600. }
  601. newUser.status = status || decideUserStatusOnRegistration();
  602. newUser.save((err, userData) => {
  603. if (err) {
  604. logger.error('createUserByEmailAndPasswordAndStatus failed: ', err);
  605. return callback(err);
  606. }
  607. if (userData.status === STATUS_ACTIVE) {
  608. userEvent.emit('activated', userData);
  609. }
  610. return callback(err, userData);
  611. });
  612. };
  613. /**
  614. * A wrapper function of createUserByEmailAndPasswordAndStatus with callback
  615. *
  616. */
  617. userSchema.statics.createUserByEmailAndPassword = function (
  618. name,
  619. username,
  620. email,
  621. password,
  622. lang,
  623. callback,
  624. ) {
  625. this.createUserByEmailAndPasswordAndStatus(
  626. name,
  627. username,
  628. email,
  629. password,
  630. lang,
  631. undefined,
  632. callback,
  633. );
  634. };
  635. /**
  636. * A wrapper function of createUserByEmailAndPasswordAndStatus
  637. *
  638. * @return {Promise<User>}
  639. */
  640. userSchema.statics.createUser = function (
  641. name,
  642. username,
  643. email,
  644. password,
  645. lang,
  646. status,
  647. ) {
  648. // biome-ignore lint/complexity/noUselessThisAlias: ignore
  649. const User = this;
  650. return new Promise((resolve, reject) => {
  651. User.createUserByEmailAndPasswordAndStatus(
  652. name,
  653. username,
  654. email,
  655. password,
  656. lang,
  657. status,
  658. (err, userData) => {
  659. if (err) {
  660. return reject(err);
  661. }
  662. return resolve(userData);
  663. },
  664. );
  665. });
  666. };
  667. userSchema.statics.isExistUserByUserPagePath = async function (path) {
  668. const username = pagePathUtils.getUsernameByPath(path);
  669. if (username == null) {
  670. return false;
  671. }
  672. const user = await this.exists({ username });
  673. return user != null;
  674. };
  675. userSchema.statics.updateIsInvitationEmailSended = async function (id) {
  676. const user = await this.findById(id);
  677. if (user == null) {
  678. throw new Error('User not found');
  679. }
  680. if (user.status !== 5) {
  681. throw new Error('The status of the user is not "invited"');
  682. }
  683. user.isInvitationEmailSended = true;
  684. user.save();
  685. };
  686. userSchema.statics.findUserBySlackMemberId = async function (slackMemberId) {
  687. const user = this.findOne({ slackMemberId });
  688. if (user == null) {
  689. throw new Error('User not found');
  690. }
  691. return user;
  692. };
  693. userSchema.statics.findUsersBySlackMemberIds = async function (
  694. slackMemberIds,
  695. ) {
  696. const users = this.find({ slackMemberId: { $in: slackMemberIds } });
  697. if (users.length === 0) {
  698. throw new Error('No user found');
  699. }
  700. return users;
  701. };
  702. userSchema.statics.findUserByUsernameRegexWithTotalCount = async function (
  703. username,
  704. status,
  705. option,
  706. ) {
  707. const opt = option || {};
  708. const sortOpt = opt.sortOpt || { username: 1 };
  709. const offset = opt.offset || 0;
  710. const limit = opt.limit || 10;
  711. const conditions = {
  712. username: { $regex: username, $options: 'i' },
  713. status: { $in: status },
  714. };
  715. const users = await this.find(conditions)
  716. .sort(sortOpt)
  717. .skip(offset)
  718. .limit(limit);
  719. const totalCount = (await this.find(conditions).distinct('username'))
  720. .length;
  721. return { users, totalCount };
  722. };
  723. class UserUpperLimitException {
  724. constructor() {
  725. this.name = this.constructor.name;
  726. }
  727. }
  728. userSchema.statics.STATUS_REGISTERED = STATUS_REGISTERED;
  729. userSchema.statics.STATUS_ACTIVE = STATUS_ACTIVE;
  730. userSchema.statics.STATUS_SUSPENDED = STATUS_SUSPENDED;
  731. userSchema.statics.STATUS_DELETED = STATUS_DELETED;
  732. userSchema.statics.STATUS_INVITED = STATUS_INVITED;
  733. userSchema.statics.USER_FIELDS_EXCEPT_CONFIDENTIAL =
  734. USER_FIELDS_EXCEPT_CONFIDENTIAL;
  735. userSchema.statics.PAGE_ITEMS = PAGE_ITEMS;
  736. return mongoose.model('User', userSchema);
  737. };
  738. export default factory;