Skip to content

Commit

Permalink
Upgrade Amplify to v6 (#139802)
Browse files Browse the repository at this point in the history
Co-authored-by: BearHanded <[email protected]>
  • Loading branch information
gmrabian and BearHanded authored Oct 22, 2024
1 parent 8ee3b08 commit d8a1d72
Show file tree
Hide file tree
Showing 25 changed files with 1,406 additions and 2,188 deletions.
10 changes: 6 additions & 4 deletions services/app-api/handlers/uploads/delete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,22 @@ import { UnauthorizedError } from "../../libs/httpErrors";
*/
export const deleteUpload = handler(async (event, _context) => {
const user = getUserCredentialsFromJwt(event);
const body = event.body ? JSON.parse(event.body) : null;
const state = event.pathParameters ? event.pathParameters["state"] : "";
const fileId = event.pathParameters ? event.pathParameters["fileId"] : "";

if (user.role !== AppRoles.STATE_USER || !body || !body.fileId || !state) {
if (user.role !== AppRoles.STATE_USER || !fileId || !state) {
throw new UnauthorizedError("Unauthorized");
}

const decodedFileId = decodeURIComponent(fileId);
// Get file, check aws filename before deleting
const documentParams = {
TableName: process.env.uploadsTableName!,
KeyConditionExpression:
"uploadedState = :uploadedState AND fileId = :fileId",
ExpressionAttributeValues: {
":uploadedState": state,
":fileId": body.fileId,
":fileId": decodedFileId,
},
};
const results = await dynamoDb.query(documentParams);
Expand All @@ -44,7 +46,7 @@ export const deleteUpload = handler(async (event, _context) => {
TableName: process.env.uploadsTableName!,
Key: {
uploadedState: state,
fileId: body.fileId,
fileId: decodedFileId,
},
};

Expand Down
3 changes: 1 addition & 2 deletions services/app-api/handlers/uploads/tests/delete.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,7 @@ describe("Test Delete Upload Handler", () => {
test("Should Call S3 delete when entry exists", async () => {
const event: APIGatewayProxyEvent = {
...testEvent,
body: `{"fileId": "uniqueIdString"}`,
pathParameters: { year: "2022", state: "AL" },
pathParameters: { year: "2022", state: "AL", fileId: "uniqueIdString" },
};

const res = await deleteUpload(event, null);
Expand Down
2 changes: 1 addition & 1 deletion services/app-api/serverless.yml
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ functions:
handler: handlers/uploads/delete.deleteUpload
events:
- http:
path: uploads/{year}/{state}
path: uploads/{year}/{state}/{fileId}
method: delete
cors: true
authorizer: aws_iam
Expand Down
8 changes: 3 additions & 5 deletions services/ui-src/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"version": "0.1.0",
"private": true,
"dependencies": {
"@aws-amplify/rtn-web-browser": "^1.0.28",
"@cmsgov/design-system": "^3.8.0",
"@fortawesome/fontawesome-svg-core": "^1.2.29",
"@fortawesome/free-solid-svg-icons": "^5.13.1",
Expand All @@ -16,7 +17,7 @@
"@testing-library/react": "^9.5.0",
"@testing-library/user-event": "^14.5.1",
"@vitejs/plugin-react": "^4.2.1",
"aws-amplify": "^5.3.4",
"aws-amplify": "^6.6.4",
"date-fns": "^3.6.0",
"font-awesome": "^4.7.0",
"jsonpath": "^1.0.2",
Expand Down Expand Up @@ -121,10 +122,7 @@
"moduleNameMapper": {
"\\.(css|less|scss)$": "<rootDir>/src/util/testing/styleMock.js",
"\\.(jpg|jpeg|png|gif|webp|svg|mp4|webm|wav|mp3|m4a)$": "<rootDir>/src/util/testing/mockAsset.ts"
},
"transformIgnorePatterns": [
"node_modules/(?!axios)"
]
}
},
"resolutions": {
"react-error-overlay": "6.0.9",
Expand Down
2 changes: 1 addition & 1 deletion services/ui-src/src/actions/certify.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export const certifyAndSubmit = () => async (dispatch, getState) => {
username: username,
};

apiLib.post("carts-api", `/state_status/${year}/${state}`, opts);
await apiLib.post(`/state_status/${year}/${state}`, opts);
dispatch({
type: CERTIFY_AND_SUBMIT_SUCCESS,
user: username,
Expand Down
6 changes: 1 addition & 5 deletions services/ui-src/src/actions/download.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,7 @@ export const getFiscalYearTemplate = (year) => async (dispatch) => {
dispatch({ type: GET_TEMPLATE, data: "" });
try {
const opts = await requestOptions();
const data = await apiLib.get(
"carts-api",
`/fiscalYearTemplate/${year}`,
opts
);
const data = await apiLib.get(`/fiscalYearTemplate/${year}`, opts);

dispatch({
type: GET_TEMPLATE_SUCCESS,
Expand Down
10 changes: 4 additions & 6 deletions services/ui-src/src/actions/initial.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export const getAllStatesData = () => {
return async (dispatch) => {
try {
const opts = await requestOptions();
const data = await apiLib.get("carts-api", `/state`, opts);
const data = await apiLib.get(`/state`, opts);

dispatch({ type: GET_ALL_STATES_DATA, data });
} catch (err) {
Expand All @@ -27,7 +27,7 @@ export const getAllStatesData = () => {

export const getAllStateStatuses = () => async (dispatch) => {
const opts = await requestOptions();
const results = await apiLib.get("carts-api", `/state_status`, opts);
const results = await apiLib.get(`/state_status`, opts);
const data = results.Items;

const payload = data
Expand Down Expand Up @@ -72,7 +72,7 @@ export const getStateAllStatuses =
(selectedYears = [], selectedStates = [], selectedStatus = []) =>
async (dispatch) => {
const opts = await requestOptions();
const results = await apiLib.get("carts-api", `/state_status`, opts);
const results = await apiLib.get(`/state_status`, opts);
const data = results.Items;
let yearFilter = () => {};
let stateFilter = () => {};
Expand Down Expand Up @@ -124,15 +124,14 @@ export const loadSections = ({ stateCode, selectedYear }) => {
return async (dispatch) => {
const opts = await requestOptions();
const data = await apiLib.get(
"carts-api",
`/section/${selectedYear}/${stateCode}`,
opts
);

const lastYear = parseInt(selectedYear) - 1;
let lastYearData = undefined;
const priorData = await apiLib
.get("carts-api", `/section/${lastYear}/${stateCode}`, opts)
.get(`/section/${lastYear}/${stateCode}`, opts)
.catch((err) => {
console.log("--- ERROR PRIOR YEAR SECTIONS ---");
console.log(err);
Expand All @@ -155,7 +154,6 @@ export const loadEnrollmentCounts = ({ stateCode, selectedYear }) => {
return async (dispatch) => {
const opts = await requestOptions();
const data = await apiLib.get(
"carts-api",
`/enrollment_counts/${selectedYear}/${stateCode}`,
opts
);
Expand Down
2 changes: 1 addition & 1 deletion services/ui-src/src/actions/uncertify.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export const uncertifyReport =
state: state,
};

await apiLib.post("carts-api", `/state_status/${year}/${state}`, opts);
await apiLib.post(`/state_status/${year}/${state}`, opts);
dispatch({
type: UNCERTIFY_SUCCESS,
user: username,
Expand Down
2 changes: 1 addition & 1 deletion services/ui-src/src/components/layout/FormTemplates.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const FormTemplates = () => {

try {
const opts = await requestOptions({ year: selectedYear });
await apiLib.post("carts-api", "/formTemplates", opts);
await apiLib.post("/formTemplates", opts);
window.alert("Request Completed");
history.push("/");
} catch (e) {
Expand Down
11 changes: 4 additions & 7 deletions services/ui-src/src/components/layout/FormTemplates.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,8 @@ import { shallow } from "enzyme";
import FormTemplates from "./FormTemplates";
import { act, render, fireEvent } from "@testing-library/react";

const mockPost = jest.fn();
jest.mock("aws-amplify", () => ({
API: {
post: () => mockPost(),
},
}));
const mockAmplifyApi = require("aws-amplify/api");

jest.mock("../../hooks/authHooks");
window.alert = jest.fn();

Expand All @@ -31,12 +27,13 @@ describe("FormTemplates Component", () => {
});

it("fires the generate forms event on button click, then navigates", async () => {
const apiSpy = jest.spyOn(mockAmplifyApi, "post");
const { getByTestId } = render(formTemplate);
const generateButton = getByTestId("generate-forms-button");
await act(async () => {
fireEvent.click(generateButton);
});
expect(mockPost).toHaveBeenCalled();
expect(apiSpy).toHaveBeenCalled();
expect(mockHistoryPush).toHaveBeenCalledWith("/");
});
});
2 changes: 1 addition & 1 deletion services/ui-src/src/components/sections/Print.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ const Print = () => {
encodedHtml: base64String,
};

const res = await apiLib.post("carts-api", "/print_pdf", opts);
const res = await apiLib.post("/print_pdf", opts);
openPdf(res.data);
};
// Load formData via side effect
Expand Down
4 changes: 2 additions & 2 deletions services/ui-src/src/components/sections/login/LocalLogins.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React from "react";
import { useHistory } from "react-router-dom";
import { Auth } from "aws-amplify";
import { signIn } from "aws-amplify/auth";
import { useFormFields } from "../../../hooks/useFormFields";

const LocalLogin = () => {
Expand All @@ -12,7 +12,7 @@ const LocalLogin = () => {
async function handleLogin(event) {
event.preventDefault();
try {
await Auth.signIn(fields.email, fields.password);
await signIn({ username: fields.email, password: fields.password });
history.push(`/`);
} catch (error) {
console.log("Error while logging in.", error); // eslint-disable-line no-console
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,8 @@ import { LocalLogins } from "./LocalLogins";

const mockPost = jest.fn();
const localLogins = <LocalLogins />;
jest.mock("aws-amplify", () => ({
Auth: {
signIn: (email, password) => mockPost(email, password),
},
jest.mock("aws-amplify/auth", () => ({
signIn: (credentials) => mockPost(credentials),
}));
const mockHistoryPush = jest.fn();
jest.mock("react-router-dom", () => ({
Expand Down Expand Up @@ -38,7 +36,10 @@ describe("LocalLogin component", () => {
await act(async () => {
fireEvent.click(generateButton);
});
expect(mockPost).toHaveBeenCalledWith("[email protected]", "superS3cure");
expect(mockPost).toHaveBeenCalledWith({
username: "[email protected]",
password: "superS3cure", // pragma: allowlist secret
});
expect(mockHistoryPush).toHaveBeenCalledWith("/");
});
});
9 changes: 5 additions & 4 deletions services/ui-src/src/hooks/authHooks/authLifecycle.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Auth, Hub } from "aws-amplify";
import { fetchAuthSession, signOut } from "aws-amplify/auth";
import { Hub } from "aws-amplify/utils";
import { add } from "date-fns";
import { setAuthTimeout } from "../../store/stateUser";

Expand Down Expand Up @@ -27,7 +28,7 @@ class AuthManager {
const isExpired = expiration && new Date(expiration).valueOf() < Date.now();
if (isExpired) {
localStorage.removeItem("mdctcarts_session_exp");
Auth.signOut().then(() => {
signOut().then(() => {
window.location.href = "/";
});
}
Expand Down Expand Up @@ -56,7 +57,7 @@ class AuthManager {
* Manual refresh of credentials paired with an instant timer clear
*/
async refreshCredentials() {
await Auth.currentAuthenticatedUser({ bypassCache: true }); // Force a token refresh
await fetchAuthSession({ forceRefresh: true }); // Force a token refresh
this.setTimer();
}

Expand All @@ -75,7 +76,7 @@ class AuthManager {
this.promptTimeout(exp);
this.timeoutForceId = setTimeout(() => {
localStorage.removeItem("mdctcarts_session_exp");
Auth.signOut();
signOut();
}, IDLE_WINDOW - PROMPT_AT);
},
PROMPT_AT,
Expand Down
8 changes: 3 additions & 5 deletions services/ui-src/src/hooks/authHooks/requestOptions.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import { Auth } from "aws-amplify";
import { fetchAuthSession } from "aws-amplify/auth";

async function requestOptions(body = null) {
try {
const session = await Auth.currentSession();
const token = await session.getIdToken().getJwtToken();

const { idToken } = (await fetchAuthSession()).tokens ?? {};
const options = {
headers: { "x-api-key": token },
headers: { "x-api-key": idToken?.toString() },
};
if (body) {
options["body"] = body;
Expand Down
16 changes: 6 additions & 10 deletions services/ui-src/src/hooks/authHooks/requestOptions.test.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
import requestOptions from "./requestOptions";

jest.mock("aws-amplify", () => ({
Auth: {
currentSession: jest.fn().mockReturnValue({
getIdToken: () => ({
getJwtToken: () => {
return "mock token";
},
}),
}),
},
jest.mock("aws-amplify/auth", () => ({
fetchAuthSession: jest.fn().mockReturnValue({
tokens: {
idToken: "mock token",
},
}),
}));

describe("requestOptions", () => {
Expand Down
Loading

0 comments on commit d8a1d72

Please sign in to comment.