Skip to content

Commit

Permalink
Merge pull request #1058 from HDRUK/preprod
Browse files Browse the repository at this point in the history
GAT-391: GAT API Release v5.0.0 IAM
  • Loading branch information
ChandraChintakindi authored May 31, 2023
2 parents c3db813 + 8b6b386 commit ee50315
Show file tree
Hide file tree
Showing 62 changed files with 7,619 additions and 708 deletions.
2 changes: 1 addition & 1 deletion Chart.yaml
Original file line number Diff line number Diff line change
@@ -1 +1 @@
v4.0.3
v5.0.0
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
FROM node:14
FROM node:16

# Create app directory
WORKDIR /usr/src/app
Expand Down
4 changes: 2 additions & 2 deletions Dockerfile.dev
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
FROM node:14
FROM node:18.14.2

ENV GOOGLE_APPLICATION_CREDENTIALS="/usr/local/etc/gcloud/application_default_credentials.json"

Expand All @@ -12,4 +12,4 @@ COPY . .

EXPOSE 3001

CMD ["npm", "run", "server"]
CMD ["npm", "run", "server"]
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -153,3 +153,6 @@ terraform apply tf_apply && rm tf_apply


[Link to terraform file](deployment/GCP/api.tf)


...
46 changes: 0 additions & 46 deletions cloudbuild_dynamic.yaml

This file was deleted.

11 changes: 9 additions & 2 deletions src/config/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@ import express from 'express';
import Provider from 'oidc-provider';
import swaggerUi from 'swagger-ui-express';
import cors from 'cors';
import logger from 'morgan';
import morgan from 'morgan';
import passport from 'passport';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';
import { connectToDatabase } from './db';
import { initialiseAuthentication } from '../resources/auth';

import { errorHandler } from '../middlewares';

require('dotenv').config();

var app = express();
Expand Down Expand Up @@ -57,7 +59,7 @@ connectToDatabase();
app.use(bodyParser.json({ limit: '10mb', extended: true }));
app.use(bodyParser.urlencoded({ limit: '10mb', extended: false }));

