Skip to content

Commit

Permalink
Use express response update error from web-ui instead
Browse files Browse the repository at this point in the history
  • Loading branch information
graduta committed Jan 8, 2025
1 parent 9954003 commit b1b2dc4
Show file tree
Hide file tree
Showing 14 changed files with 194 additions and 114 deletions.
42 changes: 26 additions & 16 deletions Control/lib/controllers/Environment.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,12 @@
* or submit itself to any jurisdiction.
*/
const {LogManager, LogLevel} = require('@aliceo2/web-ui');
const {grpcErrorToNativeError, InvalidInputError, UnauthorizedAccessError } = require('@aliceo2/web-ui');
const {
updateAndSendExpressResponseFromNativeError, grpcErrorToNativeError, InvalidInputError, UnauthorizedAccessError
} = require('@aliceo2/web-ui');

const LOG_FACILITY = 'cog/env-ctrl';
const {EnvironmentTransitionType} = require('./../common/environmentTransitionType.enum.js');
const {updateExpressResponseFromNativeError} = require('./../errors/updateExpressResponseFromNativeError.js');
const {User} = require('./../dtos/User.js');

/**
Expand Down Expand Up @@ -63,15 +64,15 @@ class EnvironmentController {
async getEnvironmentHandler(req, res) {
const {id, source} = req.params;
if (!id) {
updateExpressResponseFromNativeError(res, new InvalidInputError('Missing environment ID parameter'));
updateAndSendExpressResponseFromNativeError(res, new InvalidInputError('Missing environment ID parameter'));
return;
}
try {
const response = await this._envService.getEnvironment(id, source);
res.status(200).json(response);
} catch (error) {
this._logger.debug(error);
updateExpressResponseFromNativeError(res, error);
updateAndSendExpressResponseFromNativeError(res, error);
}
}

Expand All @@ -87,9 +88,12 @@ class EnvironmentController {
const {id} = req.params;
const {type: transitionType, runNumber = ''} = req.body;
if (!id) {
updateExpressResponseFromNativeError(res, new InvalidInputError('Missing environment ID parameter'));
updateAndSendExpressResponseFromNativeError(res, new InvalidInputError('Missing environment ID parameter'));
} else if (!(transitionType in EnvironmentTransitionType)) {
updateExpressResponseFromNativeError(res, new InvalidInputError('Invalid environment transition to perform'));
updateAndSendExpressResponseFromNativeError(
res,
new InvalidInputError('Invalid environment transition to perform'),
);
} else {
const transitionRequestedAt = Date.now();
let response = null;
Expand All @@ -104,7 +108,7 @@ class EnvironmentController {
`Request to transition environment by ${req.session.username} to ${transitionType} failed due to ${error}`,
{level: LogLevel.OPERATIONS, system: 'GUI', facility: LOG_FACILITY, partition: id, run: runNumber}
);
updateExpressResponseFromNativeError(res, error);
updateAndSendExpressResponseFromNativeError(res, error);
}
const currentRunNumber = response?.currentRunNumber ?? runNumber;
this._logger.debug(`${transitionType},${id},${currentRunNumber},${transitionRequestedAt},${Date.now()}`);
Expand All @@ -124,7 +128,7 @@ class EnvironmentController {
const {runNumber = '', keepTasks = false, allowInRunningState = false, force = false} = req.body ?? {};

if (!id) {
updateExpressResponseFromNativeError(res, new InvalidInputError('Missing environment ID parameter'));
updateAndSendExpressResponseFromNativeError(res, new InvalidInputError('Missing environment ID parameter'));
} else {
const destroyRequestedAt = Date.now();
this._logger.infoMessage(`Request to destroy environment by ${req.session.username} by force: ${force}`,
Expand All @@ -138,7 +142,7 @@ class EnvironmentController {
`Request to destroy environment by ${req.session.username} failed due to ${error}`,
{level: LogLevel.OPERATIONS, system: 'GUI', facility: LOG_FACILITY, partition: id, run: runNumber}
);
updateExpressResponseFromNativeError(res, error);
updateAndSendExpressResponseFromNativeError(res, error);
}
this._logger.debug(`DESTROY_ENVIRONMENT,${id},${runNumber},${destroyRequestedAt},${Date.now()}`);
}
Expand All @@ -156,23 +160,29 @@ class EnvironmentController {
const {detector, runType, configurationName} = req.body;

if (!this._lockService.isLockOwnedByUser(detector, user)) {
updateExpressResponseFromNativeError(res, new UnauthorizedAccessError('Lock not taken'));
updateAndSendExpressResponseFromNativeError(res, new UnauthorizedAccessError('Lock not taken'));
return;
}

if (!configurationName) {
updateExpressResponseFromNativeError(res, new InvalidInputError('Missing Configuration Name for deployment'));
updateAndSendExpressResponseFromNativeError(
res,
new InvalidInputError('Missing Configuration Name for deployment')
);
return;
}

try {
const areDetectorsAvailable = await this._detectorService.areDetectorsAvailable([detector]);
if (!areDetectorsAvailable) {
updateExpressResponseFromNativeError(res, new InvalidInputError(`Detector ${detector} is already active`));
updateAndSendExpressResponseFromNativeError(
res,
new InvalidInputError(`Detector ${detector} is already active`)
);
return;
}
} catch (error) {
updateExpressResponseFromNativeError(res, grpcErrorToNativeError(error));
updateAndSendExpressResponseFromNativeError(res, grpcErrorToNativeError(error));
return;
}

Expand All @@ -187,7 +197,7 @@ class EnvironmentController {
} catch (error) {
this._logger.debug(`Unable to retrieve saved configuration for ${configurationName} due to`);
this._logger.debug(error);
updateExpressResponseFromNativeError(res, error);
updateAndSendExpressResponseFromNativeError(res, error);
return;
}

Expand All @@ -198,7 +208,7 @@ class EnvironmentController {
workflowTemplatePath = `${repository}/workflows/${template}@${revision}`;
} catch (error) {
this._logger.debug(`Unable to retrieve default workflow template due to ${error}`);
updateExpressResponseFromNativeError(res, error);
updateAndSendExpressResponseFromNativeError(res, error);
return;
}
// Attempt to deploy environment
Expand All @@ -215,7 +225,7 @@ class EnvironmentController {
`Unable to deploy request by username(${username}) for ${configurationName} due to error`,
{level: LogLevel.OPERATIONS, system: 'GUI', facility: LOG_FACILITY}
);
updateExpressResponseFromNativeError(res, error);
updateAndSendExpressResponseFromNativeError(res, error);
}
}
}
Expand Down
8 changes: 4 additions & 4 deletions Control/lib/controllers/Lock.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@
* or submit itself to any jurisdiction.
*/

