Skip to content

Commit

Permalink
BRS-1172: Adding PUT for variance (#166)
Browse files Browse the repository at this point in the history
  • Loading branch information
marklise authored Jun 19, 2023
1 parent 5b854c6 commit 1f2fe1a
Show file tree
Hide file tree
Showing 2 changed files with 153 additions and 45 deletions.
137 changes: 94 additions & 43 deletions __tests__/variance.test.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
const AWS = require("aws-sdk");
const { DocumentClient } = require("aws-sdk/clients/dynamodb");
const { REGION, ENDPOINT, TABLE_NAME } = require("./global/settings");
const { PARKSLIST } = require("./global/data.json");
const {
REGION,
ENDPOINT,
TABLE_NAME
} = require("./global/settings");

const jwt = require("jsonwebtoken");
const tokenContent = {
resource_access: { "attendance-and-revenue": { roles: ["sysadmin"] } },
};
const token = jwt.sign(tokenContent, "defaultSecret");

const suffix = "-varianceTest";
const testParkList = [];

async function setupDb() {
new AWS.DynamoDB({
region: REGION,
Expand Down Expand Up @@ -82,20 +82,6 @@ describe("Variance Test", () => {
}),
};

const mockedUnauthenticatedUser = {
decodeJWT: jest.fn((event) => {}),
resolvePermissions: jest.fn((token) => {
return {
isAdmin: false,
roles: [],
isAuthenticated: false,
};
}),
getParkAccess: jest.fn((orcs, permissionObject) => {
return {};
}),
};

const mockedSysadmin = {
decodeJWT: jest.fn((event) => {}),
resolvePermissions: jest.fn((token) => {
Expand Down Expand Up @@ -125,12 +111,6 @@ describe("Variance Test", () => {
});

test("Variance GET Single SK Success", async () => {
const axios = require("axios");
jest.mock("axios");
axios.post.mockImplementation(() =>
Promise.resolve({ statusCode: 200, data: {} })
);

jest.mock("../lambda/permissionUtil", () => {
return mockedSysadmin;
});
Expand All @@ -155,12 +135,6 @@ describe("Variance Test", () => {
});

test("Variance GET FAIL 403 limited user", async () => {
const axios = require("axios");
jest.mock("axios");
axios.post.mockImplementation(() =>
Promise.resolve({ statusCode: 200, data: {} })
);

jest.mock("../lambda/permissionUtil", () => {
return mockedLimitedUser;
});
Expand All @@ -185,12 +159,6 @@ describe("Variance Test", () => {
});

test("Variance GET FAIL 403 public user", async () => {
const axios = require("axios");
jest.mock("axios");
axios.post.mockImplementation(() =>
Promise.resolve({ statusCode: 200, data: {} })
);

jest.mock("../lambda/permissionUtil", () => {
return mockedUnauthenticatedInvalidUser;
});
Expand All @@ -215,12 +183,6 @@ describe("Variance Test", () => {
});

test("Variance GET FAIL invalid params", async () => {
const axios = require("axios");
jest.mock("axios");
axios.post.mockImplementation(() =>
Promise.resolve({ statusCode: 200, data: {} })
);

jest.mock("../lambda/permissionUtil", () => {
return mockedSysadmin;
});
Expand Down Expand Up @@ -269,4 +231,93 @@ describe("Variance Test", () => {
percentageChange: 0.25,
});
});

test("Variance PUT FAIL invalid params", async () => {
jest.mock("../lambda/permissionUtil", () => {
return mockedSysadmin;
});

const variancePUT = require("../lambda/variance/PUT/index");
const response = await variancePUT.handler(
{
headers: {
Authorization: "Bearer " + token,
}
},
null
);
const body = JSON.parse(response.body);
expect(response.statusCode).toBe(400);
expect(response.body === "{ msg: 'Invalid request.' }")
});

test("Variance PUT FAIL 403 public user", async () => {
jest.mock("../lambda/permissionUtil", () => {
return mockedUnauthenticatedInvalidUser;
});

const variancePUT = require("../lambda/variance/PUT/index");
const response = await variancePUT.handler(
{
headers: {
Authorization: "Bearer " + token,
}
},
null
);
const body = JSON.parse(response.body);
expect(response.statusCode).toBe(403);
expect(response.body === "{ msg: 'Error: UnAuthenticated.' }")
});

test("Variance PUT FAIL 403 limited user", async () => {
jest.mock("../lambda/permissionUtil", () => {
return mockedLimitedUser;
});

const variancePUT = require("../lambda/variance/PUT/index");
const response = await variancePUT.handler(
{
headers: {
Authorization: "Bearer " + token,
}
},
null
);
const body = JSON.parse(response.body);
expect(response.statusCode).toBe(403);
expect(response.body === "{ msg: 'Error: UnAuthenticated.' }")
});

test("Variance PUT Success", async () => {
const axios = require("axios");
jest.mock("axios");
axios.post.mockImplementation(() =>
Promise.resolve({ statusCode: 200, data: {} })
);

jest.mock("../lambda/permissionUtil", () => {
return mockedSysadmin;
});

const variancePUT = require("../lambda/variance/PUT/index");
const response = await variancePUT.handler(
{
headers: {
Authorization: "Bearer " + token,
},
body: JSON.stringify({
subAreaId: "0001",
activity: "Day Use",
date: "2022-01-01",
fields: ["Some Field"],
resolve: true,
note: "Some Note"
}),
},
null
);
const body = JSON.parse(response.body);
expect(response.statusCode).toBe(200);
});
});
61 changes: 59 additions & 2 deletions lambda/variance/PUT/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,61 @@
const { dynamodb, TABLE_NAME } = require("../../dynamoUtil");
const { decodeJWT, resolvePermissions } = require("../../permissionUtil");
const { logger } = require("../../logger");
const { sendResponse } = require("../../responseUtil");

exports.handler = async (event, context) => {
logger.debug("Variance put:", event);
return sendResponse(501, { msg: "Error: Not implemented." }, context);
logger.debug("Variance PUT:", event);
try {
const token = await decodeJWT(event);
const permissionObject = resolvePermissions(token);

if (!permissionObject.isAuthenticated) {
logger.info("**NOT AUTHENTICATED, PUBLIC**");
return sendResponse(403, { msg: "Error: Unauthenticated." }, context);
}

// Admins only
if (!permissionObject.isAdmin) {
logger.info("Not authorized.");
return sendResponse(403, { msg: "Unauthorized." }, context);
}

const body = JSON.parse(event.body);

if (!body.subAreaId || !body.activity || !body.date) {
return sendResponse(400, { msg: "Invalid request" }, context);
}

let params = {
TableName: TABLE_NAME,
ConditionExpression: "attribute_exists(pk) AND attribute_exists(sk)",
Key: {
pk: { S: `variance::${body.subAreaId}::${body.activity}` },
sk: { S: body.date }
},
UpdateExpression: `SET note =:note, resolved =:resolved, #roles =:roles`,
ExpressionAttributeValues: {
':note': { S: body.note },
':resolved': { BOOL: body.resolved ? body.resolved : false },
':roles': { SS: ["sysadmin"] }
},
ExpressionAttributeNames: {
'#roles': 'roles'
}
};

if (body.fields) {
params.ExpressionAttributeValues[':fields'] = { L: body.fields.map(item => ({ S: item })) };
params.UpdateExpression += ', #fields =:fields';
params.ExpressionAttributeNames['#fields'] = 'fields';
}

const res = await dynamodb.updateItem(params).promise();
logger.info("Variance updated");
logger.debug("Result:", res);
return sendResponse(200, res);
} catch (err) {
logger.error(err);
return sendResponse(400, { msg: "Invalid request" }, context);
}
};

0 comments on commit 1f2fe1a

Please sign in to comment.