diff --git a/services/web/app.js b/services/web/app.js index 16aa07b77c..5975e0b04f 100644 --- a/services/web/app.js +++ b/services/web/app.js @@ -15,10 +15,14 @@ const Settings = require('@overleaf/settings') const logger = require('@overleaf/logger') const PlansLocator = require('./app/src/Features/Subscription/PlansLocator') logger.initialize(process.env.METRICS_APP_NAME || 'web') -logger.logger.serializers.user = require('./app/src/infrastructure/LoggerSerializers').user -logger.logger.serializers.docs = require('./app/src/infrastructure/LoggerSerializers').docs -logger.logger.serializers.files = require('./app/src/infrastructure/LoggerSerializers').files -logger.logger.serializers.project = require('./app/src/infrastructure/LoggerSerializers').project +logger.logger.serializers.user = + require('./app/src/infrastructure/LoggerSerializers').user +logger.logger.serializers.docs = + require('./app/src/infrastructure/LoggerSerializers').docs +logger.logger.serializers.files = + require('./app/src/infrastructure/LoggerSerializers').files +logger.logger.serializers.project = + require('./app/src/infrastructure/LoggerSerializers').project if ((Settings.sentry != null ? Settings.sentry.dsn : undefined) != null) { logger.initializeErrorReporting(Settings.sentry.dsn) } diff --git a/services/web/app/src/Features/Authorization/AuthorizationManager.js b/services/web/app/src/Features/Authorization/AuthorizationManager.js index 796332b6ad..5e1037f3bb 100644 --- a/services/web/app/src/Features/Authorization/AuthorizationManager.js +++ b/services/web/app/src/Features/Authorization/AuthorizationManager.js @@ -80,10 +80,11 @@ async function getPrivilegeLevelForProjectWithUser( token, opts = {} ) { - const privilegeLevel = await CollaboratorsGetter.promises.getMemberIdPrivilegeLevel( - userId, - projectId - ) + const privilegeLevel = + await CollaboratorsGetter.promises.getMemberIdPrivilegeLevel( + userId, + projectId + ) if (privilegeLevel && privilegeLevel !== PrivilegeLevels.NONE) { // The user has direct access return privilegeLevel @@ -140,13 +141,11 @@ async function getPrivilegeLevelForProjectWithToken(projectId, token) { // Anonymous users can have read-only access to token-based projects, // while read-write access must be logged in, // unless the `enableAnonymousReadAndWriteSharing` setting is enabled - const { - isValidReadAndWrite, - isValidReadOnly, - } = await TokenAccessHandler.promises.validateTokenForAnonymousAccess( - projectId, - token - ) + const { isValidReadAndWrite, isValidReadOnly } = + await TokenAccessHandler.promises.validateTokenForAnonymousAccess( + projectId, + token + ) if (isValidReadOnly) { // Grant anonymous user read-only access return PrivilegeLevels.READ_ONLY diff --git a/services/web/app/src/Features/Authorization/AuthorizationMiddleware.js b/services/web/app/src/Features/Authorization/AuthorizationMiddleware.js index 610ef4661d..9855b4c233 100644 --- a/services/web/app/src/Features/Authorization/AuthorizationMiddleware.js +++ b/services/web/app/src/Features/Authorization/AuthorizationMiddleware.js @@ -29,11 +29,12 @@ async function blockRestrictedUserFromProject(req, res, next) { const projectId = _getProjectId(req) const userId = _getUserId(req) const token = TokenAccessHandler.getRequestToken(req, projectId) - const isRestrictedUser = await AuthorizationManager.promises.isRestrictedUserForProject( - userId, - projectId, - token - ) + const isRestrictedUser = + await AuthorizationManager.promises.isRestrictedUserForProject( + userId, + projectId, + token + ) if (isRestrictedUser) { return HttpErrorHandler.forbidden(req, res) } @@ -75,11 +76,12 @@ async function ensureUserCanWriteProjectSettings(req, res, next) { const otherParams = Object.keys(req.body).filter(x => x !== 'name') if (otherParams.length > 0) { - const canWrite = await AuthorizationManager.promises.canUserWriteProjectSettings( - userId, - projectId, - token - ) + const canWrite = + await AuthorizationManager.promises.canUserWriteProjectSettings( + userId, + projectId, + token + ) if (!canWrite) { return HttpErrorHandler.forbidden(req, res) } @@ -92,11 +94,12 @@ async function ensureUserCanWriteProjectContent(req, res, next) { const projectId = _getProjectId(req) const userId = _getUserId(req) const token = TokenAccessHandler.getRequestToken(req, projectId) - const canWrite = await AuthorizationManager.promises.canUserWriteProjectContent( - userId, - projectId, - token - ) + const canWrite = + await AuthorizationManager.promises.canUserWriteProjectContent( + userId, + projectId, + token + ) if (canWrite) { logger.log( { userId, projectId }, diff --git a/services/web/app/src/Features/Captcha/CaptchaMiddleware.js b/services/web/app/src/Features/Captcha/CaptchaMiddleware.js index d1b9fd6bd7..47f97e4214 100644 --- a/services/web/app/src/Features/Captcha/CaptchaMiddleware.js +++ b/services/web/app/src/Features/Captcha/CaptchaMiddleware.js @@ -50,8 +50,7 @@ module.exports = CaptchaMiddleware = { return res.status(400).send({ errorReason: 'cannot_verify_user_not_robot', message: { - text: - 'Sorry, we could not verify that you are not a robot. Please check that Google reCAPTCHA is not being blocked by an ad blocker or firewall.', + text: 'Sorry, we could not verify that you are not a robot. Please check that Google reCAPTCHA is not being blocked by an ad blocker or firewall.', }, }) } else { diff --git a/services/web/app/src/Features/Collaborators/CollaboratorsGetter.js b/services/web/app/src/Features/Collaborators/CollaboratorsGetter.js index 3519045187..39077d28bf 100644 --- a/services/web/app/src/Features/Collaborators/CollaboratorsGetter.js +++ b/services/web/app/src/Features/Collaborators/CollaboratorsGetter.js @@ -132,42 +132,37 @@ async function isUserInvitedMemberOfProject(userId, projectId) { async function getProjectsUserIsMemberOf(userId, fields) { const limit = pLimit(2) - const [ - readAndWrite, - readOnly, - tokenReadAndWrite, - tokenReadOnly, - ] = await Promise.all([ - limit(() => Project.find({ collaberator_refs: userId }, fields).exec()), - limit(() => Project.find({ readOnly_refs: userId }, fields).exec()), - limit(() => - Project.find( - { - tokenAccessReadAndWrite_refs: userId, - publicAccesLevel: PublicAccessLevels.TOKEN_BASED, - }, - fields - ).exec() - ), - limit(() => - Project.find( - { - tokenAccessReadOnly_refs: userId, - publicAccesLevel: PublicAccessLevels.TOKEN_BASED, - }, - fields - ).exec() - ), - ]) + const [readAndWrite, readOnly, tokenReadAndWrite, tokenReadOnly] = + await Promise.all([ + limit(() => Project.find({ collaberator_refs: userId }, fields).exec()), + limit(() => Project.find({ readOnly_refs: userId }, fields).exec()), + limit(() => + Project.find( + { + tokenAccessReadAndWrite_refs: userId, + publicAccesLevel: PublicAccessLevels.TOKEN_BASED, + }, + fields + ).exec() + ), + limit(() => + Project.find( + { + tokenAccessReadOnly_refs: userId, + publicAccesLevel: PublicAccessLevels.TOKEN_BASED, + }, + fields + ).exec() + ), + ]) return { readAndWrite, readOnly, tokenReadAndWrite, tokenReadOnly } } async function getAllInvitedMembers(projectId) { try { const rawMembers = await getInvitedMembersWithPrivilegeLevels(projectId) - const { members } = ProjectEditorHandler.buildOwnerAndMembersViews( - rawMembers - ) + const { members } = + ProjectEditorHandler.buildOwnerAndMembersViews(rawMembers) return members } catch (err) { throw OError.tag(err, 'error getting members for project', { projectId }) diff --git a/services/web/app/src/Features/Collaborators/CollaboratorsHandler.js b/services/web/app/src/Features/Collaborators/CollaboratorsHandler.js index 9dd3f1c9d9..d8d0d1b6e1 100644 --- a/services/web/app/src/Features/Collaborators/CollaboratorsHandler.js +++ b/services/web/app/src/Features/Collaborators/CollaboratorsHandler.js @@ -78,14 +78,10 @@ async function removeUserFromProject(projectId, userId) { } async function removeUserFromAllProjects(userId) { - const { - readAndWrite, - readOnly, - tokenReadAndWrite, - tokenReadOnly, - } = await CollaboratorsGetter.promises.getProjectsUserIsMemberOf(userId, { - _id: 1, - }) + const { readAndWrite, readOnly, tokenReadAndWrite, tokenReadOnly } = + await CollaboratorsGetter.promises.getProjectsUserIsMemberOf(userId, { + _id: 1, + }) const allProjects = readAndWrite .concat(readOnly) .concat(tokenReadAndWrite) diff --git a/services/web/app/src/Features/Compile/ClsiStateManager.js b/services/web/app/src/Features/Compile/ClsiStateManager.js index d1db73af86..a7e687f2ab 100644 --- a/services/web/app/src/Features/Compile/ClsiStateManager.js +++ b/services/web/app/src/Features/Compile/ClsiStateManager.js @@ -38,9 +38,8 @@ const buildState = s => module.exports = ClsiStateManager = { computeHash(project, options) { - const { docs, files } = ProjectEntityHandler.getAllEntitiesFromProject( - project - ) + const { docs, files } = + ProjectEntityHandler.getAllEntitiesFromProject(project) const fileList = Array.from(files || []).map( f => `${f.file._id}:${f.file.rev}:${f.file.created}:${f.path}` ) diff --git a/services/web/app/src/Features/Editor/EditorHttpController.js b/services/web/app/src/Features/Editor/EditorHttpController.js index 555b7b2233..ff91895bdf 100644 --- a/services/web/app/src/Features/Editor/EditorHttpController.js +++ b/services/web/app/src/Features/Editor/EditorHttpController.js @@ -60,11 +60,8 @@ async function joinProject(req, res, next) { userId = null } Metrics.inc('editor.join-project') - const { - project, - privilegeLevel, - isRestrictedUser, - } = await _buildJoinProjectView(req, projectId, userId) + const { project, privilegeLevel, isRestrictedUser } = + await _buildJoinProjectView(req, projectId, userId) if (!project) { return res.sendStatus(403) } @@ -116,15 +113,17 @@ async function _buildJoinProjectView(req, projectId, userId) { 'soft-failure when fetching deletedDocs from docstore' ) } - const members = await CollaboratorsGetter.promises.getInvitedMembersWithPrivilegeLevels( - projectId - ) + const members = + await CollaboratorsGetter.promises.getInvitedMembersWithPrivilegeLevels( + projectId + ) const token = TokenAccessHandler.getRequestToken(req, projectId) - const privilegeLevel = await AuthorizationManager.promises.getPrivilegeLevelForProject( - userId, - projectId, - token - ) + const privilegeLevel = + await AuthorizationManager.promises.getPrivilegeLevelForProject( + userId, + projectId, + token + ) if (privilegeLevel == null || privilegeLevel === PrivilegeLevels.NONE) { return { project: null, privilegeLevel: null, isRestrictedUser: false } } diff --git a/services/web/app/src/Features/Errors/Errors.js b/services/web/app/src/Features/Errors/Errors.js index a94153a917..7d3940ab31 100644 --- a/services/web/app/src/Features/Errors/Errors.js +++ b/services/web/app/src/Features/Errors/Errors.js @@ -99,12 +99,8 @@ class SAMLSessionDataMissing extends BackwardCompatibleError { ? arg.samlSession : {} this.tryAgain = true - const { - universityId, - universityName, - externalUserId, - institutionEmail, - } = samlSession + const { universityId, universityName, externalUserId, institutionEmail } = + samlSession if ( !universityId && diff --git a/services/web/app/src/Features/Exports/ExportsHandler.js b/services/web/app/src/Features/Exports/ExportsHandler.js index d456b7473c..28ff5061f3 100644 --- a/services/web/app/src/Features/Exports/ExportsHandler.js +++ b/services/web/app/src/Features/Exports/ExportsHandler.js @@ -27,261 +27,265 @@ let request = require('request') request = request.defaults() settings = require('@overleaf/settings') -module.exports = ExportsHandler = self = { - exportProject(export_params, callback) { - if (callback == null) { - callback = function () {} - } - return self._buildExport(export_params, function (err, export_data) { - if (err != null) { - return callback(err) - } - return self._requestExport(export_data, function (err, body) { - if (err != null) { - return callback(err) +module.exports = + ExportsHandler = + self = + { + exportProject(export_params, callback) { + if (callback == null) { + callback = function () {} } - export_data.v1_id = body.exportId - export_data.message = body.message - // TODO: possibly store the export data in Mongo - return callback(null, export_data) - }) - }) - }, - - _buildExport(export_params, callback) { - if (callback == null) { - callback = function () {} - } - const { - project_id, - user_id, - brand_variation_id, - title, - description, - author, - license, - show_source, - } = export_params - const jobs = { - project(cb) { - return ProjectGetter.getProject(project_id, cb) - }, - // TODO: when we update async, signature will change from (cb, results) to (results, cb) - rootDoc: [ - 'project', - (cb, results) => - ProjectRootDocManager.ensureRootDocumentIsValid( - project_id, - function (error) { - if (error != null) { - return callback(error) - } - return ProjectLocator.findRootDoc( - { project: results.project, project_id }, - cb - ) + return self._buildExport(export_params, function (err, export_data) { + if (err != null) { + return callback(err) + } + return self._requestExport(export_data, function (err, body) { + if (err != null) { + return callback(err) } - ), - ], - user(cb) { - return UserGetter.getUser( + export_data.v1_id = body.exportId + export_data.message = body.message + // TODO: possibly store the export data in Mongo + return callback(null, export_data) + }) + }) + }, + + _buildExport(export_params, callback) { + if (callback == null) { + callback = function () {} + } + const { + project_id, user_id, - { first_name: 1, last_name: 1, email: 1, overleaf: 1 }, - cb + brand_variation_id, + title, + description, + author, + license, + show_source, + } = export_params + const jobs = { + project(cb) { + return ProjectGetter.getProject(project_id, cb) + }, + // TODO: when we update async, signature will change from (cb, results) to (results, cb) + rootDoc: [ + 'project', + (cb, results) => + ProjectRootDocManager.ensureRootDocumentIsValid( + project_id, + function (error) { + if (error != null) { + return callback(error) + } + return ProjectLocator.findRootDoc( + { project: results.project, project_id }, + cb + ) + } + ), + ], + user(cb) { + return UserGetter.getUser( + user_id, + { first_name: 1, last_name: 1, email: 1, overleaf: 1 }, + cb + ) + }, + historyVersion(cb) { + return ProjectHistoryHandler.ensureHistoryExistsForProject( + project_id, + function (error) { + if (error != null) { + return callback(error) + } + return self._requestVersion(project_id, cb) + } + ) + }, + } + + return async.auto(jobs, function (err, results) { + if (err != null) { + OError.tag(err, 'error building project export', { + project_id, + user_id, + brand_variation_id, + }) + return callback(err) + } + + const { project, rootDoc, user, historyVersion } = results + if (!rootDoc || rootDoc[1] == null) { + err = new OError('cannot export project without root doc', { + project_id, + }) + return callback(err) + } + + if (export_params.first_name && export_params.last_name) { + user.first_name = export_params.first_name + user.last_name = export_params.last_name + } + + const export_data = { + project: { + id: project_id, + rootDocPath: + rootDoc[1] != null ? rootDoc[1].fileSystem : undefined, + historyId: __guard__( + project.overleaf != null ? project.overleaf.history : undefined, + x => x.id + ), + historyVersion, + v1ProjectId: + project.overleaf != null ? project.overleaf.id : undefined, + metadata: { + compiler: project.compiler, + imageName: project.imageName, + title, + description, + author, + license, + showSource: show_source, + }, + }, + user: { + id: user_id, + firstName: user.first_name, + lastName: user.last_name, + email: user.email, + orcidId: null, // until v2 gets ORCID + v1UserId: user.overleaf != null ? user.overleaf.id : undefined, + }, + destination: { + brandVariationId: brand_variation_id, + }, + options: { + callbackUrl: null, + }, // for now, until we want v1 to call us back + } + return callback(null, export_data) + }) + }, + + _requestExport(export_data, callback) { + if (callback == null) { + callback = function () {} + } + return request.post( + { + url: `${settings.apis.v1.url}/api/v1/sharelatex/exports`, + auth: { user: settings.apis.v1.user, pass: settings.apis.v1.pass }, + json: export_data, + }, + function (err, res, body) { + if (err != null) { + OError.tag(err, 'error making request to v1 export', { + export: export_data, + }) + return callback(err) + } else if (res.statusCode >= 200 && res.statusCode < 300) { + return callback(null, body) + } else { + logger.warn( + { export: export_data }, + `v1 export returned failure; forwarding: ${body}` + ) + // pass the v1 error along for the publish modal to handle + const err = { forwardResponse: body } + return callback(err) + } + } ) }, - historyVersion(cb) { - return ProjectHistoryHandler.ensureHistoryExistsForProject( - project_id, - function (error) { - if (error != null) { - return callback(error) + + _requestVersion(project_id, callback) { + if (callback == null) { + callback = function () {} + } + return request.get( + { + url: `${settings.apis.project_history.url}/project/${project_id}/version`, + json: true, + }, + function (err, res, body) { + if (err != null) { + OError.tag(err, 'error making request to project history', { + project_id, + }) + return callback(err) + } else if (res.statusCode >= 200 && res.statusCode < 300) { + return callback(null, body.version) + } else { + err = new OError( + `project history version returned a failure status code: ${res.statusCode}`, + { project_id } + ) + return callback(err) + } + } + ) + }, + + fetchExport(export_id, callback) { + if (callback == null) { + callback = function () {} + } + return request.get( + { + url: `${settings.apis.v1.url}/api/v1/sharelatex/exports/${export_id}`, + auth: { user: settings.apis.v1.user, pass: settings.apis.v1.pass }, + }, + function (err, res, body) { + if (err != null) { + OError.tag(err, 'error making request to v1 export', { + export: export_id, + }) + return callback(err) + } else if (res.statusCode >= 200 && res.statusCode < 300) { + return callback(null, body) + } else { + err = new OError( + `v1 export returned a failure status code: ${res.statusCode}`, + { export: export_id } + ) + return callback(err) + } + } + ) + }, + + fetchDownload(export_id, type, callback) { + if (callback == null) { + callback = function () {} + } + return request.get( + { + url: `${settings.apis.v1.url}/api/v1/sharelatex/exports/${export_id}/${type}_url`, + auth: { user: settings.apis.v1.user, pass: settings.apis.v1.pass }, + }, + function (err, res, body) { + if (err != null) { + OError.tag(err, 'error making request to v1 export', { + export: export_id, + }) + return callback(err) + } else if (res.statusCode >= 200 && res.statusCode < 300) { + return callback(null, body) + } else { + err = new OError( + `v1 export returned a failure status code: ${res.statusCode}`, + { export: export_id } + ) + return callback(err) } - return self._requestVersion(project_id, cb) } ) }, } - return async.auto(jobs, function (err, results) { - if (err != null) { - OError.tag(err, 'error building project export', { - project_id, - user_id, - brand_variation_id, - }) - return callback(err) - } - - const { project, rootDoc, user, historyVersion } = results - if (!rootDoc || rootDoc[1] == null) { - err = new OError('cannot export project without root doc', { - project_id, - }) - return callback(err) - } - - if (export_params.first_name && export_params.last_name) { - user.first_name = export_params.first_name - user.last_name = export_params.last_name - } - - const export_data = { - project: { - id: project_id, - rootDocPath: rootDoc[1] != null ? rootDoc[1].fileSystem : undefined, - historyId: __guard__( - project.overleaf != null ? project.overleaf.history : undefined, - x => x.id - ), - historyVersion, - v1ProjectId: - project.overleaf != null ? project.overleaf.id : undefined, - metadata: { - compiler: project.compiler, - imageName: project.imageName, - title, - description, - author, - license, - showSource: show_source, - }, - }, - user: { - id: user_id, - firstName: user.first_name, - lastName: user.last_name, - email: user.email, - orcidId: null, // until v2 gets ORCID - v1UserId: user.overleaf != null ? user.overleaf.id : undefined, - }, - destination: { - brandVariationId: brand_variation_id, - }, - options: { - callbackUrl: null, - }, // for now, until we want v1 to call us back - } - return callback(null, export_data) - }) - }, - - _requestExport(export_data, callback) { - if (callback == null) { - callback = function () {} - } - return request.post( - { - url: `${settings.apis.v1.url}/api/v1/sharelatex/exports`, - auth: { user: settings.apis.v1.user, pass: settings.apis.v1.pass }, - json: export_data, - }, - function (err, res, body) { - if (err != null) { - OError.tag(err, 'error making request to v1 export', { - export: export_data, - }) - return callback(err) - } else if (res.statusCode >= 200 && res.statusCode < 300) { - return callback(null, body) - } else { - logger.warn( - { export: export_data }, - `v1 export returned failure; forwarding: ${body}` - ) - // pass the v1 error along for the publish modal to handle - const err = { forwardResponse: body } - return callback(err) - } - } - ) - }, - - _requestVersion(project_id, callback) { - if (callback == null) { - callback = function () {} - } - return request.get( - { - url: `${settings.apis.project_history.url}/project/${project_id}/version`, - json: true, - }, - function (err, res, body) { - if (err != null) { - OError.tag(err, 'error making request to project history', { - project_id, - }) - return callback(err) - } else if (res.statusCode >= 200 && res.statusCode < 300) { - return callback(null, body.version) - } else { - err = new OError( - `project history version returned a failure status code: ${res.statusCode}`, - { project_id } - ) - return callback(err) - } - } - ) - }, - - fetchExport(export_id, callback) { - if (callback == null) { - callback = function () {} - } - return request.get( - { - url: `${settings.apis.v1.url}/api/v1/sharelatex/exports/${export_id}`, - auth: { user: settings.apis.v1.user, pass: settings.apis.v1.pass }, - }, - function (err, res, body) { - if (err != null) { - OError.tag(err, 'error making request to v1 export', { - export: export_id, - }) - return callback(err) - } else if (res.statusCode >= 200 && res.statusCode < 300) { - return callback(null, body) - } else { - err = new OError( - `v1 export returned a failure status code: ${res.statusCode}`, - { export: export_id } - ) - return callback(err) - } - } - ) - }, - - fetchDownload(export_id, type, callback) { - if (callback == null) { - callback = function () {} - } - return request.get( - { - url: `${settings.apis.v1.url}/api/v1/sharelatex/exports/${export_id}/${type}_url`, - auth: { user: settings.apis.v1.user, pass: settings.apis.v1.pass }, - }, - function (err, res, body) { - if (err != null) { - OError.tag(err, 'error making request to v1 export', { - export: export_id, - }) - return callback(err) - } else if (res.statusCode >= 200 && res.statusCode < 300) { - return callback(null, body) - } else { - err = new OError( - `v1 export returned a failure status code: ${res.statusCode}`, - { export: export_id } - ) - return callback(err) - } - } - ) - }, -} - function __guard__(value, transform) { return typeof value !== 'undefined' && value !== null ? transform(value) diff --git a/services/web/app/src/Features/Helpers/EmailHelper.js b/services/web/app/src/Features/Helpers/EmailHelper.js index 99f944739b..79d112f7a5 100644 --- a/services/web/app/src/Features/Helpers/EmailHelper.js +++ b/services/web/app/src/Features/Helpers/EmailHelper.js @@ -1,5 +1,6 @@ -// eslint-disable-next-line no-useless-escape -const EMAIL_REGEXP = /^([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ +const EMAIL_REGEXP = + // eslint-disable-next-line no-useless-escape + /^([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ function getDomain(email) { email = parseEmail(email) diff --git a/services/web/app/src/Features/InactiveData/InactiveProjectManager.js b/services/web/app/src/Features/InactiveData/InactiveProjectManager.js index 0495370260..afc808ca9f 100644 --- a/services/web/app/src/Features/InactiveData/InactiveProjectManager.js +++ b/services/web/app/src/Features/InactiveData/InactiveProjectManager.js @@ -78,16 +78,21 @@ module.exports = InactiveProjectManager = { if (err != null) { logger.err({ err }, 'could not get projects for deactivating') } - const jobs = _.map(projects, project => cb => - InactiveProjectManager.deactivateProject(project._id, function (err) { - if (err) { - logger.err( - { project_id: project._id, err: err }, - 'unable to deactivate project' - ) - } - cb() - }) + const jobs = _.map( + projects, + project => cb => + InactiveProjectManager.deactivateProject( + project._id, + function (err) { + if (err) { + logger.err( + { project_id: project._id, err: err }, + 'unable to deactivate project' + ) + } + cb() + } + ) ) logger.log( { numberOfProjects: projects && projects.length }, diff --git a/services/web/app/src/Features/Institutions/InstitutionsManager.js b/services/web/app/src/Features/Institutions/InstitutionsManager.js index 16c3de08b4..a5e89a29e5 100644 --- a/services/web/app/src/Features/Institutions/InstitutionsManager.js +++ b/services/web/app/src/Features/Institutions/InstitutionsManager.js @@ -125,11 +125,8 @@ async function checkInstitutionUsers(institutionId, emitNonProUserIds) { ) result.ssoUsers.current.entitled = entitled - const { - allSsoUsers, - allSsoUsersByIds, - currentNotEntitledCount, - } = await _getSsoUsers(institutionId, lapsedUserIds) + const { allSsoUsers, allSsoUsersByIds, currentNotEntitledCount } = + await _getSsoUsers(institutionId, lapsedUserIds) result.ssoUsers.total = allSsoUsers.length result.ssoUsers.current.notEntitled = currentNotEntitledCount diff --git a/services/web/app/src/Features/LinkedFiles/ProjectOutputFileAgent.js b/services/web/app/src/Features/LinkedFiles/ProjectOutputFileAgent.js index ec11c102f5..730328ea65 100644 --- a/services/web/app/src/Features/LinkedFiles/ProjectOutputFileAgent.js +++ b/services/web/app/src/Features/LinkedFiles/ProjectOutputFileAgent.js @@ -168,10 +168,8 @@ function _checkAuth(projectId, data, currentUserId, callback) { function _getFileStream(linkedFileData, userId, callback) { callback = _.once(callback) - const { - source_output_file_path: sourceOutputFilePath, - build_id: buildId, - } = linkedFileData + const { source_output_file_path: sourceOutputFilePath, build_id: buildId } = + linkedFileData LinkedFilesHandler.getSourceProject(linkedFileData, (err, project) => { if (err) { return callback(err) diff --git a/services/web/app/src/Features/Project/ProjectController.js b/services/web/app/src/Features/Project/ProjectController.js index de7ba65ac2..bedb40e138 100644 --- a/services/web/app/src/Features/Project/ProjectController.js +++ b/services/web/app/src/Features/Project/ProjectController.js @@ -357,9 +357,8 @@ const ProjectController = { if (err != null) { return next(err) } - const { docs, files } = ProjectEntityHandler.getAllEntitiesFromProject( - project - ) + const { docs, files } = + ProjectEntityHandler.getAllEntitiesFromProject(project) const entities = docs .concat(files) // Sort by path ascending @@ -553,9 +552,8 @@ const ProjectController = { delete req.session.saml } - const portalTemplates = ProjectController._buildPortalTemplatesList( - userAffiliations - ) + const portalTemplates = + ProjectController._buildPortalTemplatesList(userAffiliations) const projects = ProjectController._buildProjectList( results.projects, userId @@ -798,9 +796,8 @@ const ProjectController = { req, projectId ) - const allowedImageNames = ProjectHelper.getAllowedImagesForUser( - sessionUser - ) + const allowedImageNames = + ProjectHelper.getAllowedImagesForUser(sessionUser) AuthorizationManager.getPrivilegeLevelForProject( userId, @@ -1028,13 +1025,8 @@ const ProjectController = { _buildProjectList(allProjects, userId) { let project - const { - owned, - readAndWrite, - readOnly, - tokenReadAndWrite, - tokenReadOnly, - } = allProjects + const { owned, readAndWrite, readOnly, tokenReadAndWrite, tokenReadOnly } = + allProjects const projects = [] for (project of owned) { projects.push( diff --git a/services/web/app/src/Features/Project/ProjectDetailsHandler.js b/services/web/app/src/Features/Project/ProjectDetailsHandler.js index 90ef7548c1..4bc932bdba 100644 --- a/services/web/app/src/Features/Project/ProjectDetailsHandler.js +++ b/services/web/app/src/Features/Project/ProjectDetailsHandler.js @@ -144,10 +144,8 @@ async function validateProjectName(name) { // with a unique name. But that requires thinking through how we would handle incoming projects from // dropbox for example. async function generateUniqueName(userId, name, suffixes = []) { - const allUsersProjectNames = await ProjectGetter.promises.findAllUsersProjects( - userId, - { name: 1 } - ) + const allUsersProjectNames = + await ProjectGetter.promises.findAllUsersProjects(userId, { name: 1 }) // allUsersProjectNames is returned as a hash {owned: [name1, name2, ...], readOnly: [....]} // collect all of the names and flatten them into a single array const projectNameList = _.pluck( @@ -241,6 +239,7 @@ async function _generateTokens(project, callback) { tokens.readAndWritePrefix = numericPrefix } if (tokens.readOnly == null) { - tokens.readOnly = await TokenGenerator.promises.generateUniqueReadOnlyToken() + tokens.readOnly = + await TokenGenerator.promises.generateUniqueReadOnlyToken() } } diff --git a/services/web/app/src/Features/Project/ProjectDuplicator.js b/services/web/app/src/Features/Project/ProjectDuplicator.js index e06949f2ca..c10779f581 100644 --- a/services/web/app/src/Features/Project/ProjectDuplicator.js +++ b/services/web/app/src/Features/Project/ProjectDuplicator.js @@ -66,11 +66,12 @@ async function duplicate(owner, originalProjectId, newProjectName) { _copyDocs(originalEntries.docEntries, originalProject, newProject), _copyFiles(originalEntries.fileEntries, originalProject, newProject), ]) - const projectVersion = await ProjectEntityMongoUpdateHandler.promises.createNewFolderStructure( - newProject._id, - docEntries, - fileEntries - ) + const projectVersion = + await ProjectEntityMongoUpdateHandler.promises.createNewFolderStructure( + newProject._id, + docEntries, + fileEntries + ) // Silently ignore the rootDoc in case it's not valid per the new limits. if ( rootDocPath && diff --git a/services/web/app/src/Features/Project/ProjectEditorHandler.js b/services/web/app/src/Features/Project/ProjectEditorHandler.js index 649eba5983..81d6db6afb 100644 --- a/services/web/app/src/Features/Project/ProjectEditorHandler.js +++ b/services/web/app/src/Features/Project/ProjectEditorHandler.js @@ -62,9 +62,8 @@ module.exports = ProjectEditorHandler = { result.invites.forEach(invite => { delete invite.token }) - ;({ owner, ownerFeatures, members } = this.buildOwnerAndMembersViews( - members - )) + ;({ owner, ownerFeatures, members } = + this.buildOwnerAndMembersViews(members)) result.owner = owner result.members = members diff --git a/services/web/app/src/Features/Project/ProjectEntityMongoUpdateHandler.js b/services/web/app/src/Features/Project/ProjectEntityMongoUpdateHandler.js index 5aa7e4fd68..46b16ffdd9 100644 --- a/services/web/app/src/Features/Project/ProjectEntityMongoUpdateHandler.js +++ b/services/web/app/src/Features/Project/ProjectEntityMongoUpdateHandler.js @@ -257,21 +257,18 @@ async function mkdirp(projectId, path, options = {}) { for (const folderName of folders) { builtUpPath += `/${folderName}` try { - const { - element: foundFolder, - } = await ProjectLocator.promises.findElementByPath({ - project, - path: builtUpPath, - exactCaseMatch: options.exactCaseMatch, - }) + const { element: foundFolder } = + await ProjectLocator.promises.findElementByPath({ + project, + path: builtUpPath, + exactCaseMatch: options.exactCaseMatch, + }) lastFolder = foundFolder } catch (err) { // Folder couldn't be found. Create it. const parentFolderId = lastFolder && lastFolder._id - const { - folder: newFolder, - parentFolderId: newParentFolderId, - } = await addFolder(projectId, parentFolderId, folderName) + const { folder: newFolder, parentFolderId: newParentFolderId } = + await addFolder(projectId, parentFolderId, folderName) newFolder.parentFolder_id = newParentFolderId lastFolder = newFolder newFolders.push(newFolder) @@ -285,23 +282,19 @@ async function moveEntity(projectId, entityId, destFolderId, entityType) { projectId, { rootFolder: true, name: true, overleaf: true } ) - const { - element: entity, - path: entityPath, - } = await ProjectLocator.promises.findElement({ - project, - element_id: entityId, - type: entityType, - }) + const { element: entity, path: entityPath } = + await ProjectLocator.promises.findElement({ + project, + element_id: entityId, + type: entityType, + }) // Prevent top-level docs/files with reserved names (to match v1 behaviour) if (_blockedFilename(entityPath, entityType)) { throw new Errors.InvalidNameError('blocked element name') } await _checkValidMove(project, entityType, entity, entityPath, destFolderId) - const { - docs: oldDocs, - files: oldFiles, - } = ProjectEntityHandler.getAllEntitiesFromProject(project) + const { docs: oldDocs, files: oldFiles } = + ProjectEntityHandler.getAllEntitiesFromProject(project) // For safety, insert the entity in the destination // location first, and then remove the original. If // there is an error the entity may appear twice. This @@ -328,10 +321,8 @@ async function moveEntity(projectId, entityId, destFolderId, entityType) { entityPath.mongo, entityId ) - const { - docs: newDocs, - files: newFiles, - } = ProjectEntityHandler.getAllEntitiesFromProject(newProject) + const { docs: newDocs, files: newFiles } = + ProjectEntityHandler.getAllEntitiesFromProject(newProject) const startPath = entityPath.fileSystem const endPath = result.path.fileSystem const changes = { @@ -418,10 +409,8 @@ async function renameEntity( // check if the new name already exists in the current folder _checkValidElementName(parentFolder, newName) - const { - docs: oldDocs, - files: oldFiles, - } = ProjectEntityHandler.getAllEntitiesFromProject(project) + const { docs: oldDocs, files: oldFiles } = + ProjectEntityHandler.getAllEntitiesFromProject(project) // we need to increment the project version number for any structure change const newProject = await Project.findOneAndUpdate( @@ -430,10 +419,8 @@ async function renameEntity( { new: true } ).exec() - const { - docs: newDocs, - files: newFiles, - } = ProjectEntityHandler.getAllEntitiesFromProject(newProject) + const { docs: newDocs, files: newFiles } = + ProjectEntityHandler.getAllEntitiesFromProject(newProject) return { project, startPath, @@ -618,14 +605,12 @@ async function _checkValidMove( entityPath, destFolderId ) { - const { - element: destEntity, - path: destFolderPath, - } = await ProjectLocator.promises.findElement({ - project, - element_id: destFolderId, - type: 'folder', - }) + const { element: destEntity, path: destFolderPath } = + await ProjectLocator.promises.findElement({ + project, + element_id: destFolderId, + type: 'folder', + }) // check if there is already a doc/file/folder with the same name // in the destination folder _checkValidElementName(destEntity, entity.name) diff --git a/services/web/app/src/Features/Project/ProjectEntityUpdateHandler.js b/services/web/app/src/Features/Project/ProjectEntityUpdateHandler.js index 30b98a97bb..08d1580f4d 100644 --- a/services/web/app/src/Features/Project/ProjectEntityUpdateHandler.js +++ b/services/web/app/src/Features/Project/ProjectEntityUpdateHandler.js @@ -1349,11 +1349,8 @@ const ProjectEntityUpdateHandler = { return callback(error) } - let { - docs, - files, - folders, - } = ProjectEntityHandler.getAllEntitiesFromProject(project) + let { docs, files, folders } = + ProjectEntityHandler.getAllEntitiesFromProject(project) // _checkFileTree() must be passed the folders before docs and // files ProjectEntityUpdateHandler._checkFiletree( diff --git a/services/web/app/src/Features/References/ReferencesHandler.js b/services/web/app/src/Features/References/ReferencesHandler.js index 8f634317a2..f0ba20c5cd 100644 --- a/services/web/app/src/Features/References/ReferencesHandler.js +++ b/services/web/app/src/Features/References/ReferencesHandler.js @@ -166,8 +166,9 @@ module.exports = ReferencesHandler = { 'flushing docs to mongo before calling references service' ) return Async.series( - docIds.map(docId => cb => - DocumentUpdaterHandler.flushDocToMongo(projectId, docId, cb) + docIds.map( + docId => cb => + DocumentUpdaterHandler.flushDocToMongo(projectId, docId, cb) ), function (err) { // continue diff --git a/services/web/app/src/Features/SplitTests/SplitTestMiddleware.js b/services/web/app/src/Features/SplitTests/SplitTestMiddleware.js index 38ef4fcfde..8355dedd97 100644 --- a/services/web/app/src/Features/SplitTests/SplitTestMiddleware.js +++ b/services/web/app/src/Features/SplitTests/SplitTestMiddleware.js @@ -41,10 +41,11 @@ async function _loadAssignmentInLocals(splitTest, session, locals) { if (cachedVariant) { LocalsHelper.setSplitTestVariant(locals, splitTest.name, cachedVariant) } else { - const assignment = await SplitTestV2Handler.promises.getAssignmentForSession( - session, - splitTest.name - ) + const assignment = + await SplitTestV2Handler.promises.getAssignmentForSession( + session, + splitTest.name + ) session.cachedSplitTestAssignments[cacheKey] = assignment.variant LocalsHelper.setSplitTestVariant( locals, diff --git a/services/web/app/src/Features/SplitTests/SplitTestV2Handler.js b/services/web/app/src/Features/SplitTests/SplitTestV2Handler.js index 4f3dd1bb42..d01fa38073 100644 --- a/services/web/app/src/Features/SplitTests/SplitTestV2Handler.js +++ b/services/web/app/src/Features/SplitTests/SplitTestV2Handler.js @@ -138,12 +138,8 @@ async function _getAssignment( if (splitTest) { const currentVersion = splitTest.getCurrentVersion() if (currentVersion.active) { - const { - activeForUser, - selectedVariantName, - phase, - versionNumber, - } = await _getAssignmentMetadata(analyticsId, userId, splitTest) + const { activeForUser, selectedVariantName, phase, versionNumber } = + await _getAssignmentMetadata(analyticsId, userId, splitTest) if (activeForUser) { const assignmentConfig = { userId, diff --git a/services/web/app/src/Features/Subscription/FeaturesUpdater.js b/services/web/app/src/Features/Subscription/FeaturesUpdater.js index b1872a6294..fff97d76f9 100644 --- a/services/web/app/src/Features/Subscription/FeaturesUpdater.js +++ b/services/web/app/src/Features/Subscription/FeaturesUpdater.js @@ -48,10 +48,8 @@ async function refreshFeatures(userId, reason) { matchedFeatureSet ) - const { - features: newFeatures, - featuresChanged, - } = await UserFeaturesUpdater.promises.updateFeatures(userId, features) + const { features: newFeatures, featuresChanged } = + await UserFeaturesUpdater.promises.updateFeatures(userId, features) if (oldFeatures.dropbox === true && features.dropbox === false) { logger.log({ userId }, '[FeaturesUpdater] must unlink dropbox') const Modules = require('../../infrastructure/Modules') @@ -70,9 +68,8 @@ async function refreshFeatures(userId, reason) { async function computeFeatures(userId) { const individualFeatures = await _getIndividualFeatures(userId) const groupFeatureSets = await _getGroupFeatureSets(userId) - const institutionFeatures = await InstitutionsFeatures.promises.getInstitutionsFeatures( - userId - ) + const institutionFeatures = + await InstitutionsFeatures.promises.getInstitutionsFeatures(userId) const v1Features = await _getV1Features(userId) const bonusFeatures = await ReferalFeatures.promises.getBonusFeatures(userId) const featuresOverrides = await _getFeaturesOverrides(userId) @@ -144,10 +141,8 @@ async function _getFeaturesOverrides(userId) { async function _getV1Features(userId) { let planCode, v1Id try { - ;({ - planCode, - v1Id, - } = await V1SubscriptionManager.promises.getPlanCodeFromV1(userId)) + ;({ planCode, v1Id } = + await V1SubscriptionManager.promises.getPlanCodeFromV1(userId)) } catch (err) { if (err.name === 'NotFoundError') { return {} diff --git a/services/web/app/src/Features/Subscription/LimitationsManager.js b/services/web/app/src/Features/Subscription/LimitationsManager.js index 5405f9a6ad..91d4fa409d 100644 --- a/services/web/app/src/Features/Subscription/LimitationsManager.js +++ b/services/web/app/src/Features/Subscription/LimitationsManager.js @@ -197,9 +197,8 @@ const LimitationsManager = { return callback(new Error('no subscription found')) } - const limitReached = LimitationsManager.teamHasReachedMemberLimit( - subscription - ) + const limitReached = + LimitationsManager.teamHasReachedMemberLimit(subscription) callback(err, limitReached, subscription) } ) diff --git a/services/web/app/src/Features/Subscription/RecurlyWrapper.js b/services/web/app/src/Features/Subscription/RecurlyWrapper.js index 9133544581..f5f70334c8 100644 --- a/services/web/app/src/Features/Subscription/RecurlyWrapper.js +++ b/services/web/app/src/Features/Subscription/RecurlyWrapper.js @@ -283,9 +283,8 @@ const RecurlyWrapper = { account_code: user._id, }, } - const customFields = getCustomFieldsFromSubscriptionDetails( - subscriptionDetails - ) + const customFields = + getCustomFieldsFromSubscriptionDetails(subscriptionDetails) if (customFields) { data.custom_fields = customFields } @@ -395,9 +394,8 @@ const RecurlyWrapper = { data.account.billing_info.three_d_secure_action_result_token_id = recurlyTokenIds.threeDSecureActionResult } - const customFields = getCustomFieldsFromSubscriptionDetails( - subscriptionDetails - ) + const customFields = + getCustomFieldsFromSubscriptionDetails(subscriptionDetails) if (customFields) { data.custom_fields = customFields } @@ -525,9 +523,8 @@ const RecurlyWrapper = { recurlySubscription.account != null && recurlySubscription.account.url != null ) { - accountId = recurlySubscription.account.url.match( - /accounts\/(.*)/ - )[1] + accountId = + recurlySubscription.account.url.match(/accounts\/(.*)/)[1] } else { return callback( new Error("I don't understand the response from Recurly") diff --git a/services/web/app/src/Features/Subscription/SubscriptionController.js b/services/web/app/src/Features/Subscription/SubscriptionController.js index ff58a5d4f8..a436207fc1 100644 --- a/services/web/app/src/Features/Subscription/SubscriptionController.js +++ b/services/web/app/src/Features/Subscription/SubscriptionController.js @@ -30,11 +30,10 @@ const validGroupPlanModalOptions = { async function plansPage(req, res) { const plans = SubscriptionViewModelBuilder.buildPlansList() - const { - currencyCode: recommendedCurrency, - } = await GeoIpLookup.promises.getCurrencyCode( - (req.query ? req.query.ip : undefined) || req.ip - ) + const { currencyCode: recommendedCurrency } = + await GeoIpLookup.promises.getCurrencyCode( + (req.query ? req.query.ip : undefined) || req.ip + ) function getDefault(param, category, defaultValue) { const v = req.query && req.query[param] @@ -77,17 +76,17 @@ async function paymentPage(req, res) { if (!plan) { return HttpErrorHandler.unprocessableEntity(req, res, 'Plan not found') } - const hasSubscription = await LimitationsManager.promises.userHasV1OrV2Subscription( - user - ) + const hasSubscription = + await LimitationsManager.promises.userHasV1OrV2Subscription(user) if (hasSubscription) { res.redirect('/user/subscription?hasSubscription=true') } else { // LimitationsManager.userHasV2Subscription only checks Mongo. Double check with // Recurly as well at this point (we don't do this most places for speed). - const valid = await SubscriptionHandler.promises.validateNoSubscriptionInRecurly( - user._id - ) + const valid = + await SubscriptionHandler.promises.validateNoSubscriptionInRecurly( + user._id + ) if (!valid) { res.redirect('/user/subscription?hasSubscription=true') } else { @@ -98,12 +97,10 @@ async function paymentPage(req, res) { currency = queryCurrency } } - const { - currencyCode: recommendedCurrency, - countryCode, - } = await GeoIpLookup.promises.getCurrencyCode( - (req.query ? req.query.ip : undefined) || req.ip - ) + const { currencyCode: recommendedCurrency, countryCode } = + await GeoIpLookup.promises.getCurrencyCode( + (req.query ? req.query.ip : undefined) || req.ip + ) if (recommendedCurrency && currency == null) { currency = recommendedCurrency } @@ -127,9 +124,10 @@ async function paymentPage(req, res) { async function userSubscriptionPage(req, res) { const user = SessionManager.getSessionUser(req.session) - const results = await SubscriptionViewModelBuilder.promises.buildUsersSubscriptionViewModel( - user - ) + const results = + await SubscriptionViewModelBuilder.promises.buildUsersSubscriptionViewModel( + user + ) const { personalSubscription, memberGroupSubscriptions, @@ -139,9 +137,8 @@ async function userSubscriptionPage(req, res) { managedPublishers, v1SubscriptionStatus, } = results - const hasSubscription = await LimitationsManager.promises.userHasV1OrV2Subscription( - user - ) + const hasSubscription = + await LimitationsManager.promises.userHasV1OrV2Subscription(user) const fromPlansPage = req.query.hasSubscription const plans = SubscriptionViewModelBuilder.buildPlansList( personalSubscription ? personalSubscription.plan : undefined @@ -446,9 +443,8 @@ function processUpgradeToAnnualPlan(req, res, next) { async function extendTrial(req, res) { const user = SessionManager.getSessionUser(req.session) - const { - subscription, - } = await LimitationsManager.promises.userHasV2Subscription(user) + const { subscription } = + await LimitationsManager.promises.userHasV2Subscription(user) try { await SubscriptionHandler.promises.extendTrial(subscription, 14) @@ -485,10 +481,11 @@ async function refreshUserFeatures(req, res) { async function redirectToHostedPage(req, res) { const userId = SessionManager.getLoggedInUserId(req.session) const { pageType } = req.params - const url = await SubscriptionViewModelBuilder.promises.getRedirectToHostedPage( - userId, - pageType - ) + const url = + await SubscriptionViewModelBuilder.promises.getRedirectToHostedPage( + userId, + pageType + ) logger.warn({ userId, pageType }, 'redirecting to recurly hosted page') res.redirect(url) } diff --git a/services/web/app/src/Features/Subscription/SubscriptionUpdater.js b/services/web/app/src/Features/Subscription/SubscriptionUpdater.js index c658012b79..8aecc0a437 100644 --- a/services/web/app/src/Features/Subscription/SubscriptionUpdater.js +++ b/services/web/app/src/Features/Subscription/SubscriptionUpdater.js @@ -79,9 +79,8 @@ async function removeUserFromGroup(subscriptionId, userId) { } async function removeUserFromAllGroups(userId) { - const subscriptions = await SubscriptionLocator.promises.getMemberSubscriptions( - userId - ) + const subscriptions = + await SubscriptionLocator.promises.getMemberSubscriptions(userId) if (subscriptions.length === 0) { return } @@ -114,9 +113,8 @@ async function deleteSubscription(subscription, deleterData) { } async function restoreSubscription(subscriptionId) { - const deletedSubscription = await SubscriptionLocator.promises.getDeletedSubscription( - subscriptionId - ) + const deletedSubscription = + await SubscriptionLocator.promises.getDeletedSubscription(subscriptionId) const subscription = deletedSubscription.subscription // 1. upsert subscription @@ -249,9 +247,8 @@ async function updateSubscriptionFromRecurly( async function _sendUserGroupPlanCodeUserProperty(userId) { try { - const subscriptions = await SubscriptionLocator.promises.getMemberSubscriptions( - userId - ) + const subscriptions = + await SubscriptionLocator.promises.getMemberSubscriptions(userId) let bestPlanCode = null let bestFeatures = {} for (const subscription of subscriptions) { diff --git a/services/web/app/src/Features/Subscription/SubscriptionViewModelBuilder.js b/services/web/app/src/Features/Subscription/SubscriptionViewModelBuilder.js index fa90149151..b715ed7ca0 100644 --- a/services/web/app/src/Features/Subscription/SubscriptionViewModelBuilder.js +++ b/services/web/app/src/Features/Subscription/SubscriptionViewModelBuilder.js @@ -21,9 +21,8 @@ async function getRedirectToHostedPage(userId, pageType) { if (!['billing-details', 'account-management'].includes(pageType)) { throw new InvalidError('unexpected page type') } - const personalSubscription = await SubscriptionLocator.promises.getUsersSubscription( - userId - ) + const personalSubscription = + await SubscriptionLocator.promises.getUsersSubscription(userId) const recurlySubscriptionId = personalSubscription?.recurlySubscription_id if (!recurlySubscriptionId) { throw new NotFoundError('not a recurly subscription') @@ -253,23 +252,27 @@ function buildUsersSubscriptionViewModel(user, callback) { const pendingSubscriptionTax = personalSubscription.recurly.taxRate * recurlySubscription.pending_subscription.unit_amount_in_cents - personalSubscription.recurly.price = SubscriptionFormatters.formatPrice( - recurlySubscription.pending_subscription.unit_amount_in_cents + - pendingAddOnPrice + - pendingAddOnTax + - pendingSubscriptionTax, - recurlySubscription.currency - ) + personalSubscription.recurly.price = + SubscriptionFormatters.formatPrice( + recurlySubscription.pending_subscription.unit_amount_in_cents + + pendingAddOnPrice + + pendingAddOnTax + + pendingSubscriptionTax, + recurlySubscription.currency + ) const pendingTotalLicenses = (pendingPlan.membersLimit || 0) + pendingAdditionalLicenses - personalSubscription.recurly.pendingAdditionalLicenses = pendingAdditionalLicenses - personalSubscription.recurly.pendingTotalLicenses = pendingTotalLicenses + personalSubscription.recurly.pendingAdditionalLicenses = + pendingAdditionalLicenses + personalSubscription.recurly.pendingTotalLicenses = + pendingTotalLicenses personalSubscription.pendingPlan = pendingPlan } else { - personalSubscription.recurly.price = SubscriptionFormatters.formatPrice( - recurlySubscription.unit_amount_in_cents + addOnPrice + tax, - recurlySubscription.currency - ) + personalSubscription.recurly.price = + SubscriptionFormatters.formatPrice( + recurlySubscription.unit_amount_in_cents + addOnPrice + tax, + recurlySubscription.currency + ) } } diff --git a/services/web/app/src/Features/ThirdPartyDataStore/TpdsUpdateSender.js b/services/web/app/src/Features/ThirdPartyDataStore/TpdsUpdateSender.js index 69f7f7a2ea..9e3cc3a6ab 100644 --- a/services/web/app/src/Features/ThirdPartyDataStore/TpdsUpdateSender.js +++ b/services/web/app/src/Features/ThirdPartyDataStore/TpdsUpdateSender.js @@ -7,8 +7,8 @@ const path = require('path') const request = require('request-promise-native') const settings = require('@overleaf/settings') -const CollaboratorsGetter = require('../Collaborators/CollaboratorsGetter') - .promises +const CollaboratorsGetter = + require('../Collaborators/CollaboratorsGetter').promises const UserGetter = require('../User/UserGetter.js').promises const tpdsUrl = _.get(settings, ['apis', 'thirdPartyDataStore', 'url']) @@ -149,10 +149,8 @@ async function enqueue(group, method, job) { async function getProjectUsersIds(projectId) { // get list of all user ids with access to project. project owner // will always be the first entry in the list. - const [ - ownerUserId, - ...invitedUserIds - ] = await CollaboratorsGetter.getInvitedMemberIds(projectId) + const [ownerUserId, ...invitedUserIds] = + await CollaboratorsGetter.getInvitedMemberIds(projectId) // if there are no invited users, always return the owner if (!invitedUserIds.length) { return [ownerUserId] diff --git a/services/web/app/src/Features/TokenAccess/TokenAccessController.js b/services/web/app/src/Features/TokenAccess/TokenAccessController.js index e9b8031788..6ece78fdc2 100644 --- a/services/web/app/src/Features/TokenAccess/TokenAccessController.js +++ b/services/web/app/src/Features/TokenAccess/TokenAccessController.js @@ -25,11 +25,12 @@ async function _userAlreadyHasHigherPrivilege( if (!Object.values(TokenAccessHandler.TOKEN_TYPES).includes(tokenType)) { throw new Error('bad token type') } - const privilegeLevel = await AuthorizationManager.promises.getPrivilegeLevelForProject( - userId, - projectId, - token - ) + const privilegeLevel = + await AuthorizationManager.promises.getPrivilegeLevelForProject( + userId, + projectId, + token + ) return ( orderedPrivilegeLevels.indexOf(privilegeLevel) >= orderedPrivilegeLevels.indexOf(tokenType) @@ -84,9 +85,8 @@ async function tokenAccessPage(req, res, next) { } try { if (TokenAccessHandler.isReadOnlyToken(token)) { - const docPublishedInfo = await TokenAccessHandler.promises.getV1DocPublishedInfo( - token - ) + const docPublishedInfo = + await TokenAccessHandler.promises.getV1DocPublishedInfo(token) if (docPublishedInfo.allow === false) { return res.redirect(302, docPublishedInfo.published_path) } @@ -135,9 +135,8 @@ async function checkAndGetProjectOrResponseAction( const projectId = project._id const isAnonymousUser = !userId - const tokenAccessEnabled = TokenAccessHandler.tokenAccessEnabledForProject( - project - ) + const tokenAccessEnabled = + TokenAccessHandler.tokenAccessEnabledForProject(project) if (isAnonymousUser && tokenAccessEnabled) { if (tokenType === TokenAccessHandler.TOKEN_TYPES.READ_AND_WRITE) { if (TokenAccessHandler.ANONYMOUS_READ_AND_WRITE_ENABLED) { @@ -260,9 +259,8 @@ async function grantTokenAccessReadOnly(req, res, next) { return res.sendStatus(400) } const tokenType = TokenAccessHandler.TOKEN_TYPES.READ_ONLY - const docPublishedInfo = await TokenAccessHandler.promises.getV1DocPublishedInfo( - token - ) + const docPublishedInfo = + await TokenAccessHandler.promises.getV1DocPublishedInfo(token) if (docPublishedInfo.allow === false) { return res.json({ redirect: docPublishedInfo.published_path }) } diff --git a/services/web/app/src/Features/Uploads/ProjectUploadManager.js b/services/web/app/src/Features/Uploads/ProjectUploadManager.js index 47a75799b1..dd70e6a9ee 100644 --- a/services/web/app/src/Features/Uploads/ProjectUploadManager.js +++ b/services/web/app/src/Features/Uploads/ProjectUploadManager.js @@ -29,12 +29,10 @@ module.exports = { async function createProjectFromZipArchive(ownerId, defaultName, zipPath) { const contentsPath = await _extractZip(zipPath) - const { - path, - content, - } = await ProjectRootDocManager.promises.findRootDocFileFromDirectory( - contentsPath - ) + const { path, content } = + await ProjectRootDocManager.promises.findRootDocFileFromDirectory( + contentsPath + ) const projectName = DocumentHelper.getTitleFromTexContent(content || '') || defaultName @@ -131,11 +129,12 @@ async function _initializeProjectWithZipContents( project._id, importEntries ) - const projectVersion = await ProjectEntityMongoUpdateHandler.promises.createNewFolderStructure( - project._id, - docEntries, - fileEntries - ) + const projectVersion = + await ProjectEntityMongoUpdateHandler.promises.createNewFolderStructure( + project._id, + docEntries, + fileEntries + ) await _notifyDocumentUpdater(project, ownerId, { newFiles: fileEntries, newDocs: docEntries, diff --git a/services/web/app/src/Features/User/SAMLIdentityManager.js b/services/web/app/src/Features/User/SAMLIdentityManager.js index 581071be70..8659bf84a1 100644 --- a/services/web/app/src/Features/User/SAMLIdentityManager.js +++ b/services/web/app/src/Features/User/SAMLIdentityManager.js @@ -223,9 +223,8 @@ async function getUser(providerId, externalUserId) { } async function redundantSubscription(userId, providerId, providerName) { - const subscription = await SubscriptionLocator.promises.getUserIndividualSubscription( - userId - ) + const subscription = + await SubscriptionLocator.promises.getUserIndividualSubscription(userId) if (subscription) { await NotificationsBuilder.promises diff --git a/services/web/app/src/Features/User/UserGetter.js b/services/web/app/src/Features/User/UserGetter.js index 798aa7ba80..e54e84b9fa 100644 --- a/services/web/app/src/Features/User/UserGetter.js +++ b/services/web/app/src/Features/User/UserGetter.js @@ -264,9 +264,8 @@ const decorateFullEmails = ( ) } - emailData.emailHasInstitutionLicence = InstitutionsHelper.emailHasLicence( - emailData - ) + emailData.emailHasInstitutionLicence = + InstitutionsHelper.emailHasLicence(emailData) }) return emailsData diff --git a/services/web/app/src/Features/User/UserSessionsManager.js b/services/web/app/src/Features/User/UserSessionsManager.js index e8839204b8..43f355b8b1 100644 --- a/services/web/app/src/Features/User/UserSessionsManager.js +++ b/services/web/app/src/Features/User/UserSessionsManager.js @@ -217,19 +217,20 @@ const UserSessionsManager = { return callback(err) } Async.series( - sessionKeys.map(key => next => - rclient.get(key, function (err, val) { - if (err) { - return next(err) - } - if (!val) { - rclient.srem(sessionSetKey, key, function (err, result) { + sessionKeys.map( + key => next => + rclient.get(key, function (err, val) { + if (err) { return next(err) - }) - } else { - next() - } - }) + } + if (!val) { + rclient.srem(sessionSetKey, key, function (err, result) { + return next(err) + }) + } else { + next() + } + }) ), function (err, results) { callback(err) diff --git a/services/web/app/src/Features/UserMembership/UserMembershipController.js b/services/web/app/src/Features/UserMembership/UserMembershipController.js index 43ffef3f4c..c106783e46 100644 --- a/services/web/app/src/Features/UserMembership/UserMembershipController.js +++ b/services/web/app/src/Features/UserMembership/UserMembershipController.js @@ -31,9 +31,8 @@ module.exports = { if (error != null) { return next(error) } - const entityPrimaryKey = entity[ - entityConfig.fields.primaryKey - ].toString() + const entityPrimaryKey = + entity[entityConfig.fields.primaryKey].toString() if (entityConfig.fields.name) { entityName = entity[entityConfig.fields.name] } diff --git a/services/web/app/src/Features/UserMembership/UserMembershipMiddleware.js b/services/web/app/src/Features/UserMembership/UserMembershipMiddleware.js index 76f9e8285b..d84730b927 100644 --- a/services/web/app/src/Features/UserMembership/UserMembershipMiddleware.js +++ b/services/web/app/src/Features/UserMembership/UserMembershipMiddleware.js @@ -198,10 +198,11 @@ function fetchEntityConfig(entityName) { // fetch the entity with id and config, and set it in the request function fetchEntity() { return expressify(async (req, res, next) => { - const entity = await UserMembershipHandler.promises.getEntityWithoutAuthorizationCheck( - req.params.id, - req.entityConfig - ) + const entity = + await UserMembershipHandler.promises.getEntityWithoutAuthorizationCheck( + req.params.id, + req.entityConfig + ) req.entity = entity next() }) diff --git a/services/web/app/src/infrastructure/Features.js b/services/web/app/src/infrastructure/Features.js index 72c10472fe..badfd40655 100644 --- a/services/web/app/src/infrastructure/Features.js +++ b/services/web/app/src/infrastructure/Features.js @@ -1,19 +1,16 @@ const _ = require('lodash') const Settings = require('@overleaf/settings') -const publicRegistrationModuleAvailable = Settings.moduleImportSequence.includes( - 'public-registration' -) +const publicRegistrationModuleAvailable = + Settings.moduleImportSequence.includes('public-registration') const supportModuleAvailable = Settings.moduleImportSequence.includes('support') -const historyV1ModuleAvailable = Settings.moduleImportSequence.includes( - 'history-v1' -) +const historyV1ModuleAvailable = + Settings.moduleImportSequence.includes('history-v1') -const trackChangesModuleAvailable = Settings.moduleImportSequence.includes( - 'track-changes' -) +const trackChangesModuleAvailable = + Settings.moduleImportSequence.includes('track-changes') /** * @typedef {Object} Settings diff --git a/services/web/app/src/infrastructure/Translations.js b/services/web/app/src/infrastructure/Translations.js index af92ca5f08..81f6905d8e 100644 --- a/services/web/app/src/infrastructure/Translations.js +++ b/services/web/app/src/infrastructure/Translations.js @@ -77,9 +77,8 @@ function setLangBasedOnDomainMiddleware(req, res, next) { // offering to switch to the appropriate library const detectedLanguageCode = headerLangDetector.detect(req, res) if (req.language !== detectedLanguageCode) { - res.locals.suggestedLanguageSubdomainConfig = subdomainConfigs.get( - detectedLanguageCode - ) + res.locals.suggestedLanguageSubdomainConfig = + subdomainConfigs.get(detectedLanguageCode) } // Decorate req.i18n with translate function alias for backwards diff --git a/services/web/frontend/js/directives/onEnter.js b/services/web/frontend/js/directives/onEnter.js index 7c99867ffc..ce6a66159a 100644 --- a/services/web/frontend/js/directives/onEnter.js +++ b/services/web/frontend/js/directives/onEnter.js @@ -7,11 +7,13 @@ */ import App from '../base' -export default App.directive('onEnter', () => (scope, element, attrs) => - element.bind('keydown keypress', function (event) { - if (event.which === 13) { - scope.$apply(() => scope.$eval(attrs.onEnter, { event })) - return event.preventDefault() - } - }) +export default App.directive( + 'onEnter', + () => (scope, element, attrs) => + element.bind('keydown keypress', function (event) { + if (event.which === 13) { + scope.$apply(() => scope.$eval(attrs.onEnter, { event })) + return event.preventDefault() + } + }) ) diff --git a/services/web/frontend/js/features/clone-project-modal/components/clone-project-modal-content.js b/services/web/frontend/js/features/clone-project-modal/components/clone-project-modal-content.js index 585ec3f180..6b71689816 100644 --- a/services/web/frontend/js/features/clone-project-modal/components/clone-project-modal-content.js +++ b/services/web/frontend/js/features/clone-project-modal/components/clone-project-modal-content.js @@ -27,9 +27,10 @@ export default function CloneProjectModalContent({ ) // valid if the cloned project has a name - const valid = useMemo(() => clonedProjectName.trim().length > 0, [ - clonedProjectName, - ]) + const valid = useMemo( + () => clonedProjectName.trim().length > 0, + [clonedProjectName] + ) // form submission: clone the project if the name is valid const handleSubmit = event => { diff --git a/services/web/frontend/js/features/editor-navigation-toolbar/components/editor-navigation-toolbar-root.js b/services/web/frontend/js/features/editor-navigation-toolbar/components/editor-navigation-toolbar-root.js index 3b51cebd9a..6bba84ca07 100644 --- a/services/web/frontend/js/features/editor-navigation-toolbar/components/editor-navigation-toolbar-root.js +++ b/services/web/frontend/js/features/editor-navigation-toolbar/components/editor-navigation-toolbar-root.js @@ -69,9 +69,8 @@ const EditorNavigationToolbarRoot = React.memo( pdfLayout, } = useLayoutContext(layoutContextPropTypes) - const { markMessagesAsRead, unreadMessageCount } = useChatContext( - chatContextPropTypes - ) + const { markMessagesAsRead, unreadMessageCount } = + useChatContext(chatContextPropTypes) const toggleChatOpen = useCallback(() => { if (!chatIsOpen) { diff --git a/services/web/frontend/js/features/file-tree/components/file-tree-context-menu.js b/services/web/frontend/js/features/file-tree/components/file-tree-context-menu.js index 2e2ec06093..da980730ab 100644 --- a/services/web/frontend/js/features/file-tree/components/file-tree-context-menu.js +++ b/services/web/frontend/js/features/file-tree/components/file-tree-context-menu.js @@ -7,11 +7,8 @@ import { useFileTreeMainContext } from '../contexts/file-tree-main' import FileTreeItemMenuItems from './file-tree-item/file-tree-item-menu-items' function FileTreeContextMenu() { - const { - hasWritePermissions, - contextMenuCoords, - setContextMenuCoords, - } = useFileTreeMainContext() + const { hasWritePermissions, contextMenuCoords, setContextMenuCoords } = + useFileTreeMainContext() if (!hasWritePermissions || !contextMenuCoords) return null diff --git a/services/web/frontend/js/features/file-tree/components/file-tree-create/modes/file-tree-import-from-project.js b/services/web/frontend/js/features/file-tree/components/file-tree-create/modes/file-tree-import-from-project.js index f71d69f3e1..e251fee737 100644 --- a/services/web/frontend/js/features/file-tree/components/file-tree-create/modes/file-tree-import-from-project.js +++ b/services/web/frontend/js/features/file-tree/components/file-tree-create/modes/file-tree-import-from-project.js @@ -16,10 +16,8 @@ import ErrorMessage from '../error-message' export default function FileTreeImportFromProject() { const { t } = useTranslation() - const { - hasLinkedProjectFileFeature, - hasLinkedProjectOutputFileFeature, - } = window.ExposedSettings + const { hasLinkedProjectFileFeature, hasLinkedProjectOutputFileFeature } = + window.ExposedSettings const canSwitchOutputFilesMode = hasLinkedProjectFileFeature && hasLinkedProjectOutputFileFeature diff --git a/services/web/frontend/js/features/file-tree/components/file-tree-item/file-tree-item-name.js b/services/web/frontend/js/features/file-tree/components/file-tree-item/file-tree-item-name.js index 65a3472964..aadb1e1174 100644 --- a/services/web/frontend/js/features/file-tree/components/file-tree-item/file-tree-item-name.js +++ b/services/web/frontend/js/features/file-tree/components/file-tree-item/file-tree-item-name.js @@ -9,13 +9,8 @@ import { useFileTreeMainContext } from '../../contexts/file-tree-main' function FileTreeItemName({ name, isSelected, setIsDraggable }) { const { hasWritePermissions } = useFileTreeMainContext() - const { - isRenaming, - startRenaming, - finishRenaming, - error, - cancel, - } = useFileTreeActionable() + const { isRenaming, startRenaming, finishRenaming, error, cancel } = + useFileTreeActionable() const isRenamingEntity = isRenaming && isSelected && !error diff --git a/services/web/frontend/js/features/file-tree/components/file-tree-toolbar.js b/services/web/frontend/js/features/file-tree/components/file-tree-toolbar.js index 9e53483d7d..c2fe3ff235 100644 --- a/services/web/frontend/js/features/file-tree/components/file-tree-toolbar.js +++ b/services/web/frontend/js/features/file-tree/components/file-tree-toolbar.js @@ -63,12 +63,8 @@ function FileTreeToolbarLeft() { function FileTreeToolbarRight() { const { t } = useTranslation() - const { - canRename, - canDelete, - startRenaming, - startDeleting, - } = useFileTreeActionable() + const { canRename, canDelete, startRenaming, startDeleting } = + useFileTreeActionable() if (!canRename && !canDelete) { return null diff --git a/services/web/frontend/js/features/file-tree/components/modals/file-tree-modal-create-folder.js b/services/web/frontend/js/features/file-tree/components/modals/file-tree-modal-create-folder.js index cdffa65950..054d7fb664 100644 --- a/services/web/frontend/js/features/file-tree/components/modals/file-tree-modal-create-folder.js +++ b/services/web/frontend/js/features/file-tree/components/modals/file-tree-modal-create-folder.js @@ -18,13 +18,8 @@ function FileTreeModalCreateFolder() { const [name, setName] = useState('') const [validName, setValidName] = useState(true) - const { - isCreatingFolder, - inFlight, - finishCreatingFolder, - cancel, - error, - } = useFileTreeActionable() + const { isCreatingFolder, inFlight, finishCreatingFolder, cancel, error } = + useFileTreeActionable() if (!isCreatingFolder) return null // the modal will not be rendered; return early diff --git a/services/web/frontend/js/features/file-tree/controllers/file-tree-controller.js b/services/web/frontend/js/features/file-tree/controllers/file-tree-controller.js index 76d54bf508..31d0d048e8 100644 --- a/services/web/frontend/js/features/file-tree/controllers/file-tree-controller.js +++ b/services/web/frontend/js/features/file-tree/controllers/file-tree-controller.js @@ -5,116 +5,119 @@ import { cloneDeep } from 'lodash' import FileTreeRoot from '../components/file-tree-root' import { rootContext } from '../../../shared/context/root-context' -App.controller('ReactFileTreeController', function ( - $scope, - $timeout, - ide - // eventTracking -) { - $scope.projectId = ide.project_id - $scope.rootFolder = null - $scope.rootDocId = null - $scope.hasWritePermissions = false - $scope.isConnected = true +App.controller( + 'ReactFileTreeController', + function ( + $scope, + $timeout, + ide + // eventTracking + ) { + $scope.projectId = ide.project_id + $scope.rootFolder = null + $scope.rootDocId = null + $scope.hasWritePermissions = false + $scope.isConnected = true - $scope.$on('project:joined', () => { - $scope.rootFolder = $scope.project.rootFolder - $scope.rootDocId = $scope.project.rootDoc_id - $scope.$emit('file-tree:initialized') - }) - - $scope.$watch('permissions.write', hasWritePermissions => { - $scope.hasWritePermissions = hasWritePermissions - }) - - $scope.$watch('editor.open_doc_id', openDocId => { - window.dispatchEvent( - new CustomEvent('editor.openDoc', { detail: openDocId }) - ) - }) - - // Set isConnected to true if: - // - connection state is 'ready', OR - // - connection state is 'waitingCountdown' and reconnection_countdown is null - // The added complexity is needed because in Firefox on page reload the - // connection state goes into 'waitingCountdown' before being hidden and we - // don't want to show a disconnect UI. - function updateIsConnected() { - const isReady = $scope.connection.state === 'ready' - const willStartCountdown = - $scope.connection.state === 'waitingCountdown' && - $scope.connection.reconnection_countdown === null - $scope.isConnected = isReady || willStartCountdown - } - - $scope.$watch('connection.state', updateIsConnected) - $scope.$watch('connection.reconnection_countdown', updateIsConnected) - - $scope.onInit = () => { - // HACK: resize the vertical pane on init after a 0ms timeout. We do not - // understand why this is necessary but without this the resized handle is - // stuck at the bottom. The vertical resize will soon be migrated to React - // so we accept to live with this hack for now. - $timeout(() => { - $scope.$emit('left-pane-resize-all') + $scope.$on('project:joined', () => { + $scope.rootFolder = $scope.project.rootFolder + $scope.rootDocId = $scope.project.rootDoc_id + $scope.$emit('file-tree:initialized') }) - } - $scope.onSelect = selectedEntities => { - if (selectedEntities.length === 1) { - const selectedEntity = selectedEntities[0] - const type = - selectedEntity.type === 'fileRef' ? 'file' : selectedEntity.type - $scope.$emit('entity:selected', { - ...selectedEntity.entity, - id: selectedEntity.entity._id, - type, - }) + $scope.$watch('permissions.write', hasWritePermissions => { + $scope.hasWritePermissions = hasWritePermissions + }) - // in the react implementation there is no such concept as "1 - // multi-selected entity" so here we pass a count of 0 - $scope.$emit('entities:multiSelected', { count: 0 }) - } else if (selectedEntities.length > 1) { - $scope.$emit('entities:multiSelected', { - count: selectedEntities.length, + $scope.$watch('editor.open_doc_id', openDocId => { + window.dispatchEvent( + new CustomEvent('editor.openDoc', { detail: openDocId }) + ) + }) + + // Set isConnected to true if: + // - connection state is 'ready', OR + // - connection state is 'waitingCountdown' and reconnection_countdown is null + // The added complexity is needed because in Firefox on page reload the + // connection state goes into 'waitingCountdown' before being hidden and we + // don't want to show a disconnect UI. + function updateIsConnected() { + const isReady = $scope.connection.state === 'ready' + const willStartCountdown = + $scope.connection.state === 'waitingCountdown' && + $scope.connection.reconnection_countdown === null + $scope.isConnected = isReady || willStartCountdown + } + + $scope.$watch('connection.state', updateIsConnected) + $scope.$watch('connection.reconnection_countdown', updateIsConnected) + + $scope.onInit = () => { + // HACK: resize the vertical pane on init after a 0ms timeout. We do not + // understand why this is necessary but without this the resized handle is + // stuck at the bottom. The vertical resize will soon be migrated to React + // so we accept to live with this hack for now. + $timeout(() => { + $scope.$emit('left-pane-resize-all') }) - } else { - $scope.$emit('entity:no-selection') + } + + $scope.onSelect = selectedEntities => { + if (selectedEntities.length === 1) { + const selectedEntity = selectedEntities[0] + const type = + selectedEntity.type === 'fileRef' ? 'file' : selectedEntity.type + $scope.$emit('entity:selected', { + ...selectedEntity.entity, + id: selectedEntity.entity._id, + type, + }) + + // in the react implementation there is no such concept as "1 + // multi-selected entity" so here we pass a count of 0 + $scope.$emit('entities:multiSelected', { count: 0 }) + } else if (selectedEntities.length > 1) { + $scope.$emit('entities:multiSelected', { + count: selectedEntities.length, + }) + } else { + $scope.$emit('entity:no-selection') + } + } + + $scope.userHasFeature = feature => ide.$scope.user.features[feature] + + $scope.$watch('permissions.write', hasWritePermissions => { + $scope.hasWritePermissions = hasWritePermissions + }) + + $scope.refProviders = ide.$scope.user.refProviders || {} + + ide.$scope.$watch( + 'user.refProviders', + refProviders => { + $scope.refProviders = cloneDeep(refProviders) + }, + true + ) + + $scope.setRefProviderEnabled = provider => { + ide.$scope.$applyAsync(() => { + ide.$scope.user.refProviders[provider] = true + }) + } + + $scope.setStartedFreeTrial = started => { + $scope.$applyAsync(() => { + $scope.startedFreeTrial = started + }) + } + + $scope.reindexReferences = () => { + ide.$scope.$emit('references:should-reindex', {}) } } - - $scope.userHasFeature = feature => ide.$scope.user.features[feature] - - $scope.$watch('permissions.write', hasWritePermissions => { - $scope.hasWritePermissions = hasWritePermissions - }) - - $scope.refProviders = ide.$scope.user.refProviders || {} - - ide.$scope.$watch( - 'user.refProviders', - refProviders => { - $scope.refProviders = cloneDeep(refProviders) - }, - true - ) - - $scope.setRefProviderEnabled = provider => { - ide.$scope.$applyAsync(() => { - ide.$scope.user.refProviders[provider] = true - }) - } - - $scope.setStartedFreeTrial = started => { - $scope.$applyAsync(() => { - $scope.startedFreeTrial = started - }) - } - - $scope.reindexReferences = () => { - ide.$scope.$emit('references:should-reindex', {}) - } -}) +) App.component( 'fileTreeRoot', diff --git a/services/web/frontend/js/features/file-tree/hooks/file-tree-socket-listener.js b/services/web/frontend/js/features/file-tree/hooks/file-tree-socket-listener.js index daf335cf4c..3a1e8731b8 100644 --- a/services/web/frontend/js/features/file-tree/hooks/file-tree-socket-listener.js +++ b/services/web/frontend/js/features/file-tree/hooks/file-tree-socket-listener.js @@ -19,12 +19,8 @@ export function useFileTreeSocketListener() { dispatchCreateFile, fileTreeData, } = useFileTreeMutable() - const { - selectedEntityIds, - selectedEntityParentIds, - select, - unselect, - } = useFileTreeSelectable() + const { selectedEntityIds, selectedEntityParentIds, select, unselect } = + useFileTreeSelectable() const socket = window._ide && window._ide.socket const selectEntityIfCreatedByUser = useCallback( diff --git a/services/web/frontend/js/features/pdf-preview/components/detach-compile-button.js b/services/web/frontend/js/features/pdf-preview/components/detach-compile-button.js index da13d7eb0d..0f0ece8e1d 100644 --- a/services/web/frontend/js/features/pdf-preview/components/detach-compile-button.js +++ b/services/web/frontend/js/features/pdf-preview/components/detach-compile-button.js @@ -16,9 +16,10 @@ export function DetachCompileButton() { 'detached' ) - const handleStartCompile = useCallback(() => startOrTriggerCompile(), [ - startOrTriggerCompile, - ]) + const handleStartCompile = useCallback( + () => startOrTriggerCompile(), + [startOrTriggerCompile] + ) return (
lorem ipsum
', + body: 'lorem ipsum
', }) const promise = getJSON('/test') diff --git a/services/web/test/karma/ide/editor/aceEditor/spell-check/SpellCheckManagerTests.js b/services/web/test/karma/ide/editor/aceEditor/spell-check/SpellCheckManagerTests.js index 56597bf9b4..9e17e04027 100644 --- a/services/web/test/karma/ide/editor/aceEditor/spell-check/SpellCheckManagerTests.js +++ b/services/web/test/karma/ide/editor/aceEditor/spell-check/SpellCheckManagerTests.js @@ -100,16 +100,7 @@ export default describe('SpellCheckManager', function () { this.timelord.tick(500) this.$httpBackend.flush() expect(this.adapter.getLinesByRows).to.have.been.calledWith([ - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ]) }) }) diff --git a/services/web/test/karma/ide/history/HistoryV2ManagerTests.js b/services/web/test/karma/ide/history/HistoryV2ManagerTests.js index 84c5300604..f9e7c64c12 100644 --- a/services/web/test/karma/ide/history/HistoryV2ManagerTests.js +++ b/services/web/test/karma/ide/history/HistoryV2ManagerTests.js @@ -270,7 +270,8 @@ export default describe('HistoryV2Manager', function () { describe('with a previously selected file', function () { it('should prefer the previously selected file if it is available and has operations', function () { - this.historyManager._previouslySelectedPathname = this.mockedAddedFile.pathname + this.historyManager._previouslySelectedPathname = + this.mockedAddedFile.pathname this.historyManager.autoSelectFile() expect(this.$scope.history.selection.file).to.deep.equal( this.mockedAddedFile @@ -278,7 +279,8 @@ export default describe('HistoryV2Manager', function () { }) it('should prefer a file with ops if the previously selected file is available but has no operations', function () { - this.historyManager._previouslySelectedPathname = this.mockedReferencesFile.pathname + this.historyManager._previouslySelectedPathname = + this.mockedReferencesFile.pathname this.historyManager.autoSelectFile() expect(this.$scope.history.selection.file.operation).to.exist }) @@ -335,9 +337,8 @@ export default describe('HistoryV2Manager', function () { this.mockedAddedFile ) this.$scope.history.selection.files.splice(indexOfAddedFile, 1) - const indexOfRenamedFile = this.$scope.history.selection.files.indexOf( - this.mockedRenamedFile - ) + const indexOfRenamedFile = + this.$scope.history.selection.files.indexOf(this.mockedRenamedFile) this.$scope.history.selection.files.splice(indexOfRenamedFile, 1) this.historyManager.autoSelectFile() expect(this.$scope.history.selection.file).to.deep.equal( @@ -392,9 +393,8 @@ export default describe('HistoryV2Manager', function () { this.mockedMainTex ) this.$scope.history.selection.files.splice(indexOfMainTex, 1) - const indexOfOtherTexFile = this.$scope.history.selection.files.indexOf( - this.mockedOtherTexFile - ) + const indexOfOtherTexFile = + this.$scope.history.selection.files.indexOf(this.mockedOtherTexFile) this.$scope.history.selection.files.splice(indexOfOtherTexFile, 1) this.historyManager.autoSelectFile() expect(this.$scope.history.selection.file).to.deep.equal( @@ -440,8 +440,10 @@ export default describe('HistoryV2Manager', function () { ], } this.sampleUpdateEditedFile = this.sampleUpdates[0].pathnames[0] - this.sampleUpdateAddedFile = this.sampleUpdates[0].project_ops[0].add.pathname - this.sampleUpdateRenamedFile = this.sampleUpdates[0].project_ops[1].rename.newPathname + this.sampleUpdateAddedFile = + this.sampleUpdates[0].project_ops[0].add.pathname + this.sampleUpdateRenamedFile = + this.sampleUpdates[0].project_ops[1].rename.newPathname this.$scope.history.updates = this.sampleUpdates this.$scope.history.selection.range = { fromV: this.sampleUpdates[0].toV, @@ -625,19 +627,18 @@ export default describe('HistoryV2Manager', function () { ] const lastUpdate = 5 - this.historyManager.$scope.history.labels = this.historyManager._loadLabels( - this.historyManager.$scope.history.labels, - lastUpdate - ) + this.historyManager.$scope.history.labels = + this.historyManager._loadLabels( + this.historyManager.$scope.history.labels, + lastUpdate + ) expect( this.historyManager.$scope.history.labels[0].isPseudoCurrentStateLabel ).to.equal(true) - this.historyManager.$scope.history.labels = this.historyManager._loadLabels( - [], - lastUpdate - ) + this.historyManager.$scope.history.labels = + this.historyManager._loadLabels([], lastUpdate) expect( this.historyManager.$scope.history.labels[0].isPseudoCurrentStateLabel ).to.equal(true) diff --git a/services/web/test/unit/src/Authentication/AuthenticationControllerTests.js b/services/web/test/unit/src/Authentication/AuthenticationControllerTests.js index 0f95ee0012..20526dd825 100644 --- a/services/web/test/unit/src/Authentication/AuthenticationControllerTests.js +++ b/services/web/test/unit/src/Authentication/AuthenticationControllerTests.js @@ -58,7 +58,8 @@ describe('AuthenticationController', function () { identifyUser: sinon.stub(), getIdsFromSession: sinon.stub().returns({ userId: this.user._id }), }), - '../../infrastructure/SessionStoreManager': (this.SessionStoreManager = {}), + '../../infrastructure/SessionStoreManager': (this.SessionStoreManager = + {}), '@overleaf/settings': (this.Settings = { siteUrl: 'http://www.foo.bar', httpAuthUsers: this.httpAuthUsers, @@ -78,13 +79,14 @@ describe('AuthenticationController', function () { ipMatcherAffiliation: sinon.stub().returns({ create: sinon.stub() }), }), '../../models/User': { User: this.UserModel }, - '../../../../modules/oauth2-server/app/src/Oauth2Server': (this.Oauth2Server = { - Request: sinon.stub(), - Response: sinon.stub(), - server: { - authenticate: sinon.stub(), - }, - }), + '../../../../modules/oauth2-server/app/src/Oauth2Server': + (this.Oauth2Server = { + Request: sinon.stub(), + Response: sinon.stub(), + server: { + authenticate: sinon.stub(), + }, + }), '../Helpers/UrlHelper': (this.UrlHelper = { getSafeRedirectPath: sinon.stub(), }), @@ -413,7 +415,8 @@ describe('AuthenticationController', function () { describe('when the user is not logged in', function () { beforeEach(function () { this.req.session = {} - this.AuthenticationController._redirectToLoginOrRegisterPage = sinon.stub() + this.AuthenticationController._redirectToLoginOrRegisterPage = + sinon.stub() this.req.query = {} this.SessionManager.isUserLoggedIn = sinon.stub().returns(false) this.middleware(this.req, this.res, this.next) @@ -455,7 +458,8 @@ describe('AuthenticationController', function () { regenerate: sinon.stub().yields(), } this.req.user = this.user - this.AuthenticationController._redirectToLoginOrRegisterPage = sinon.stub() + this.AuthenticationController._redirectToLoginOrRegisterPage = + sinon.stub() this.req.query = {} this.SessionStoreManager.hasValidationToken = sinon .stub() diff --git a/services/web/test/unit/src/Authentication/AuthenticationManagerTests.js b/services/web/test/unit/src/Authentication/AuthenticationManagerTests.js index f825822e30..0fa27b829d 100644 --- a/services/web/test/unit/src/Authentication/AuthenticationManagerTests.js +++ b/services/web/test/unit/src/Authentication/AuthenticationManagerTests.js @@ -118,9 +118,8 @@ describe('AuthenticationManager', function () { 'testpassword', err => { expect(err).to.not.exist - const { - hashedPassword, - } = this.db.users.updateOne.lastCall.args[1].$set + const { hashedPassword } = + this.db.users.updateOne.lastCall.args[1].$set expect(hashedPassword).to.exist expect(hashedPassword.length).to.equal(60) expect(hashedPassword).to.match(/^\$2a\$04\$[a-zA-Z0-9/.]{53}$/) @@ -283,9 +282,8 @@ describe('AuthenticationManager', function () { describe('validateEmail', function () { describe('valid', function () { it('should return null', function () { - const result = this.AuthenticationManager.validateEmail( - 'foo@example.com' - ) + const result = + this.AuthenticationManager.validateEmail('foo@example.com') expect(result).to.equal(null) }) }) @@ -374,9 +372,8 @@ describe('AuthenticationManager', function () { }) it('should reject passwords that are too short', function () { - const result = this.AuthenticationManager.validatePassword( - '012345678' - ) + const result = + this.AuthenticationManager.validatePassword('012345678') expect(result).to.be.an.instanceOf( AuthenticationErrors.InvalidPasswordError @@ -392,9 +389,8 @@ describe('AuthenticationManager', function () { }) it('should reject passwords that are too long', function () { - const result = this.AuthenticationManager.validatePassword( - '0123456789abc' - ) + const result = + this.AuthenticationManager.validatePassword('0123456789abc') expect(result).to.be.an.instanceOf( AuthenticationErrors.InvalidPasswordError diff --git a/services/web/test/unit/src/Authorization/AuthorizationManagerTests.js b/services/web/test/unit/src/Authorization/AuthorizationManagerTests.js index 06e65c6207..e4849ea7ea 100644 --- a/services/web/test/unit/src/Authorization/AuthorizationManagerTests.js +++ b/services/web/test/unit/src/Authorization/AuthorizationManagerTests.js @@ -98,11 +98,12 @@ describe('AuthorizationManager', function () { this.CollaboratorsGetter.promises.getMemberIdPrivilegeLevel .withArgs(this.user._id, this.project._id) .resolves(PrivilegeLevels.READ_ONLY) - this.result = await this.AuthorizationManager.promises.getPrivilegeLevelForProject( - this.user._id, - this.project._id, - this.token - ) + this.result = + await this.AuthorizationManager.promises.getPrivilegeLevelForProject( + this.user._id, + this.project._id, + this.token + ) }) it("should return the user's privilege level", function () { @@ -112,11 +113,12 @@ describe('AuthorizationManager', function () { describe('with a user id with no privilege level', function () { beforeEach(async function () { - this.result = await this.AuthorizationManager.promises.getPrivilegeLevelForProject( - this.user._id, - this.project._id, - this.token - ) + this.result = + await this.AuthorizationManager.promises.getPrivilegeLevelForProject( + this.user._id, + this.project._id, + this.token + ) }) it('should return false', function () { @@ -127,11 +129,12 @@ describe('AuthorizationManager', function () { describe('with a user id who is an admin', function () { beforeEach(async function () { this.user.isAdmin = true - this.result = await this.AuthorizationManager.promises.getPrivilegeLevelForProject( - this.user._id, - this.project._id, - this.token - ) + this.result = + await this.AuthorizationManager.promises.getPrivilegeLevelForProject( + this.user._id, + this.project._id, + this.token + ) }) it('should return the user as an owner', function () { @@ -142,11 +145,12 @@ describe('AuthorizationManager', function () { describe('with no user (anonymous)', function () { describe('when the token is not valid', function () { beforeEach(async function () { - this.result = await this.AuthorizationManager.promises.getPrivilegeLevelForProject( - null, - this.project._id, - this.token - ) + this.result = + await this.AuthorizationManager.promises.getPrivilegeLevelForProject( + null, + this.project._id, + this.token + ) }) it('should not call CollaboratorsGetter.getMemberIdPrivilegeLevel', function () { @@ -169,15 +173,17 @@ describe('AuthorizationManager', function () { describe('when the token is valid for read-and-write', function () { beforeEach(async function () { - this.TokenAccessHandler.promises.validateTokenForAnonymousAccess = sinon - .stub() - .withArgs(this.project._id, this.token) - .resolves({ isValidReadAndWrite: true, isValidReadOnly: false }) - this.result = await this.AuthorizationManager.promises.getPrivilegeLevelForProject( - null, - this.project._id, - this.token - ) + this.TokenAccessHandler.promises.validateTokenForAnonymousAccess = + sinon + .stub() + .withArgs(this.project._id, this.token) + .resolves({ isValidReadAndWrite: true, isValidReadOnly: false }) + this.result = + await this.AuthorizationManager.promises.getPrivilegeLevelForProject( + null, + this.project._id, + this.token + ) }) it('should not call CollaboratorsGetter.getMemberIdPrivilegeLevel', function () { @@ -200,15 +206,17 @@ describe('AuthorizationManager', function () { describe('when the token is valid for read-only', function () { beforeEach(async function () { - this.TokenAccessHandler.promises.validateTokenForAnonymousAccess = sinon - .stub() - .withArgs(this.project._id, this.token) - .resolves({ isValidReadAndWrite: false, isValidReadOnly: true }) - this.result = await this.AuthorizationManager.promises.getPrivilegeLevelForProject( - null, - this.project._id, - this.token - ) + this.TokenAccessHandler.promises.validateTokenForAnonymousAccess = + sinon + .stub() + .withArgs(this.project._id, this.token) + .resolves({ isValidReadAndWrite: false, isValidReadOnly: true }) + this.result = + await this.AuthorizationManager.promises.getPrivilegeLevelForProject( + null, + this.project._id, + this.token + ) }) it('should not call CollaboratorsGetter.getMemberIdPrivilegeLevel', function () { @@ -241,11 +249,12 @@ describe('AuthorizationManager', function () { this.CollaboratorsGetter.promises.getMemberIdPrivilegeLevel .withArgs(this.user._id, this.project._id) .resolves(PrivilegeLevels.READ_ONLY) - this.result = await this.AuthorizationManager.promises.getPrivilegeLevelForProject( - this.user._id, - this.project._id, - this.token - ) + this.result = + await this.AuthorizationManager.promises.getPrivilegeLevelForProject( + this.user._id, + this.project._id, + this.token + ) }) it("should return the user's privilege level", function () { @@ -255,11 +264,12 @@ describe('AuthorizationManager', function () { describe('with a user id with no privilege level', function () { beforeEach(async function () { - this.result = await this.AuthorizationManager.promises.getPrivilegeLevelForProject( - this.user._id, - this.project._id, - this.token - ) + this.result = + await this.AuthorizationManager.promises.getPrivilegeLevelForProject( + this.user._id, + this.project._id, + this.token + ) }) it('should return false', function () { @@ -270,11 +280,12 @@ describe('AuthorizationManager', function () { describe('with a user id who is an admin', function () { beforeEach(async function () { this.user.isAdmin = true - this.result = await this.AuthorizationManager.promises.getPrivilegeLevelForProject( - this.user._id, - this.project._id, - this.token - ) + this.result = + await this.AuthorizationManager.promises.getPrivilegeLevelForProject( + this.user._id, + this.project._id, + this.token + ) }) it('should return the user as an owner', function () { @@ -284,11 +295,12 @@ describe('AuthorizationManager', function () { describe('with no user (anonymous)', function () { beforeEach(async function () { - this.result = await this.AuthorizationManager.promises.getPrivilegeLevelForProject( - null, - this.project._id, - this.token - ) + this.result = + await this.AuthorizationManager.promises.getPrivilegeLevelForProject( + null, + this.project._id, + this.token + ) }) it('should not call CollaboratorsGetter.getMemberIdPrivilegeLevel', function () { @@ -313,11 +325,12 @@ describe('AuthorizationManager', function () { this.CollaboratorsGetter.promises.getMemberIdPrivilegeLevel .withArgs(this.user._id, this.project._id) .resolves(PrivilegeLevels.READ_ONLY) - this.result = await this.AuthorizationManager.promises.getPrivilegeLevelForProject( - this.user._id, - this.project._id, - this.token - ) + this.result = + await this.AuthorizationManager.promises.getPrivilegeLevelForProject( + this.user._id, + this.project._id, + this.token + ) }) it("should return the user's privilege level", function () { @@ -327,11 +340,12 @@ describe('AuthorizationManager', function () { describe('with a user id with no privilege level', function () { beforeEach(async function () { - this.result = await this.AuthorizationManager.promises.getPrivilegeLevelForProject( - this.user._id, - this.project._id, - this.token - ) + this.result = + await this.AuthorizationManager.promises.getPrivilegeLevelForProject( + this.user._id, + this.project._id, + this.token + ) }) it('should return the public privilege level', function () { @@ -342,11 +356,12 @@ describe('AuthorizationManager', function () { describe('with a user id who is an admin', function () { beforeEach(async function () { this.user.isAdmin = true - this.result = await this.AuthorizationManager.promises.getPrivilegeLevelForProject( - this.user._id, - this.project._id, - this.token - ) + this.result = + await this.AuthorizationManager.promises.getPrivilegeLevelForProject( + this.user._id, + this.project._id, + this.token + ) }) it('should return the user as an owner', function () { @@ -356,11 +371,12 @@ describe('AuthorizationManager', function () { describe('with no user (anonymous)', function () { beforeEach(async function () { - this.result = await this.AuthorizationManager.promises.getPrivilegeLevelForProject( - null, - this.project._id, - this.token - ) + this.result = + await this.AuthorizationManager.promises.getPrivilegeLevelForProject( + null, + this.project._id, + this.token + ) }) it('should not call CollaboratorsGetter.getMemberIdPrivilegeLevel', function () { @@ -447,18 +463,20 @@ describe('AuthorizationManager', function () { }) it('should return true', async function () { - const isAdmin = await this.AuthorizationManager.promises.isUserSiteAdmin( - this.user._id - ) + const isAdmin = + await this.AuthorizationManager.promises.isUserSiteAdmin( + this.user._id + ) expect(isAdmin).to.equal(true) }) }) describe('when user is not admin', function () { it('should return false', async function () { - const isAdmin = await this.AuthorizationManager.promises.isUserSiteAdmin( - this.user._id - ) + const isAdmin = + await this.AuthorizationManager.promises.isUserSiteAdmin( + this.user._id + ) expect(isAdmin).to.equal(false) }) }) @@ -466,18 +484,16 @@ describe('AuthorizationManager', function () { describe('when user is not found', function () { it('should return false', async function () { const someOtherId = new ObjectId() - const isAdmin = await this.AuthorizationManager.promises.isUserSiteAdmin( - someOtherId - ) + const isAdmin = + await this.AuthorizationManager.promises.isUserSiteAdmin(someOtherId) expect(isAdmin).to.equal(false) }) }) describe('when no user is passed', function () { it('should return false', async function () { - const isAdmin = await this.AuthorizationManager.promises.isUserSiteAdmin( - null - ) + const isAdmin = + await this.AuthorizationManager.promises.isUserSiteAdmin(null) expect(isAdmin).to.equal(false) }) }) diff --git a/services/web/test/unit/src/Authorization/AuthorizationMiddlewareTests.js b/services/web/test/unit/src/Authorization/AuthorizationMiddlewareTests.js index 2bcfd51ac0..0509cf6bac 100644 --- a/services/web/test/unit/src/Authorization/AuthorizationMiddlewareTests.js +++ b/services/web/test/unit/src/Authorization/AuthorizationMiddlewareTests.js @@ -38,8 +38,8 @@ describe('AuthorizationMiddleware', function () { requires: { './AuthorizationManager': this.AuthorizationManager, '../Errors/HttpErrorHandler': this.HttpErrorHandler, - '../Authentication/AuthenticationController': this - .AuthenticationController, + '../Authentication/AuthenticationController': + this.AuthenticationController, '../Authentication/SessionManager': this.SessionManager, '../TokenAccess/TokenAccessHandler': this.TokenAccessHandler, }, diff --git a/services/web/test/unit/src/BetaProgram/BetaProgramControllerTests.js b/services/web/test/unit/src/BetaProgram/BetaProgramControllerTests.js index 8a785b2818..933d6d2200 100644 --- a/services/web/test/unit/src/BetaProgram/BetaProgramControllerTests.js +++ b/services/web/test/unit/src/BetaProgram/BetaProgramControllerTests.js @@ -33,9 +33,10 @@ describe('BetaProgramController', function () { '@overleaf/settings': (this.settings = { languages: {}, }), - '../Authentication/AuthenticationController': (this.AuthenticationController = { - getLoggedInUserId: sinon.stub().returns(this.user._id), - }), + '../Authentication/AuthenticationController': + (this.AuthenticationController = { + getLoggedInUserId: sinon.stub().returns(this.user._id), + }), }, }) this.res = { diff --git a/services/web/test/unit/src/Collaborators/CollaboratorsGetterTests.js b/services/web/test/unit/src/Collaborators/CollaboratorsGetterTests.js index bc0490141c..9857c9fde0 100644 --- a/services/web/test/unit/src/Collaborators/CollaboratorsGetterTests.js +++ b/services/web/test/unit/src/Collaborators/CollaboratorsGetterTests.js @@ -64,9 +64,10 @@ describe('CollaboratorsGetter', function () { describe('getMemberIdsWithPrivilegeLevels', function () { describe('with project', function () { it('should return an array of member ids with their privilege levels', async function () { - const result = await this.CollaboratorsGetter.promises.getMemberIdsWithPrivilegeLevels( - this.project._id - ) + const result = + await this.CollaboratorsGetter.promises.getMemberIdsWithPrivilegeLevels( + this.project._id + ) expect(result).to.have.deep.members([ { id: this.ownerRef.toString(), @@ -141,9 +142,10 @@ describe('CollaboratorsGetter', function () { describe('getInvitedMemberIds', function () { it('should return the invited ids', async function () { - const memberIds = await this.CollaboratorsGetter.promises.getInvitedMemberIds( - this.project._id - ) + const memberIds = + await this.CollaboratorsGetter.promises.getInvitedMemberIds( + this.project._id + ) expect(memberIds).to.have.members([ this.ownerRef.toString(), this.readOnlyRef1.toString(), @@ -171,9 +173,10 @@ describe('CollaboratorsGetter', function () { }) it('should return an array of invited members with their privilege levels', async function () { - const result = await this.CollaboratorsGetter.promises.getInvitedMembersWithPrivilegeLevels( - this.project._id - ) + const result = + await this.CollaboratorsGetter.promises.getInvitedMembersWithPrivilegeLevels( + this.project._id + ) expect(result).to.have.deep.members([ { user: { _id: this.readOnlyRef1 }, privilegeLevel: 'readOnly' }, { user: { _id: this.readWriteRef2 }, privilegeLevel: 'readAndWrite' }, @@ -183,18 +186,20 @@ describe('CollaboratorsGetter', function () { describe('getMemberIdPrivilegeLevel', function () { it('should return the privilege level if it exists', async function () { - const level = await this.CollaboratorsGetter.promises.getMemberIdPrivilegeLevel( - this.readOnlyRef1, - this.project._id - ) + const level = + await this.CollaboratorsGetter.promises.getMemberIdPrivilegeLevel( + this.readOnlyRef1, + this.project._id + ) expect(level).to.equal('readOnly') }) it('should return false if the member has no privilege level', async function () { - const level = await this.CollaboratorsGetter.promises.getMemberIdPrivilegeLevel( - this.nonMemberRef, - this.project._id - ) + const level = + await this.CollaboratorsGetter.promises.getMemberIdPrivilegeLevel( + this.nonMemberRef, + this.project._id + ) expect(level).to.equal(false) }) }) @@ -202,18 +207,20 @@ describe('CollaboratorsGetter', function () { describe('isUserInvitedMemberOfProject', function () { describe('when user is a member of the project', function () { it('should return true and the privilegeLevel', async function () { - const isMember = await this.CollaboratorsGetter.promises.isUserInvitedMemberOfProject( - this.readOnlyRef1 - ) + const isMember = + await this.CollaboratorsGetter.promises.isUserInvitedMemberOfProject( + this.readOnlyRef1 + ) expect(isMember).to.equal(true) }) }) describe('when user is not a member of the project', function () { it('should return false', async function () { - const isMember = await this.CollaboratorsGetter.promises.isUserInvitedMemberOfProject( - this.nonMemberRef - ) + const isMember = + await this.CollaboratorsGetter.promises.isUserInvitedMemberOfProject( + this.nonMemberRef + ) expect(isMember).to.equal(false) }) }) @@ -260,10 +267,11 @@ describe('CollaboratorsGetter', function () { }) it('should call the callback with the projects', async function () { - const projects = await this.CollaboratorsGetter.promises.getProjectsUserIsMemberOf( - this.userId, - this.fields - ) + const projects = + await this.CollaboratorsGetter.promises.getProjectsUserIsMemberOf( + this.userId, + this.fields + ) expect(projects).to.deep.equal({ readAndWrite: [ 'mock-read-write-project-1', @@ -311,9 +319,10 @@ describe('CollaboratorsGetter', function () { .withArgs(this.readWriteUser._id.toString()) .resolves(this.readWriteUser) this.ProjectEditorHandler.buildOwnerAndMembersViews.returns(this.views) - this.result = await this.CollaboratorsGetter.promises.getAllInvitedMembers( - this.project._id - ) + this.result = + await this.CollaboratorsGetter.promises.getAllInvitedMembers( + this.project._id + ) }) it('should produce a list of members', function () { @@ -332,19 +341,21 @@ describe('CollaboratorsGetter', function () { describe('userIsTokenMember', function () { it('should return true when the project is found', async function () { this.ProjectMock.expects('findOne').chain('exec').resolves(this.project) - const isMember = await this.CollaboratorsGetter.promises.userIsTokenMember( - this.userId, - this.project._id - ) + const isMember = + await this.CollaboratorsGetter.promises.userIsTokenMember( + this.userId, + this.project._id + ) expect(isMember).to.be.true }) it('should return false when the project is not found', async function () { this.ProjectMock.expects('findOne').chain('exec').resolves(null) - const isMember = await this.CollaboratorsGetter.promises.userIsTokenMember( - this.userId, - this.project._id - ) + const isMember = + await this.CollaboratorsGetter.promises.userIsTokenMember( + this.userId, + this.project._id + ) expect(isMember).to.be.false }) }) diff --git a/services/web/test/unit/src/Collaborators/CollaboratorsInviteControllerTests.js b/services/web/test/unit/src/Collaborators/CollaboratorsInviteControllerTests.js index 7f04d0ad03..7ff21a839f 100644 --- a/services/web/test/unit/src/Collaborators/CollaboratorsInviteControllerTests.js +++ b/services/web/test/unit/src/Collaborators/CollaboratorsInviteControllerTests.js @@ -52,8 +52,8 @@ describe('CollaboratorsInviteController', function () { emitToRoom: sinon.stub(), }), '../Analytics/AnalyticsManager': this.AnalyticsManger, - '../Authentication/AuthenticationController': this - .AuthenticationController, + '../Authentication/AuthenticationController': + this.AuthenticationController, '@overleaf/settings': (this.settings = {}), '../../infrastructure/RateLimiter': this.RateLimiter, }, diff --git a/services/web/test/unit/src/Collaborators/CollaboratorsInviteHandlerTests.js b/services/web/test/unit/src/Collaborators/CollaboratorsInviteHandlerTests.js index 08eca22d94..53fbedf858 100644 --- a/services/web/test/unit/src/Collaborators/CollaboratorsInviteHandlerTests.js +++ b/services/web/test/unit/src/Collaborators/CollaboratorsInviteHandlerTests.js @@ -62,7 +62,8 @@ describe('CollaboratorsInviteHandler', function () { }), '../User/UserGetter': (this.UserGetter = { getUser: sinon.stub() }), '../Project/ProjectGetter': (this.ProjectGetter = {}), - '../Notifications/NotificationsBuilder': (this.NotificationsBuilder = {}), + '../Notifications/NotificationsBuilder': (this.NotificationsBuilder = + {}), crypto: this.Crypto, }, }) @@ -368,9 +369,8 @@ describe('CollaboratorsInviteHandler', function () { describe('when _trySendInviteNotification produces an error', function () { beforeEach(function () { - return (this.CollaboratorsInviteHandler._trySendInviteNotification = sinon - .stub() - .callsArgWith(3, new Error('woops'))) + return (this.CollaboratorsInviteHandler._trySendInviteNotification = + sinon.stub().callsArgWith(3, new Error('woops'))) }) it('should produce an error', function (done) { diff --git a/services/web/test/unit/src/Compile/ClsiManagerTests.js b/services/web/test/unit/src/Compile/ClsiManagerTests.js index 656f2e7dfb..3d7531a4ac 100644 --- a/services/web/test/unit/src/Compile/ClsiManagerTests.js +++ b/services/web/test/unit/src/Compile/ClsiManagerTests.js @@ -54,8 +54,8 @@ describe('ClsiManager', function () { }, '../Project/ProjectEntityHandler': this.ProjectEntityHandler, '../Project/ProjectGetter': this.ProjectGetter, - '../DocumentUpdater/DocumentUpdaterHandler': this - .DocumentUpdaterHandler, + '../DocumentUpdater/DocumentUpdaterHandler': + this.DocumentUpdaterHandler, './ClsiCookieManager': () => this.ClsiCookieManager, './ClsiStateManager': this.ClsiStateManager, request: this.request, diff --git a/services/web/test/unit/src/Documents/DocumentControllerTests.js b/services/web/test/unit/src/Documents/DocumentControllerTests.js index a1b5da1b42..44b01f8d4e 100644 --- a/services/web/test/unit/src/Documents/DocumentControllerTests.js +++ b/services/web/test/unit/src/Documents/DocumentControllerTests.js @@ -13,7 +13,8 @@ describe('DocumentController', function () { '../Project/ProjectGetter': (this.ProjectGetter = {}), '../Project/ProjectLocator': (this.ProjectLocator = {}), '../Project/ProjectEntityHandler': (this.ProjectEntityHandler = {}), - '../Project/ProjectEntityUpdateHandler': (this.ProjectEntityUpdateHandler = {}), + '../Project/ProjectEntityUpdateHandler': + (this.ProjectEntityUpdateHandler = {}), }, }) this.res = new MockResponse() diff --git a/services/web/test/unit/src/Downloads/ProjectDownloadsControllerTests.js b/services/web/test/unit/src/Downloads/ProjectDownloadsControllerTests.js index 538c5bc7bd..4c9f0c3575 100644 --- a/services/web/test/unit/src/Downloads/ProjectDownloadsControllerTests.js +++ b/services/web/test/unit/src/Downloads/ProjectDownloadsControllerTests.js @@ -32,8 +32,8 @@ describe('ProjectDownloadsController', function () { './ProjectZipStreamManager': (this.ProjectZipStreamManager = {}), '../Project/ProjectGetter': (this.ProjectGetter = {}), '@overleaf/metrics': (this.metrics = {}), - '../DocumentUpdater/DocumentUpdaterHandler': this - .DocumentUpdaterHandler, + '../DocumentUpdater/DocumentUpdaterHandler': + this.DocumentUpdaterHandler, }, } )) diff --git a/services/web/test/unit/src/Editor/EditorControllerTests.js b/services/web/test/unit/src/Editor/EditorControllerTests.js index 8dca636c2d..8ad80de8b3 100644 --- a/services/web/test/unit/src/Editor/EditorControllerTests.js +++ b/services/web/test/unit/src/Editor/EditorControllerTests.js @@ -47,7 +47,8 @@ describe('EditorController', function () { return (this.EditorController = SandboxedModule.require(modulePath, { requires: { - '../Project/ProjectEntityUpdateHandler': (this.ProjectEntityUpdateHandler = {}), + '../Project/ProjectEntityUpdateHandler': + (this.ProjectEntityUpdateHandler = {}), '../Project/ProjectOptionsHandler': (this.ProjectOptionsHandler = { setCompiler: sinon.stub().yields(), setImageName: sinon.stub().yields(), @@ -59,10 +60,11 @@ describe('EditorController', function () { setPublicAccessLevel: sinon.stub().yields(), }), '../Project/ProjectDeleter': (this.ProjectDeleter = {}), - '../DocumentUpdater/DocumentUpdaterHandler': (this.DocumentUpdaterHandler = { - flushDocToMongo: sinon.stub().yields(), - setDocument: sinon.stub().yields(), - }), + '../DocumentUpdater/DocumentUpdaterHandler': + (this.DocumentUpdaterHandler = { + flushDocToMongo: sinon.stub().yields(), + setDocument: sinon.stub().yields(), + }), './EditorRealTimeController': (this.EditorRealTimeController = { emitToRoom: sinon.stub(), }), diff --git a/services/web/test/unit/src/Editor/EditorHttpControllerTests.js b/services/web/test/unit/src/Editor/EditorHttpControllerTests.js index 7e3dddc89e..3fc20fdf6c 100644 --- a/services/web/test/unit/src/Editor/EditorHttpControllerTests.js +++ b/services/web/test/unit/src/Editor/EditorHttpControllerTests.js @@ -138,13 +138,13 @@ describe('EditorHttpController', function () { '@overleaf/metrics': this.Metrics, '../Collaborators/CollaboratorsGetter': this.CollaboratorsGetter, '../Collaborators/CollaboratorsHandler': this.CollaboratorsHandler, - '../Collaborators/CollaboratorsInviteHandler': this - .CollaboratorsInviteHandler, + '../Collaborators/CollaboratorsInviteHandler': + this.CollaboratorsInviteHandler, '../TokenAccess/TokenAccessHandler': this.TokenAccessHandler, '../Authentication/SessionManager': this.SessionManager, '../../infrastructure/FileWriter': this.FileWriter, - '../Project/ProjectEntityUpdateHandler': this - .ProjectEntityUpdateHandler, + '../Project/ProjectEntityUpdateHandler': + this.ProjectEntityUpdateHandler, '../Docstore/DocstoreManager': this.DocstoreManager, '../Errors/HttpErrorHandler': this.HttpErrorHandler, }, diff --git a/services/web/test/unit/src/Exports/ExportsControllerTests.js b/services/web/test/unit/src/Exports/ExportsControllerTests.js index 66fdfabc9b..356eacf25e 100644 --- a/services/web/test/unit/src/Exports/ExportsControllerTests.js +++ b/services/web/test/unit/src/Exports/ExportsControllerTests.js @@ -65,8 +65,8 @@ describe('ExportsController', function () { return (this.controller = SandboxedModule.require(modulePath, { requires: { './ExportsHandler': this.handler, - '../Authentication/AuthenticationController': this - .AuthenticationController, + '../Authentication/AuthenticationController': + this.AuthenticationController, }, })) }) diff --git a/services/web/test/unit/src/History/HistoryControllerTests.js b/services/web/test/unit/src/History/HistoryControllerTests.js index 0ffc3f1fb6..65308617e9 100644 --- a/services/web/test/unit/src/History/HistoryControllerTests.js +++ b/services/web/test/unit/src/History/HistoryControllerTests.js @@ -30,7 +30,8 @@ describe('HistoryController', function () { '../Authentication/SessionManager': this.SessionManager, './HistoryManager': (this.HistoryManager = {}), '../Project/ProjectDetailsHandler': (this.ProjectDetailsHandler = {}), - '../Project/ProjectEntityUpdateHandler': (this.ProjectEntityUpdateHandler = {}), + '../Project/ProjectEntityUpdateHandler': + (this.ProjectEntityUpdateHandler = {}), '../User/UserGetter': (this.UserGetter = {}), './RestoreManager': (this.RestoreManager = {}), }, diff --git a/services/web/test/unit/src/History/RestoreManagerTests.js b/services/web/test/unit/src/History/RestoreManagerTests.js index 79516c6f10..0f8884fc81 100644 --- a/services/web/test/unit/src/History/RestoreManagerTests.js +++ b/services/web/test/unit/src/History/RestoreManagerTests.js @@ -29,7 +29,8 @@ describe('RestoreManager', function () { requires: { '@overleaf/settings': {}, '../../infrastructure/FileWriter': (this.FileWriter = {}), - '../Uploads/FileSystemImportManager': (this.FileSystemImportManager = {}), + '../Uploads/FileSystemImportManager': (this.FileSystemImportManager = + {}), '../Project/ProjectEntityHandler': (this.ProjectEntityHandler = {}), '../Editor/EditorController': (this.EditorController = {}), }, diff --git a/services/web/test/unit/src/Institutions/InstitutionsGetterTests.js b/services/web/test/unit/src/Institutions/InstitutionsGetterTests.js index 9972f290d1..14285a1c7d 100644 --- a/services/web/test/unit/src/Institutions/InstitutionsGetterTests.js +++ b/services/web/test/unit/src/Institutions/InstitutionsGetterTests.js @@ -17,8 +17,10 @@ describe('InstitutionsGetter', function () { this.InstitutionsGetter = SandboxedModule.require(modulePath, { requires: { '../User/UserGetter': this.UserGetter, - '../UserMembership/UserMembershipsHandler': (this.UserMembershipsHandler = {}), - '../UserMembership/UserMembershipEntityConfigs': (this.UserMembershipEntityConfigs = {}), + '../UserMembership/UserMembershipsHandler': + (this.UserMembershipsHandler = {}), + '../UserMembership/UserMembershipEntityConfigs': + (this.UserMembershipEntityConfigs = {}), }, }) @@ -94,17 +96,19 @@ describe('InstitutionsGetter', function () { describe('getCurrentInstitutionIds', function () { it('filters unconfirmed affiliations, those past reconfirmation, and returns only 1 result per institution', async function () { this.UserGetter.promises.getUserFullEmails.resolves(this.userEmails) - const institutions = await this.InstitutionsGetter.promises.getCurrentInstitutionIds( - this.userId - ) + const institutions = + await this.InstitutionsGetter.promises.getCurrentInstitutionIds( + this.userId + ) expect(institutions.length).to.equal(1) expect(institutions[0]).to.equal(456) }) it('handles empty response', async function () { this.UserGetter.promises.getUserFullEmails.resolves([]) - const institutions = await this.InstitutionsGetter.promises.getCurrentInstitutionIds( - this.userId - ) + const institutions = + await this.InstitutionsGetter.promises.getCurrentInstitutionIds( + this.userId + ) expect(institutions).to.deep.equal([]) }) it('handles errors', async function () { @@ -131,9 +135,10 @@ describe('InstitutionsGetter', function () { this.unconfirmedDomainLicensedAffiliation, this.unconfirmedEmailLicensedAffiliation, ]) - const institutions = await this.InstitutionsGetter.promises.getCurrentInstitutionsWithLicence( - this.userId - ) + const institutions = + await this.InstitutionsGetter.promises.getCurrentInstitutionsWithLicence( + this.userId + ) expect(institutions.map(institution => institution.id)).to.deep.equal([ this.licencedAffiliation.affiliation.institution.id, ]) diff --git a/services/web/test/unit/src/Institutions/InstitutionsManagerTests.js b/services/web/test/unit/src/Institutions/InstitutionsManagerTests.js index b8b1dc96d2..955465630e 100644 --- a/services/web/test/unit/src/Institutions/InstitutionsManagerTests.js +++ b/services/web/test/unit/src/Institutions/InstitutionsManagerTests.js @@ -96,12 +96,14 @@ describe('InstitutionsManager', function () { './InstitutionsAPI': { getInstitutionAffiliations: this.getInstitutionAffiliations, promises: { - getInstitutionAffiliations: (this.getInstitutionAffiliationsPromise = sinon - .stub() - .resolves(this.affiliations)), - getInstitutionAffiliationsCounts: (this.getInstitutionAffiliationsCounts = sinon - .stub() - .resolves(this.v1Counts)), + getInstitutionAffiliations: + (this.getInstitutionAffiliationsPromise = sinon + .stub() + .resolves(this.affiliations)), + getInstitutionAffiliationsCounts: + (this.getInstitutionAffiliationsCounts = sinon + .stub() + .resolves(this.v1Counts)), }, }, '../Subscription/FeaturesUpdater': { @@ -207,9 +209,10 @@ describe('InstitutionsManager', function () { it('returns entitled/not, sso/not, lapsed/current, and pro counts', async function () { if (Features.hasFeature('saas')) { this.isFeatureSetBetter.returns(true) - const usersSummary = await this.InstitutionsManager.promises.checkInstitutionUsers( - this.institutionId - ) + const usersSummary = + await this.InstitutionsManager.promises.checkInstitutionUsers( + this.institutionId + ) expect(usersSummary).to.deep.equal({ emailUsers: { total: 1, @@ -248,9 +251,10 @@ describe('InstitutionsManager', function () { if (Features.hasFeature('saas')) { this.isFeatureSetBetter.returns(true) this.v1Counts.with_confirmed_email = 100 - const usersSummary = await this.InstitutionsManager.promises.checkInstitutionUsers( - this.institutionId - ) + const usersSummary = + await this.InstitutionsManager.promises.checkInstitutionUsers( + this.institutionId + ) expect(usersSummary).to.deep.equal({ emailUsers: { total: 1, diff --git a/services/web/test/unit/src/Metadata/MetaHandlerTests.js b/services/web/test/unit/src/Metadata/MetaHandlerTests.js index 31a460e299..8b4408e579 100644 --- a/services/web/test/unit/src/Metadata/MetaHandlerTests.js +++ b/services/web/test/unit/src/Metadata/MetaHandlerTests.js @@ -54,8 +54,8 @@ describe('MetaHandler', function () { return (this.MetaHandler = SandboxedModule.require(modulePath, { requires: { '../Project/ProjectEntityHandler': this.ProjectEntityHandler, - '../DocumentUpdater/DocumentUpdaterHandler': this - .DocumentUpdaterHandler, + '../DocumentUpdater/DocumentUpdaterHandler': + this.DocumentUpdaterHandler, './packageMapping': this.packageMapping, }, })) diff --git a/services/web/test/unit/src/Notifications/NotificationsControllerTests.js b/services/web/test/unit/src/Notifications/NotificationsControllerTests.js index 288b9aa19c..dd1104d698 100644 --- a/services/web/test/unit/src/Notifications/NotificationsControllerTests.js +++ b/services/web/test/unit/src/Notifications/NotificationsControllerTests.js @@ -33,8 +33,8 @@ describe('NotificationsController', function () { this.controller = SandboxedModule.require(modulePath, { requires: { './NotificationsHandler': this.handler, - '../Authentication/AuthenticationController': this - .AuthenticationController, + '../Authentication/AuthenticationController': + this.AuthenticationController, }, }) }) diff --git a/services/web/test/unit/src/PasswordReset/PasswordResetControllerTests.js b/services/web/test/unit/src/PasswordReset/PasswordResetControllerTests.js index 6d53110abf..b91d0e773e 100644 --- a/services/web/test/unit/src/PasswordReset/PasswordResetControllerTests.js +++ b/services/web/test/unit/src/PasswordReset/PasswordResetControllerTests.js @@ -57,10 +57,11 @@ describe('PasswordResetController', function () { '../Authentication/AuthenticationManager': { validatePassword: sinon.stub().returns(null), }, - '../Authentication/AuthenticationController': (this.AuthenticationController = { - getLoggedInUserId: sinon.stub(), - finishLogin: sinon.stub(), - }), + '../Authentication/AuthenticationController': + (this.AuthenticationController = { + getLoggedInUserId: sinon.stub(), + finishLogin: sinon.stub(), + }), '../User/UserGetter': (this.UserGetter = { promises: { getUser: sinon.stub(), diff --git a/services/web/test/unit/src/PasswordReset/PasswordResetHandlerTests.js b/services/web/test/unit/src/PasswordReset/PasswordResetHandlerTests.js index b38708744d..86c5e96567 100644 --- a/services/web/test/unit/src/PasswordReset/PasswordResetHandlerTests.js +++ b/services/web/test/unit/src/PasswordReset/PasswordResetHandlerTests.js @@ -281,8 +281,8 @@ describe('PasswordResetHandler', function () { (error, result) => { const { reset, userId } = result expect(error).to.not.exist - const logCall = this.UserAuditLogHandler.promises.addEntry - .lastCall + const logCall = + this.UserAuditLogHandler.promises.addEntry.lastCall expect(logCall.args[0]).to.equal(this.user_id) expect(logCall.args[1]).to.equal('reset-password') expect(logCall.args[2]).to.equal(undefined) @@ -320,8 +320,8 @@ describe('PasswordResetHandler', function () { (error, result) => { const { reset, userId } = result expect(error).to.not.exist - const logCall = this.UserAuditLogHandler.promises.addEntry - .lastCall + const logCall = + this.UserAuditLogHandler.promises.addEntry.lastCall expect(logCall.args[0]).to.equal(this.user_id) expect(logCall.args[1]).to.equal('reset-password') expect(logCall.args[2]).to.equal(this.user_id) @@ -337,10 +337,8 @@ describe('PasswordResetHandler', function () { describe('errors', function () { describe('via UserAuditLogHandler', function () { beforeEach(function () { - this.PasswordResetHandler.promises.getUserForPasswordResetToken = sinon - .stub() - .withArgs(this.token) - .resolves(this.user) + this.PasswordResetHandler.promises.getUserForPasswordResetToken = + sinon.stub().withArgs(this.token).resolves(this.user) this.UserAuditLogHandler.promises.addEntry.rejects( new Error('oops') ) diff --git a/services/web/test/unit/src/Project/ProjectControllerTests.js b/services/web/test/unit/src/Project/ProjectControllerTests.js index cacd39511c..412bb8cb0a 100644 --- a/services/web/test/unit/src/Project/ProjectControllerTests.js +++ b/services/web/test/unit/src/Project/ProjectControllerTests.js @@ -184,8 +184,8 @@ describe('ProjectController', function () { '../Subscription/FeaturesUpdater': this.FeaturesUpdater, '../Notifications/NotificationsBuilder': this.NotificationBuilder, '../User/UserGetter': this.UserGetter, - '../BrandVariations/BrandVariationsHandler': this - .BrandVariationsHandler, + '../BrandVariations/BrandVariationsHandler': + this.BrandVariationsHandler, '../ThirdPartyDataStore/TpdsProjectFlusher': this.TpdsProjectFlusher, '../../models/Project': {}, '../Analytics/AnalyticsManager': { recordEventForUser: () => {} }, diff --git a/services/web/test/unit/src/Project/ProjectDeleterTests.js b/services/web/test/unit/src/Project/ProjectDeleterTests.js index 1ea1bb7680..2ba5361eb4 100644 --- a/services/web/test/unit/src/Project/ProjectDeleterTests.js +++ b/services/web/test/unit/src/Project/ProjectDeleterTests.js @@ -143,8 +143,8 @@ describe('ProjectDeleter', function () { '../../models/Project': { Project: Project }, './ProjectHelper': this.ProjectHelper, '../../models/DeletedProject': { DeletedProject: DeletedProject }, - '../DocumentUpdater/DocumentUpdaterHandler': this - .DocumentUpdaterHandler, + '../DocumentUpdater/DocumentUpdaterHandler': + this.DocumentUpdaterHandler, '../Tags/TagsHandler': this.TagsHandler, '../FileStore/FileStoreHandler': this.FileStoreHandler, '../ThirdPartyDataStore/TpdsUpdateSender': this.TpdsUpdateSender, @@ -267,10 +267,10 @@ describe('ProjectDeleter', function () { deletedProjectOwnerId: this.project.owner_ref, deletedProjectCollaboratorIds: this.project.collaberator_refs, deletedProjectReadOnlyIds: this.project.readOnly_refs, - deletedProjectReadWriteTokenAccessIds: this.project - .tokenAccessReadAndWrite_refs, - deletedProjectReadOnlyTokenAccessIds: this.project - .tokenAccessReadOnly_refs, + deletedProjectReadWriteTokenAccessIds: + this.project.tokenAccessReadAndWrite_refs, + deletedProjectReadOnlyTokenAccessIds: + this.project.tokenAccessReadOnly_refs, deletedProjectReadWriteToken: this.project.tokens.readAndWrite, deletedProjectReadOnlyToken: this.project.tokens.readOnly, deletedProjectOverleafId: this.project.overleaf.id, diff --git a/services/web/test/unit/src/Project/ProjectDetailsHandlerTests.js b/services/web/test/unit/src/Project/ProjectDetailsHandlerTests.js index dd71d7ce65..a03bb9d6a9 100644 --- a/services/web/test/unit/src/Project/ProjectDetailsHandlerTests.js +++ b/services/web/test/unit/src/Project/ProjectDetailsHandlerTests.js @@ -121,9 +121,10 @@ describe('ProjectDetailsHandler', function () { it('should make a call to mongo just for the description', async function () { this.ProjectGetter.promises.getProject.resolves() await this.handler.promises.getProjectDescription(this.project._id) - expect( - this.ProjectGetter.promises.getProject - ).to.have.been.calledWith(this.project._id, { description: true }) + expect(this.ProjectGetter.promises.getProject).to.have.been.calledWith( + this.project._id, + { description: true } + ) }) it('should return what the mongo call returns', async function () { diff --git a/services/web/test/unit/src/Project/ProjectDuplicatorTests.js b/services/web/test/unit/src/Project/ProjectDuplicatorTests.js index 8968a4554b..0c286bdfc2 100644 --- a/services/web/test/unit/src/Project/ProjectDuplicatorTests.js +++ b/services/web/test/unit/src/Project/ProjectDuplicatorTests.js @@ -204,13 +204,13 @@ describe('ProjectDuplicator', function () { '../../models/Doc': { Doc: this.Doc }, '../../models/File': { File: this.File }, '../Docstore/DocstoreManager': this.DocstoreManager, - '../DocumentUpdater/DocumentUpdaterHandler': this - .DocumentUpdaterHandler, + '../DocumentUpdater/DocumentUpdaterHandler': + this.DocumentUpdaterHandler, '../FileStore/FileStoreHandler': this.FileStoreHandler, './ProjectCreationHandler': this.ProjectCreationHandler, './ProjectDeleter': this.ProjectDeleter, - './ProjectEntityMongoUpdateHandler': this - .ProjectEntityMongoUpdateHandler, + './ProjectEntityMongoUpdateHandler': + this.ProjectEntityMongoUpdateHandler, './ProjectEntityUpdateHandler': this.ProjectEntityUpdateHandler, './ProjectGetter': this.ProjectGetter, './ProjectLocator': this.ProjectLocator, diff --git a/services/web/test/unit/src/Project/ProjectEntityHandlerTests.js b/services/web/test/unit/src/Project/ProjectEntityHandlerTests.js index fe24120e16..f6023682a7 100644 --- a/services/web/test/unit/src/Project/ProjectEntityHandlerTests.js +++ b/services/web/test/unit/src/Project/ProjectEntityHandlerTests.js @@ -32,8 +32,8 @@ describe('ProjectEntityHandler', function () { this.ProjectEntityHandler = SandboxedModule.require(modulePath, { requires: { '../Docstore/DocstoreManager': (this.DocstoreManager = {}), - '../../Features/DocumentUpdater/DocumentUpdaterHandler': this - .DocumentUpdaterHandler, + '../../Features/DocumentUpdater/DocumentUpdaterHandler': + this.DocumentUpdaterHandler, '../../models/Project': { Project: this.ProjectModel, }, diff --git a/services/web/test/unit/src/Project/ProjectEntityUpdateHandlerTests.js b/services/web/test/unit/src/Project/ProjectEntityUpdateHandlerTests.js index 8536f62c3a..ee2175e523 100644 --- a/services/web/test/unit/src/Project/ProjectEntityUpdateHandlerTests.js +++ b/services/web/test/unit/src/Project/ProjectEntityUpdateHandlerTests.js @@ -154,8 +154,8 @@ describe('ProjectEntityUpdateHandler', function () { fs: this.fs, '../../models/Doc': { Doc: this.DocModel }, '../Docstore/DocstoreManager': this.DocstoreManager, - '../../Features/DocumentUpdater/DocumentUpdaterHandler': this - .DocumentUpdaterHandler, + '../../Features/DocumentUpdater/DocumentUpdaterHandler': + this.DocumentUpdaterHandler, '../../models/File': { File: this.FileModel }, '../FileStore/FileStoreHandler': this.FileStoreHandler, '../../infrastructure/LockManager': this.LockManager, @@ -164,8 +164,8 @@ describe('ProjectEntityUpdateHandler', function () { './ProjectLocator': this.ProjectLocator, './ProjectUpdateHandler': this.ProjectUpdater, './ProjectEntityHandler': this.ProjectEntityHandler, - './ProjectEntityMongoUpdateHandler': this - .ProjectEntityMongoUpdateHandler, + './ProjectEntityMongoUpdateHandler': + this.ProjectEntityMongoUpdateHandler, '../ThirdPartyDataStore/TpdsUpdateSender': this.TpdsUpdateSender, '../Editor/EditorRealTimeController': this.EditorRealTimeController, '../../infrastructure/FileWriter': this.FileWriter, diff --git a/services/web/test/unit/src/Project/ProjectGetterTests.js b/services/web/test/unit/src/Project/ProjectGetterTests.js index 6f459bf8e4..3b835c3f7a 100644 --- a/services/web/test/unit/src/Project/ProjectGetterTests.js +++ b/services/web/test/unit/src/Project/ProjectGetterTests.js @@ -55,8 +55,8 @@ describe('ProjectGetter', function () { }, '../Collaborators/CollaboratorsGetter': this.CollaboratorsGetter, '../../infrastructure/LockManager': this.LockManager, - './ProjectEntityMongoUpdateHandler': this - .ProjectEntityMongoUpdateHandler, + './ProjectEntityMongoUpdateHandler': + this.ProjectEntityMongoUpdateHandler, }, }) }) diff --git a/services/web/test/unit/src/Publishers/PublishersGetterTests.js b/services/web/test/unit/src/Publishers/PublishersGetterTests.js index b003b23bf6..7103e4ddf2 100644 --- a/services/web/test/unit/src/Publishers/PublishersGetterTests.js +++ b/services/web/test/unit/src/Publishers/PublishersGetterTests.js @@ -30,20 +30,22 @@ describe('PublishersGetter', function () { this.PublishersGetter = SandboxedModule.require(modulePath, { requires: { '../User/UserGetter': this.UserGetter, - '../UserMembership/UserMembershipsHandler': (this.UserMembershipsHandler = { - getEntitiesByUser: sinon - .stub() - .callsArgWith(2, null, [this.publisher]), - }), - '../UserMembership/UserMembershipEntityConfigs': (this.UserMembershipEntityConfigs = { - publisher: { - modelName: 'Publisher', - canCreate: true, - fields: { - primaryKey: 'slug', + '../UserMembership/UserMembershipsHandler': + (this.UserMembershipsHandler = { + getEntitiesByUser: sinon + .stub() + .callsArgWith(2, null, [this.publisher]), + }), + '../UserMembership/UserMembershipEntityConfigs': + (this.UserMembershipEntityConfigs = { + publisher: { + modelName: 'Publisher', + canCreate: true, + fields: { + primaryKey: 'slug', + }, }, - }, - }), + }), }, }) diff --git a/services/web/test/unit/src/References/ReferencesHandlerTests.js b/services/web/test/unit/src/References/ReferencesHandlerTests.js index b0fa942aee..272ef49336 100644 --- a/services/web/test/unit/src/References/ReferencesHandlerTests.js +++ b/services/web/test/unit/src/References/ReferencesHandlerTests.js @@ -64,9 +64,10 @@ describe('ReferencesHandler', function () { '../User/UserGetter': (this.UserGetter = { getUser: sinon.stub(), }), - '../DocumentUpdater/DocumentUpdaterHandler': (this.DocumentUpdaterHandler = { - flushDocToMongo: sinon.stub().callsArgWith(2, null), - }), + '../DocumentUpdater/DocumentUpdaterHandler': + (this.DocumentUpdaterHandler = { + flushDocToMongo: sinon.stub().callsArgWith(2, null), + }), '../../infrastructure/Features': (this.Features = { hasFeature: sinon.stub().returns(true), }), diff --git a/services/web/test/unit/src/Spelling/SpellingControllerTests.js b/services/web/test/unit/src/Spelling/SpellingControllerTests.js index c4b72fff3f..ae450280ff 100644 --- a/services/web/test/unit/src/Spelling/SpellingControllerTests.js +++ b/services/web/test/unit/src/Spelling/SpellingControllerTests.js @@ -36,8 +36,8 @@ describe('SpellingController', function () { ], apis: { spelling: { host: SPELLING_HOST, url: SPELLING_URL } }, }, - '../Authentication/AuthenticationController': this - .AuthenticationController, + '../Authentication/AuthenticationController': + this.AuthenticationController, }, }) this.req = { diff --git a/services/web/test/unit/src/Subscription/FeaturesUpdaterTests.js b/services/web/test/unit/src/Subscription/FeaturesUpdaterTests.js index 1e6e6c32f9..12675055ae 100644 --- a/services/web/test/unit/src/Subscription/FeaturesUpdaterTests.js +++ b/services/web/test/unit/src/Subscription/FeaturesUpdaterTests.js @@ -127,13 +127,11 @@ describe('FeaturesUpdater', function () { describe('refreshFeatures', function () { it('should return features and featuresChanged', async function () { - const { - features, - featuresChanged, - } = await this.FeaturesUpdater.promises.refreshFeatures( - this.user._id, - 'test' - ) + const { features, featuresChanged } = + await this.FeaturesUpdater.promises.refreshFeatures( + this.user._id, + 'test' + ) expect(features).to.exist expect(featuresChanged).to.exist }) diff --git a/services/web/test/unit/src/Subscription/LimitationsManagerTests.js b/services/web/test/unit/src/Subscription/LimitationsManagerTests.js index f70af9b305..a8934e6899 100644 --- a/services/web/test/unit/src/Subscription/LimitationsManagerTests.js +++ b/services/web/test/unit/src/Subscription/LimitationsManagerTests.js @@ -41,7 +41,8 @@ describe('LimitationsManager', function () { './SubscriptionLocator': this.SubscriptionLocator, '@overleaf/settings': (this.Settings = {}), '../Collaborators/CollaboratorsGetter': (this.CollaboratorsGetter = {}), - '../Collaborators/CollaboratorsInviteHandler': (this.CollaboratorsInviteHandler = {}), + '../Collaborators/CollaboratorsInviteHandler': + (this.CollaboratorsInviteHandler = {}), './V1SubscriptionManager': (this.V1SubscriptionManager = {}), }, }) diff --git a/services/web/test/unit/src/Subscription/RecurlyWrapperTests.js b/services/web/test/unit/src/Subscription/RecurlyWrapperTests.js index fdc9d77dc5..81e2c7e080 100644 --- a/services/web/test/unit/src/Subscription/RecurlyWrapperTests.js +++ b/services/web/test/unit/src/Subscription/RecurlyWrapperTests.js @@ -141,16 +141,14 @@ describe('RecurlyWrapper', function () { } tk.freeze(Date.now()) // freeze the time for these tests - return (this.RecurlyWrapper = RecurlyWrapper = SandboxedModule.require( - modulePath, - { + return (this.RecurlyWrapper = RecurlyWrapper = + SandboxedModule.require(modulePath, { requires: { '@overleaf/settings': this.settings, request: sinon.stub(), './Errors': SubscriptionErrors, }, - } - )) + })) }) afterEach(function () { diff --git a/services/web/test/unit/src/Subscription/SubscriptionControllerTests.js b/services/web/test/unit/src/Subscription/SubscriptionControllerTests.js index 09273f83fe..170afae8de 100644 --- a/services/web/test/unit/src/Subscription/SubscriptionControllerTests.js +++ b/services/web/test/unit/src/Subscription/SubscriptionControllerTests.js @@ -467,7 +467,8 @@ describe('SubscriptionController', function () { threeDSecureActionResult: '5678', } this.req.body.recurly_token_id = this.recurlyTokenIds.billing - this.req.body.recurly_three_d_secure_action_result_token_id = this.recurlyTokenIds.threeDSecureActionResult + this.req.body.recurly_three_d_secure_action_result_token_id = + this.recurlyTokenIds.threeDSecureActionResult this.req.body.subscriptionDetails = this.subscriptionDetails this.LimitationsManager.userHasV1OrV2Subscription.yields(null, false) return this.SubscriptionController.createSubscription(this.req, this.res) diff --git a/services/web/test/unit/src/Subscription/SubscriptionGroupHandlerTests.js b/services/web/test/unit/src/Subscription/SubscriptionGroupHandlerTests.js index 22b6951c53..6b8a88df8a 100644 --- a/services/web/test/unit/src/Subscription/SubscriptionGroupHandlerTests.js +++ b/services/web/test/unit/src/Subscription/SubscriptionGroupHandlerTests.js @@ -99,8 +99,8 @@ describe('SubscriptionGroupHandler', function () { '../Email/EmailHandler': this.EmailHandler, '@overleaf/settings': this.settings, '../Notifications/NotificationsBuilder': this.NotificationsBuilder, - '../UserMembership/UserMembershipViewModel': this - .UserMembershipViewModel, + '../UserMembership/UserMembershipViewModel': + this.UserMembershipViewModel, }, })) }) diff --git a/services/web/test/unit/src/Subscription/SubscriptionHandlerTests.js b/services/web/test/unit/src/Subscription/SubscriptionHandlerTests.js index c2f9448c18..e5281969ec 100644 --- a/services/web/test/unit/src/Subscription/SubscriptionHandlerTests.js +++ b/services/web/test/unit/src/Subscription/SubscriptionHandlerTests.js @@ -202,8 +202,8 @@ describe('SubscriptionHandler', function () { expect( this.RecurlyClient.changeSubscriptionByUuid ).to.have.been.calledWith(this.subscription.recurlySubscription_id) - const updateOptions = this.RecurlyClient.changeSubscriptionByUuid - .args[0][1] + const updateOptions = + this.RecurlyClient.changeSubscriptionByUuid.args[0][1] updateOptions.planCode.should.equal(this.plan_code) }) } @@ -252,8 +252,8 @@ describe('SubscriptionHandler', function () { shouldSyncSubscription() it('should update with timeframe ' + timeframe, function () { - const updateOptions = this.RecurlyClient.changeSubscriptionByUuid - .args[0][1] + const updateOptions = + this.RecurlyClient.changeSubscriptionByUuid.args[0][1] updateOptions.timeframe.should.equal(timeframe) }) } @@ -364,8 +364,8 @@ describe('SubscriptionHandler', function () { expect(this.RecurlyClient.changeSubscriptionByUuid).to.be.calledWith( this.subscription.recurlySubscription_id ) - const updateOptions = this.RecurlyClient.changeSubscriptionByUuid - .args[0][1] + const updateOptions = + this.RecurlyClient.changeSubscriptionByUuid.args[0][1] updateOptions.planCode.should.equal(this.plan_code) }) }) diff --git a/services/web/test/unit/src/Templates/TemplatesControllerTests.js b/services/web/test/unit/src/Templates/TemplatesControllerTests.js index dd43000941..af9d927ed9 100644 --- a/services/web/test/unit/src/Templates/TemplatesControllerTests.js +++ b/services/web/test/unit/src/Templates/TemplatesControllerTests.js @@ -24,9 +24,10 @@ describe('TemplatesController', function () { this.TemplatesController = SandboxedModule.require(modulePath, { requires: { '../Project/ProjectHelper': ProjectHelper, - '../Authentication/AuthenticationController': (this.AuthenticationController = { - getLoggedInUserId: sinon.stub().returns(this.user_id), - }), + '../Authentication/AuthenticationController': + (this.AuthenticationController = { + getLoggedInUserId: sinon.stub().returns(this.user_id), + }), './TemplatesManager': (this.TemplatesManager = { createProjectFromV1Template: sinon.stub(), }), diff --git a/services/web/test/unit/src/ThirdPartyDataStore/TpdsProjectFlusherTests.js b/services/web/test/unit/src/ThirdPartyDataStore/TpdsProjectFlusherTests.js index bcdec7f9ff..1d00d14cac 100644 --- a/services/web/test/unit/src/ThirdPartyDataStore/TpdsProjectFlusherTests.js +++ b/services/web/test/unit/src/ThirdPartyDataStore/TpdsProjectFlusherTests.js @@ -47,8 +47,8 @@ describe('TpdsProjectFlusher', function () { this.TpdsProjectFlusher = SandboxedModule.require(MODULE_PATH, { requires: { - '../DocumentUpdater/DocumentUpdaterHandler': this - .DocumentUpdaterHandler, + '../DocumentUpdater/DocumentUpdaterHandler': + this.DocumentUpdaterHandler, '../Project/ProjectGetter': this.ProjectGetter, '../Project/ProjectEntityHandler': this.ProjectEntityHandler, '../../models/Project': { Project }, diff --git a/services/web/test/unit/src/Uploads/ProjectUploadManagerTests.js b/services/web/test/unit/src/Uploads/ProjectUploadManagerTests.js index 125236937c..233095fd44 100644 --- a/services/web/test/unit/src/Uploads/ProjectUploadManagerTests.js +++ b/services/web/test/unit/src/Uploads/ProjectUploadManagerTests.js @@ -151,13 +151,13 @@ describe('ProjectUploadManager', function () { '../../models/Doc': { Doc: this.Doc }, '../Docstore/DocstoreManager': this.DocstoreManager, '../Documents/DocumentHelper': this.DocumentHelper, - '../DocumentUpdater/DocumentUpdaterHandler': this - .DocumentUpdaterHandler, + '../DocumentUpdater/DocumentUpdaterHandler': + this.DocumentUpdaterHandler, '../FileStore/FileStoreHandler': this.FileStoreHandler, './FileSystemImportManager': this.FileSystemImportManager, '../Project/ProjectCreationHandler': this.ProjectCreationHandler, - '../Project/ProjectEntityMongoUpdateHandler': this - .ProjectEntityMongoUpdateHandler, + '../Project/ProjectEntityMongoUpdateHandler': + this.ProjectEntityMongoUpdateHandler, '../Project/ProjectRootDocManager': this.ProjectRootDocManager, '../Project/ProjectDetailsHandler': this.ProjectDetailsHandler, '../Project/ProjectDeleter': this.ProjectDeleter, diff --git a/services/web/test/unit/src/User/ThirdPartyIdentityManagerTests.js b/services/web/test/unit/src/User/ThirdPartyIdentityManagerTests.js index 54e3e3ecb6..3667a7cb93 100644 --- a/services/web/test/unit/src/User/ThirdPartyIdentityManagerTests.js +++ b/services/web/test/unit/src/User/ThirdPartyIdentityManagerTests.js @@ -16,12 +16,14 @@ describe('ThirdPartyIdentityManager', function () { this.auditLog = { initiatorId: this.userId, ipAddress: '0:0:0:0' } this.ThirdPartyIdentityManager = SandboxedModule.require(modulePath, { requires: { - '../../../../app/src/Features/User/UserAuditLogHandler': (this.UserAuditLogHandler = { - addEntry: sinon.stub().yields(), - }), - '../../../../app/src/Features/Email/EmailHandler': (this.EmailHandler = { - sendEmail: sinon.stub().yields(), - }), + '../../../../app/src/Features/User/UserAuditLogHandler': + (this.UserAuditLogHandler = { + addEntry: sinon.stub().yields(), + }), + '../../../../app/src/Features/Email/EmailHandler': (this.EmailHandler = + { + sendEmail: sinon.stub().yields(), + }), '../../../../app/src/models/User': { User: (this.User = { findOneAndUpdate: sinon.stub().yields(undefined, this.user), diff --git a/services/web/test/unit/src/User/UserControllerTests.js b/services/web/test/unit/src/User/UserControllerTests.js index 77cf549500..8440e6c4e4 100644 --- a/services/web/test/unit/src/User/UserControllerTests.js +++ b/services/web/test/unit/src/User/UserControllerTests.js @@ -105,8 +105,8 @@ describe('UserController', function () { }, '../Newsletter/NewsletterManager': this.NewsLetterManager, './UserRegistrationHandler': this.UserRegistrationHandler, - '../Authentication/AuthenticationController': this - .AuthenticationController, + '../Authentication/AuthenticationController': + this.AuthenticationController, '../Authentication/SessionManager': this.SessionManager, '../Authentication/AuthenticationManager': this.AuthenticationManager, '../../infrastructure/Features': (this.Features = { diff --git a/services/web/test/unit/src/User/UserCreatorTests.js b/services/web/test/unit/src/User/UserCreatorTests.js index b1c0b8c874..cc447bc358 100644 --- a/services/web/test/unit/src/User/UserCreatorTests.js +++ b/services/web/test/unit/src/User/UserCreatorTests.js @@ -48,9 +48,10 @@ describe('UserCreator', function () { './UserOnboardingEmailManager': (this.UserOnboardingEmailManager = { scheduleOnboardingEmail: sinon.stub(), }), - './UserPostRegistrationAnalyticsManager': (this.UserPostRegistrationAnalyticsManager = { - schedulePostRegistrationAnalytics: sinon.stub(), - }), + './UserPostRegistrationAnalyticsManager': + (this.UserPostRegistrationAnalyticsManager = { + schedulePostRegistrationAnalytics: sinon.stub(), + }), }, }) diff --git a/services/web/test/unit/src/User/UserEmailsControllerTests.js b/services/web/test/unit/src/User/UserEmailsControllerTests.js index da948cf004..303ce150ba 100644 --- a/services/web/test/unit/src/User/UserEmailsControllerTests.js +++ b/services/web/test/unit/src/User/UserEmailsControllerTests.js @@ -62,12 +62,13 @@ describe('UserEmailsController', function () { }, }), '../Helpers/EmailHelper': this.EmailHelper, - './UserEmailsConfirmationHandler': (this.UserEmailsConfirmationHandler = { - sendReconfirmationEmail: sinon.stub(), - promises: { - sendConfirmationEmail: sinon.stub().resolves(), - }, - }), + './UserEmailsConfirmationHandler': (this.UserEmailsConfirmationHandler = + { + sendReconfirmationEmail: sinon.stub(), + promises: { + sendConfirmationEmail: sinon.stub().resolves(), + }, + }), '../Institutions/InstitutionsAPI': this.InstitutionsAPI, '../Errors/HttpErrorHandler': this.HttpErrorHandler, }, @@ -132,8 +133,8 @@ describe('UserEmailsController', function () { this.newEmail ) - const affiliationOptions = this.UserUpdater.promises.addEmailAddress - .lastCall.args[2] + const affiliationOptions = + this.UserUpdater.promises.addEmailAddress.lastCall.args[2] Object.keys(affiliationOptions).length.should.equal(3) affiliationOptions.university.should.equal(this.req.body.university) affiliationOptions.department.should.equal(this.req.body.department) diff --git a/services/web/test/unit/src/User/UserPagesControllerTests.js b/services/web/test/unit/src/User/UserPagesControllerTests.js index 279aea69ff..deef5bc2ca 100644 --- a/services/web/test/unit/src/User/UserPagesControllerTests.js +++ b/services/web/test/unit/src/User/UserPagesControllerTests.js @@ -63,8 +63,8 @@ describe('UserPagesController', function () { './UserGetter': this.UserGetter, './UserSessionsManager': this.UserSessionsManager, '../Errors/ErrorController': this.ErrorController, - '../Authentication/AuthenticationController': this - .AuthenticationController, + '../Authentication/AuthenticationController': + this.AuthenticationController, '../Authentication/SessionManager': this.SessionManager, request: (this.request = sinon.stub()), }, diff --git a/services/web/test/unit/src/User/UserUpdaterTests.js b/services/web/test/unit/src/User/UserUpdaterTests.js index f8489fb975..c5f0128bdd 100644 --- a/services/web/test/unit/src/User/UserUpdaterTests.js +++ b/services/web/test/unit/src/User/UserUpdaterTests.js @@ -670,11 +670,11 @@ describe('UserUpdater', function () { error => { expect(error).to.not.exist this.EmailHandler.promises.sendEmail.callCount.should.equal(2) - const toOldEmailAlert = this.EmailHandler.promises.sendEmail - .firstCall + const toOldEmailAlert = + this.EmailHandler.promises.sendEmail.firstCall expect(toOldEmailAlert.args[0]).to.equal('securityAlert') - const toNewEmailAlert = this.EmailHandler.promises.sendEmail - .lastCall + const toNewEmailAlert = + this.EmailHandler.promises.sendEmail.lastCall expect(toOldEmailAlert.args[1].to).to.equal(this.stubbedUser.email) expect(toNewEmailAlert.args[0]).to.equal('securityAlert') expect(toNewEmailAlert.args[1].to).to.equal(this.newEmail) diff --git a/services/web/test/unit/src/infrastructure/GeoIpLookupTest.js b/services/web/test/unit/src/infrastructure/GeoIpLookupTest.js index 2e2b6f392a..8fafd64b4b 100644 --- a/services/web/test/unit/src/infrastructure/GeoIpLookupTest.js +++ b/services/web/test/unit/src/infrastructure/GeoIpLookupTest.js @@ -227,10 +227,8 @@ describe('GeoIpLookup', function () { describe('async', function () { it('should return GBP for GB country', async function () { this.request.get.callsArgWith(1, null, null, this.stubbedResponse) - const { - currencyCode, - countryCode, - } = await this.GeoIpLookup.promises.getCurrencyCode(this.ipAddress) + const { currencyCode, countryCode } = + await this.GeoIpLookup.promises.getCurrencyCode(this.ipAddress) currencyCode.should.equal('GBP') countryCode.should.equal('GB') }) @@ -238,10 +236,8 @@ describe('GeoIpLookup', function () { it('should return GBP for gb country', async function () { this.stubbedResponse.country_code = 'gb' this.request.get.callsArgWith(1, null, null, this.stubbedResponse) - const { - currencyCode, - countryCode, - } = await this.GeoIpLookup.promises.getCurrencyCode(this.ipAddress) + const { currencyCode, countryCode } = + await this.GeoIpLookup.promises.getCurrencyCode(this.ipAddress) currencyCode.should.equal('GBP') countryCode.should.equal('GB') }) @@ -249,10 +245,8 @@ describe('GeoIpLookup', function () { it('should return USD for US', async function () { this.stubbedResponse.country_code = 'US' this.request.get.callsArgWith(1, null, null, this.stubbedResponse) - const { - currencyCode, - countryCode, - } = await this.GeoIpLookup.promises.getCurrencyCode(this.ipAddress) + const { currencyCode, countryCode } = + await this.GeoIpLookup.promises.getCurrencyCode(this.ipAddress) currencyCode.should.equal('USD') countryCode.should.equal('US') }) @@ -260,30 +254,24 @@ describe('GeoIpLookup', function () { it('should return EUR for DE', async function () { this.stubbedResponse.country_code = 'DE' this.request.get.callsArgWith(1, null, null, this.stubbedResponse) - const { - currencyCode, - countryCode, - } = await this.GeoIpLookup.promises.getCurrencyCode(this.ipAddress) + const { currencyCode, countryCode } = + await this.GeoIpLookup.promises.getCurrencyCode(this.ipAddress) currencyCode.should.equal('EUR') countryCode.should.equal('DE') }) it('should default to USD if there is an error', async function () { this.request.get.callsArgWith(1, null, null, { error: true }) - const { - currencyCode, - countryCode, - } = await this.GeoIpLookup.promises.getCurrencyCode(this.ipAddress) + const { currencyCode, countryCode } = + await this.GeoIpLookup.promises.getCurrencyCode(this.ipAddress) currencyCode.should.equal('USD') expect(countryCode).to.be.undefined }) it('should default to USD if there are no details', async function () { this.request.get.callsArgWith(1, null, null, {}) - const { - currencyCode, - countryCode, - } = await this.GeoIpLookup.promises.getCurrencyCode(this.ipAddress) + const { currencyCode, countryCode } = + await this.GeoIpLookup.promises.getCurrencyCode(this.ipAddress) currencyCode.should.equal('USD') expect(countryCode).to.be.undefined }) @@ -291,10 +279,8 @@ describe('GeoIpLookup', function () { it('should default to USD if there is no match for their country', async function () { this.stubbedResponse.country_code = 'Non existant' this.request.get.callsArgWith(1, null, null, this.stubbedResponse) - const { - currencyCode, - countryCode, - } = await this.GeoIpLookup.promises.getCurrencyCode(this.ipAddress) + const { currencyCode, countryCode } = + await this.GeoIpLookup.promises.getCurrencyCode(this.ipAddress) currencyCode.should.equal('USD') countryCode.should.equal('NON EXISTANT') })