const {LogManager, LogLevel, InvalidInputError} = require('@aliceo2/web-ui');
const { LogManager, LogLevel } = require('@aliceo2/web-ui');
const { updateAndSendExpressResponseFromNativeError, InvalidInputError } = require('@aliceo2/web-ui');

const { DetectorLockAction } = require('./../common/lock/detectorLockAction.enum.js');
const {updateExpressResponseFromNativeError} = require('./../errors/updateExpressResponseFromNativeError.js');
const {User} = require('./../dtos/User.js');

const LOG_FACILITY = 'cog/log-ctrl';
Expand Down Expand Up @@ -48,7 +48,7 @@ class LockController {
try {
res.status(200).json(this._lockService.locksByDetectorToJSON());
} catch (error) {
updateExpressResponseFromNativeError(res, error);
updateAndSendExpressResponseFromNativeError(res, error);
}
}

Expand Down Expand Up @@ -98,7 +98,7 @@ class LockController {
}
} catch (error) {
this._logger.errorMessage(error, {level: LogLevel.DEVELOPER, facility: LOG_FACILITY});
updateExpressResponseFromNativeError(res, error);
updateAndSendExpressResponseFromNativeError(res, error);
}
}

Expand Down
7 changes: 3 additions & 4 deletions Control/lib/controllers/Run.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,8 @@
* granted to it by virtue of its status as an Intergovernmental Organization
* or submit itself to any jurisdiction.
*/
const {LogManager, LogLevel} = require('@aliceo2/web-ui');
const {LogManager, LogLevel, updateAndSendExpressResponseFromNativeError} = require('@aliceo2/web-ui');
const LOG_FACILITY = 'run-ctrl';
const {updateExpressResponseFromNativeError} = require('./../errors/updateExpressResponseFromNativeError.js');
const {CacheKeys} = require('./../common/cacheKeys.enum.js');