app.use(logger('dev'));
app.use(morgan('tiny'));
app.use(cookieParser());
app.use(passport.initialize());
app.use(passport.session());
Expand Down Expand Up @@ -164,7 +166,10 @@ app.use('/api/v1/auth/register', require('../resources/user/user.register.route'
app.use('/api/v1/users', require('../resources/user/user.route'));
app.use('/api/v1/topics', require('../resources/topic/topic.route'));
app.use('/api/v1/publishers', require('../resources/publisher/publisher.route'));

app.use('/api/v1/teams', require('../resources/team/team.route'));
app.use('/api/v3/teams', require('../resources/team/v3/team.route'));

app.use('/api/v1/workflows', require('../resources/workflow/workflow.route'));

app.use('/api/v1/messages', require('../resources/message/message.route'));
Expand Down Expand Up @@ -236,6 +241,8 @@ app.use('/api/v2/questionbank', require('../resources/questionbank/questionbank.
app.use('/api/v2/data-use-registers', require('../resources/dataUseRegister/dataUseRegister.route'));
app.use('/api/v1/locations', require('../resources/spatialfilter/SpatialRouter'));

app.use(errorHandler);

app.use('/api/v1/metadata', require('../resources/metadata/metadata.route'));

initialiseAuthentication(app);
Expand Down
4 changes: 2 additions & 2 deletions src/exceptions/HttpExceptions.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export default class HttpExceptions extends Error {
constructor(message) {
constructor(message, statusCode = 500) {
super(message);
this.message = message;
this.status = statusCode;
}
}
1 change: 0 additions & 1 deletion src/middlewares/__tests__/activitylog.middleware.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,6 @@ describe('Testing the ActivityLog middleware', () => {
await authoriseView(req, res, nextFunction);

expect(versionsStub.calledOnce).toBe(true);
expect(nextFunction.mock.calls.length).toBe(1);
});

it('Should respond 401 if an error is thrown', async () => {
Expand Down
17 changes: 17 additions & 0 deletions src/middlewares/checkAccessTeamMiddleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import HttpExceptions from '../exceptions/HttpExceptions';
import teamV3Util from '../resources/utilities/team.v3.util';

const checkAccessToTeamMiddleware = (arrayAllowedPermissions) => (req, res, next) => {
const teamId = req.params.teamid || '';
const currentUserId = req.user._id || '';

if (!teamId || !currentUserId) {
throw new HttpExceptions('One or more required parameters missing', 400);
}

req.allowPerms = arrayAllowedPermissions;

next();
}

export { checkAccessToTeamMiddleware };
26 changes: 26 additions & 0 deletions src/middlewares/errorHandler.middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@

import { LoggingService } from "../services";

const errorHandler = (error, req, res, next) => {
const errorStatusCode = error.status || 500;
const loggingService = new LoggingService();
const loggingEnabled = parseInt(process.env.LOGGING_LOG_ENABLED) || 0;

const errorMessage = {
type: 'error',
message: error.message,
stack: error.stack.split("\n"),
};

process.stdout.write(JSON.stringify(errorMessage));

if (loggingEnabled) {
loggingService.sendDataInLogging(errorMessage, 'ERROR');
}

res.status(errorStatusCode).json(errorMessage);

return;
}

export { errorHandler }
2 changes: 2 additions & 0 deletions src/middlewares/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import checkInputMiddleware from './checkInputMiddleware';
import checkMinLengthMiddleware from './checkMinLengthMiddleware';
import checkStringMiddleware from './checkStringMiddleware';
import { validateUpdateRequest, validateUploadRequest, authorizeUpdate, authorizeUpload } from './dataUseRegister.middleware';
import { errorHandler } from './errorHandler.middleware';

export {
checkIDMiddleware,
Expand All @@ -30,4 +31,5 @@ export {
validateUploadRequest,
authorizeUpdate,
authorizeUpload,
errorHandler,
};
Empty file.
6 changes: 5 additions & 1 deletion src/resources/auth/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,11 @@ const loginAndSignToken = (req, res, next) => {
const userIsTeamManager = () => async (req, res, next) => {
const { user, params } = req;
const members = await TeamModel.findOne({ _id: params.id }, { _id: 0, members: { $elemMatch: { memberid: user._id } } }).lean();
if ((!isEmpty(members) && members.members[0].roles.includes(constants.roleTypes.MANAGER)) || user.role === 'Admin') return next();

const isDarManager = members.members[0].roles.includes(constants.roleMemberTeam.CUST_DAR_MANAGER);
const isTeamAdmin = members.members[0].roles.includes(constants.roleMemberTeam.CUST_TEAM_ADMIN);

if ((!isEmpty(members) && (isDarManager || isTeamAdmin)) || user.role === 'Admin') return next();

return res.status(401).json({
status: 'error',
Expand Down
2 changes: 1 addition & 1 deletion src/resources/collections/collectioncounter.route.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const datasetLimiter = rateLimit({

router.post('/update', datasetLimiter, async (req, res) => {
const { id, counter } = req.body;
Collections.findOneAndUpdate({ id: { $eq: id } }, { counter }, err => {
Collections.findOneAndUpdate({ id: { $eq: id } }, { $set: { counter: counter } }, { timestamps: false }, err => {
if (err) return res.json({ success: false, error: err });
return res.json({ success: true });
});
Expand Down
60 changes: 10 additions & 50 deletions src/resources/dataUseRegister/dataUseRegister.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { filtersService } from '../filters/dependency';
import { DataUseRegister } from '../dataUseRegister/dataUseRegister.model';
import { isEmpty, isUndefined } from 'lodash';
import { UserModel } from '../user/user.model';
import HttpExceptions from '../../exceptions/HttpExceptions';

const logCategory = 'dataUseRegister';

Expand All @@ -33,10 +34,7 @@ export default class DataUseRegisterController extends Controller {

// If no id provided, it is a bad request
if (!id) {
return res.status(400).json({
success: false,
message: 'You must provide a dataUseRegister identifier',
});
throw new HttpExceptions(`You must provide a dataUseRegister identifier`, 400);
}

// Find the dataUseRegister
Expand All @@ -53,10 +51,7 @@ export default class DataUseRegisterController extends Controller {

// Return if no dataUseRegister found
if (!dataUseRegister) {
return res.status(404).json({
success: false,
message: 'A dataUseRegister could not be found with the provided id',
});
throw new HttpExceptions(`A dataUseRegister could not be found with the provided id`, 404);
}

// Reverse look up
Expand Down Expand Up @@ -100,12 +95,7 @@ export default class DataUseRegisterController extends Controller {
...dataUseRegister,
});
} catch (err) {
// Return error response if something goes wrong
process.stdout.write(`DATA USE REGISTER - getDataUseRegister : ${err.message}`);
return res.status(500).json({
success: false,
message: 'A server error occurred, please try again',
});
throw new HttpExceptions(`A server error occurred, please try again :: ${err.message}`, 500);
}
}

Expand Down Expand Up @@ -149,12 +139,7 @@ export default class DataUseRegisterController extends Controller {
});
}
} catch (err) {
// Return error response if something goes wrong
logger.logError(err, logCategory);
return res.status(500).json({
success: false,
message: 'A server error occurred, please try again',
});
throw new HttpExceptions(`A server error occurred, please try again :: ${err.message}`, 500);
}
}

Expand Down Expand Up @@ -210,12 +195,7 @@ export default class DataUseRegisterController extends Controller {
success: true,
});
} catch (err) {
// Return error response if something goes wrong
logger.logError(err, logCategory);
return res.status(500).json({
success: false,
message: 'A server error occurred, please try again',
});
throw new HttpExceptions(`A server error occurred, please try again :: ${JSON.stringify(err.message)}`, 500);
}
}

Expand All @@ -231,12 +211,7 @@ export default class DataUseRegisterController extends Controller {
result,
});
} catch (err) {
// Return error response if something goes wrong
logger.logError(err, logCategory);
return res.status(500).json({
success: false,
message: 'A server error occurred, please try again',
});
throw new HttpExceptions(`A server error occurred, please try again :: ${JSON.stringify(err.message)}`, 500);
}
}

Expand All @@ -248,12 +223,7 @@ export default class DataUseRegisterController extends Controller {

return res.status(200).json({ success: true, result });
} catch (err) {
// Return error response if something goes wrong
logger.logError(err, logCategory);
return res.status(500).json({
success: false,
message: 'A server error occurred, please try again',
});
throw new HttpExceptions(`A server error occurred, please try again :: ${err.message}`, 500);
}
}

Expand Down Expand Up @@ -376,12 +346,7 @@ export default class DataUseRegisterController extends Controller {

return res.status(200).json({ success: true, newPayload });
} catch (err) {
//Return error response if something goes wrong
logger.logError(err, logCategory);
return res.status(500).json({
success: false,
message: 'A server error occurred, please try again',
});
throw new HttpExceptions(`A server error occurred, please try again :: ${err.message}`, 500);
}
}

Expand Down Expand Up @@ -478,12 +443,7 @@ export default class DataUseRegisterController extends Controller {
this.dataUseRegisterService.updateDataUseRegister(id, { counter });
return res.status(200).json({ success: true });
} catch (err) {
// Return error response if something goes wrong
logger.logError(err, logCategory);
return res.status(500).json({
success: false,
message: 'A server error occurred, please try again',
});
throw new HttpExceptions(`A server error occurred, please try again :: ${err.message}`, 500);
}
}
}
13 changes: 8 additions & 5 deletions src/resources/dataUseRegister/dataUseRegister.route.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ router.get('/search', logger.logRequestMiddleware({ logCategory, action: 'Search
dataUseRegisterController.searchDataUseRegisters(req, res)
);

// @route GET /api/v2/data-use-registers/id
// @route GET /api/v2/data-use-registers/:id
// @desc Returns a dataUseRegister based on dataUseRegister ID provided
// @access Public
router.get('/:id', logger.logRequestMiddleware({ logCategory, action: 'Viewed dataUseRegister data' }), (req, res) =>
Expand All @@ -35,8 +35,9 @@ router.get(
// @route PATCH /api/v2/data-use-registers/counter
// @desc Updates the data use register counter for page views
// @access Public
router.patch('/counter', logger.logRequestMiddleware({ logCategory, action: 'Data use counter update' }), (req, res) =>
dataUseRegisterController.updateDataUseRegisterCounter(req, res)
router.patch('/counter',
logger.logRequestMiddleware({ logCategory, action: 'Data use counter update' }),
(req, res) => dataUseRegisterController.updateDataUseRegisterCounter(req, res)
);

// @route PATCH /api/v2/data-use-registers/id
Expand All @@ -54,8 +55,10 @@ router.patch(
// @route POST /api/v2/data-use-registers/check
// @desc Check the submitted data uses for duplicates and returns links to Gatway entities (datasets, users)
// @access Public
router.post('/check', passport.authenticate('jwt'), logger.logRequestMiddleware({ logCategory, action: 'Check data uses' }), (req, res) =>
dataUseRegisterController.checkDataUseRegister(req, res)
router.post('/check',
passport.authenticate('jwt'),
logger.logRequestMiddleware({ logCategory, action: 'Check data uses' }),
(req, res) => dataUseRegisterController.checkDataUseRegister(req, res)
);

// @route POST /api/v2/data-use-registers/upload
Expand Down
Loading

0 comments on commit ee50315

Please sign in to comment.