/**
Expand Down Expand Up @@ -59,7 +58,7 @@ class RunController {
res.status(200).json(calibrationRuns);
} catch (error) {
this._logger.debug(error);
updateExpressResponseFromNativeError(res, error);
updateAndSendExpressResponseFromNativeError(res, error);
}
}

Expand All @@ -81,7 +80,7 @@ class RunController {
const logMessage = `Error refreshing calibration configuration by ${req.session.username} due to: ${error}`;
this._logger.errorMessage(logMessage, {level: LogLevel.OPERATIONS, facility: LOG_FACILITY})

updateExpressResponseFromNativeError(res, error);
updateAndSendExpressResponseFromNativeError(res, error);
}
}
}
Expand Down
13 changes: 8 additions & 5 deletions Control/lib/controllers/WorkflowTemplate.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
* granted to it by virtue of its status as an Intergovernmental Organization
* or submit itself to any jurisdiction.
*/
const {updateExpressResponseFromNativeError} = require('./../errors/updateExpressResponseFromNativeError.js');
const {updateAndSendExpressResponseFromNativeError, InvalidInputError} = require('@aliceo2/web-ui');

/**
* Controller for dealing with all API requests on workflow templates from AliECS:
Expand Down Expand Up @@ -40,7 +40,7 @@ class WorkflowTemplateController {
const defaultTemplateSource = await this._workflowService.getDefaultTemplateSource();
res.status(200).json(defaultTemplateSource);
} catch (error) {
updateExpressResponseFromNativeError(res, error);
updateAndSendExpressResponseFromNativeError(res, error);
}
}

Expand All @@ -55,7 +55,7 @@ class WorkflowTemplateController {
const mappings = await this._workflowService.retrieveWorkflowMappings();
res.status(200).json(mappings);
} catch (error) {
updateExpressResponseFromNativeError(res, error);
updateAndSendExpressResponseFromNativeError(res, error);
}
}

Expand All @@ -69,13 +69,16 @@ class WorkflowTemplateController {
try {
const {name} = req.query;
if (!name) {
res.status(400).json({message: 'No name for the configuration provided'});
updateAndSendExpressResponseFromNativeError(
res,
new InvalidInputError('No name for the configuration provided')
);
return;
}
const mappings = await this._workflowService.retrieveWorkflowSavedConfiguration(name);
res.status(200).json(mappings);
} catch (error) {
updateExpressResponseFromNativeError(res, error);
updateAndSendExpressResponseFromNativeError(res, error);
}
}
}
Expand Down
44 changes: 0 additions & 44 deletions Control/lib/errors/updateExpressResponseFromNativeError.js

This file was deleted.

7 changes: 3 additions & 4 deletions Control/lib/middleware/lockOwnership.middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,8 @@
* or submit itself to any jurisdiction.
*/

const {LogManager} = require('@aliceo2/web-ui');
const {LogManager, updateAndSendExpressResponseFromNativeError} = require('@aliceo2/web-ui');
const {User} = require('../dtos/User');
const {updateExpressResponseFromNativeError} = require('../errors/updateExpressResponseFromNativeError');

/**
* Middleware function to check that the user has ownership of the locks for the given detectors
Expand Down Expand Up @@ -41,7 +40,7 @@ const lockOwnershipMiddleware = (lockService, environmentService) => {
} catch (error) {
const logger = LogManager.getLogger(`${process.env.npm_config_log_label ?? 'cog'}/lock-ownership-middleware`);
logger.errorMessage(error);
updateExpressResponseFromNativeError(res, error);
updateAndSendExpressResponseFromNativeError(res, error);
return;
}
try {
Expand All @@ -53,7 +52,7 @@ const lockOwnershipMiddleware = (lockService, environmentService) => {
} catch (error) {
const logger = LogManager.getLogger(`${process.env.npm_config_log_label ?? 'cog'}/lock-ownership-middleware`);
logger.errorMessage(error);
updateExpressResponseFromNativeError(res, error);
updateAndSendExpressResponseFromNativeError(res, error);
}
};
};
Expand Down
7 changes: 3 additions & 4 deletions Control/lib/middleware/minimumRole.middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,8 @@
* or submit itself to any jurisdiction.
*/

const {UnauthorizedAccessError, updateAndSendExpressResponseFromNativeError} = require('@aliceo2/web-ui');
const {isRoleSufficient} = require('../common/role.enum.js');
const {UnauthorizedAccessError} = require('@aliceo2/web-ui');
const {updateExpressResponseFromNativeError} = require('../errors/updateExpressResponseFromNativeError.js');

/**
* Method to receive a minimum role that needs to be met by owner of request and to return a middleware function
Expand All @@ -41,15 +40,15 @@ const minimumRoleMiddleware = (minimumRole) => {
}
const isAllowed = accessList.some((role) => isRoleSufficient(role, minimumRole));
if (!isAllowed) {
updateExpressResponseFromNativeError(res,
updateAndSendExpressResponseFromNativeError(res,
new UnauthorizedAccessError('Not enough permissions for this operation')
);
return;
}
next();
} catch (error) {
console.error(error);
updateExpressResponseFromNativeError(res, error);
updateAndSendExpressResponseFromNativeError(res, error);
}
}
};
Expand Down
16 changes: 12 additions & 4 deletions Control/test/api/lock/api-put-locks.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,19 @@ describe(`'API - PUT - /locks/:action/:detectorId' test suite`, () => {
await request(`${TEST_URL}/api/locks`)
.put(`/${DetectorLockAction.TAKE}/MID?token=${ADMIN_TEST_TOKEN}`)
.expect(403, {
message: 'Unauthorized TAKE action for lock of detector MID by user Admin User'
message: 'Unauthorized TAKE action for lock of detector MID by user Admin User',
title: 'Unauthorized Access',
status: 403,
});
});

it('should return unauthorized error for attempt to take lock as Guest User', async () => {
await request(`${TEST_URL}/api/locks`)
.put(`/${DetectorLockAction.TAKE}/DCS?token=${GUEST_TEST_TOKEN}`)
.expect(403, {
message: 'Not enough permissions for this operation'
message: 'Not enough permissions for this operation',
title: 'Unauthorized Access',
status: 403,
});
});

Expand Down Expand Up @@ -114,15 +118,19 @@ describe(`'API - PUT - /locks/:action/:detectorId' test suite`, () => {
await request(`${TEST_URL}/api/locks`)
.put(`/${DetectorLockAction.RELEASE}/MID?token=${GUEST_TEST_TOKEN}`)
.expect(403, {
message: 'Not enough permissions for this operation'
message: 'Not enough permissions for this operation',
status: 403,
title: 'Unauthorized Access',
});
});

it('should return error for attempt to release a lock not owned by user', async () => {
await request(`${TEST_URL}/api/locks`)
.put(`/${DetectorLockAction.RELEASE}/MID?token=${DET_MID_TEST_TOKEN}`)
.expect(403, {
message: 'Unauthorized RELEASE action for lock of detector MID by user Detector User'
message: 'Unauthorized RELEASE action for lock of detector MID by user Detector User',
status: 403,
title: 'Unauthorized Access',
});
});

Expand Down
Loading

0 comments on commit b1b2dc4

Please sign in to comment.