Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor amplify to live in apiLib #139859

Merged
merged 3 commits into from
Dec 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions services/ui-src/src/actions/certify.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import requestOptions from "../hooks/authHooks/requestOptions";
import { REPORT_STATUS } from "../types";
import { apiLib } from "../util/apiLib";

Expand All @@ -19,10 +18,11 @@ export const certifyAndSubmit = () => async (dispatch, getState) => {
dispatch({ type: CERTIFY_AND_SUBMIT });

try {
const opts = await requestOptions();
opts.body = {
status: REPORT_STATUS.certified,
username: username,
const opts = {
body: {
status: REPORT_STATUS.certified,
username: username,
},
};

await apiLib.post(`/state_status/${year}/${state}`, opts);
Expand Down
4 changes: 1 addition & 3 deletions services/ui-src/src/actions/download.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import requestOptions from "../hooks/authHooks/requestOptions";
import { apiLib } from "../util/apiLib";

export const GET_TEMPLATE = "GET_TEMPLATE";
Expand All @@ -8,8 +7,7 @@ export const GET_TEMPLATE_FAILURE = "GET_TEMPLATE_FAILURE";
export const getFiscalYearTemplate = (year) => async (dispatch) => {
dispatch({ type: GET_TEMPLATE, data: "" });
try {
const opts = await requestOptions();
const data = await apiLib.get(`/fiscalYearTemplate/${year}`, opts);
const data = await apiLib.get(`/fiscalYearTemplate/${year}`);

dispatch({
type: GET_TEMPLATE_SUCCESS,
Expand Down
22 changes: 6 additions & 16 deletions services/ui-src/src/actions/initial.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
/* eslint-disable no-underscore-dangle, no-console */
import requestOptions from "../hooks/authHooks/requestOptions";
import { getProgramData, getStateData, getUserData } from "../store/stateUser";
import { apiLib } from "../util/apiLib";

Expand All @@ -14,8 +13,7 @@ export const LOAD_LASTYEAR_SECTIONS = "LOAD_LASTYEAR_SECTIONS";
export const getAllStatesData = () => {
return async (dispatch) => {
try {
const opts = await requestOptions();
const data = await apiLib.get(`/state`, opts);
const data = await apiLib.get(`/state`);

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

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

const payload = data
Expand Down Expand Up @@ -71,8 +68,7 @@ export const getAllStateStatuses = () => async (dispatch) => {
export const getStateAllStatuses =
(selectedYears = [], selectedStates = [], selectedStatus = []) =>
async (dispatch) => {
const opts = await requestOptions();
const results = await apiLib.get(`/state_status`, opts);
const results = await apiLib.get(`/state_status`);
const data = results.Items;
let yearFilter = () => {};
let stateFilter = () => {};
Expand Down Expand Up @@ -122,16 +118,12 @@ export const getStateAllStatuses =

export const loadSections = ({ stateCode, selectedYear }) => {
return async (dispatch) => {
const opts = await requestOptions();
const data = await apiLib.get(
`/section/${selectedYear}/${stateCode}`,
opts
);
const data = await apiLib.get(`/section/${selectedYear}/${stateCode}`);

const lastYear = parseInt(selectedYear) - 1;
let lastYearData = undefined;
const priorData = await apiLib
.get(`/section/${lastYear}/${stateCode}`, opts)
.get(`/section/${lastYear}/${stateCode}`)
.catch((err) => {
console.log("--- ERROR PRIOR YEAR SECTIONS ---");
console.log(err);
Expand All @@ -152,10 +144,8 @@ export const loadSections = ({ stateCode, selectedYear }) => {

export const loadEnrollmentCounts = ({ stateCode, selectedYear }) => {
return async (dispatch) => {
const opts = await requestOptions();
const data = await apiLib.get(
`/enrollment_counts/${selectedYear}/${stateCode}`,
opts
`/enrollment_counts/${selectedYear}/${stateCode}`
);

dispatch({ type: SET_ENROLLMENT_COUNTS, data });
Expand Down
14 changes: 7 additions & 7 deletions services/ui-src/src/actions/uncertify.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import requestOptions from "../hooks/authHooks/requestOptions";
import { REPORT_STATUS } from "../types";
import { apiLib } from "../util/apiLib";

Expand All @@ -16,12 +15,13 @@ export const uncertifyReport =

dispatch({ type: UNCERTIFY });
try {
const opts = await requestOptions();
opts.body = {
status: REPORT_STATUS.in_progress,
username: username,
year: reportYear,
state: state,
const opts = {
body: {
status: REPORT_STATUS.in_progress,
username: username,
year: reportYear,
state: state,
},
};

await apiLib.post(`/state_status/${year}/${state}`, opts);
Expand Down
5 changes: 3 additions & 2 deletions services/ui-src/src/components/layout/FormTemplates.jsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import requestOptions from "../../hooks/authHooks/requestOptions";
import React, { useState } from "react";
import "react-data-table-component-extensions/dist/index.css";
import { Button } from "@cmsgov/design-system";
Expand All @@ -15,7 +14,9 @@ const FormTemplates = () => {
setInprogress(true);

try {
const opts = await requestOptions({ year: selectedYear });
const opts = {
body: { year: selectedYear },
};
await apiLib.post("/formTemplates", opts);
window.alert("Request Completed");
history.push("/");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ import React from "react";
import { shallow } from "enzyme";
import FormTemplates from "./FormTemplates";
import { act, render, fireEvent } from "@testing-library/react";

const mockAmplifyApi = require("aws-amplify/api");
import { apiLib } from "../../util/apiLib";

jest.mock("../../hooks/authHooks");
window.alert = jest.fn();
Expand All @@ -27,7 +26,7 @@ describe("FormTemplates Component", () => {
});

it("fires the generate forms event on button click, then navigates", async () => {
const apiSpy = jest.spyOn(mockAmplifyApi, "post");
const apiSpy = jest.spyOn(apiLib, "post");
const { getByTestId } = render(formTemplate);
const generateButton = getByTestId("generate-forms-button");
await act(async () => {
Expand Down
8 changes: 4 additions & 4 deletions services/ui-src/src/components/sections/Print.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import Section from "../layout/Section";
// utils
import statesArray from "../utils/statesArray";
import { loadEnrollmentCounts, loadSections } from "../../actions/initial";
import requestOptions from "../../hooks/authHooks/requestOptions";
import { apiLib } from "../../util/apiLib";

/**
Expand Down Expand Up @@ -83,9 +82,10 @@ const Print = () => {
.replaceAll("\u2014", "-");

const base64String = btoa(unescape(encodeURIComponent(htmlString)));
const opts = await requestOptions();
opts.body = {
encodedHtml: base64String,
const opts = {
body: {
encodedHtml: base64String,
},
};

const res = await apiLib.post("/print_pdf", opts);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React from "react";
import { useHistory } from "react-router-dom";
import { signIn } from "aws-amplify/auth";
import { useFormFields } from "../../../hooks/useFormFields";
import { loginUser } from "../../../util/apiLib";

const LocalLogin = () => {
const history = useHistory();
Expand All @@ -12,8 +12,8 @@ const LocalLogin = () => {
async function handleLogin(event) {
event.preventDefault();
try {
await signIn({ username: fields.email, password: fields.password });
history.push(`/`);
await loginUser(fields.email, 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 @@ -3,10 +3,10 @@ import { shallow } from "enzyme";
import { act, render, fireEvent } from "@testing-library/react";
import { LocalLogins } from "./LocalLogins";

const mockPost = jest.fn();
const localLogins = <LocalLogins />;
jest.mock("aws-amplify/auth", () => ({
signIn: (credentials) => mockPost(credentials),
const mockLoginUser = jest.fn();
jest.mock("../../../util/apiLib", () => ({
loginUser: (username, password) => mockLoginUser(username, password),
}));
const mockHistoryPush = jest.fn();
jest.mock("react-router-dom", () => ({
Expand All @@ -31,15 +31,12 @@ describe("LocalLogin component", () => {
fireEvent.change(emailField, { target: { value: "[email protected]" } });
});
await act(async () => {
fireEvent.change(passwordField, { target: { value: "superS3cure" } });
fireEvent.change(passwordField, { target: { value: "test" } });
});
await act(async () => {
fireEvent.click(generateButton);
});
expect(mockPost).toHaveBeenCalledWith({
username: "[email protected]",
password: "superS3cure", // pragma: allowlist secret
});
expect(mockLoginUser).toHaveBeenCalledWith("[email protected]", "test");
expect(mockHistoryPush).toHaveBeenCalledWith("/");
});
});
8 changes: 4 additions & 4 deletions services/ui-src/src/hooks/authHooks/authLifecycle.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { fetchAuthSession, signOut } from "aws-amplify/auth";
import { Hub } from "aws-amplify/utils";
import { add } from "date-fns";
import { setAuthTimeout } from "../../store/stateUser";
import { logoutUser, refreshSession } from "../../util/apiLib";

/*
* After the token expires, refresh tokens will be used in the allotted idle window.
Expand All @@ -28,7 +28,7 @@ class AuthManager {
const isExpired = expiration && new Date(expiration).valueOf() < Date.now();
if (isExpired) {
localStorage.removeItem("mdctcarts_session_exp");
signOut().then(() => {
logoutUser().then(() => {
window.location.href = "/";
});
}
Expand Down Expand Up @@ -57,7 +57,7 @@ class AuthManager {
* Manual refresh of credentials paired with an instant timer clear
*/
async refreshCredentials() {
await fetchAuthSession({ forceRefresh: true }); // Force a token refresh
await refreshSession();
this.setTimer();
}

Expand All @@ -76,7 +76,7 @@ class AuthManager {
this.promptTimeout(exp);
this.timeoutForceId = setTimeout(() => {
localStorage.removeItem("mdctcarts_session_exp");
signOut();
logoutUser();
}, IDLE_WINDOW - PROMPT_AT);
},
PROMPT_AT,
Expand Down
1 change: 0 additions & 1 deletion services/ui-src/src/hooks/authHooks/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
export * from "./useUser";
export * from "./userProvider";
export * from "./requestOptions";
export * from "./authLifecycle";
18 changes: 0 additions & 18 deletions services/ui-src/src/hooks/authHooks/requestOptions.js

This file was deleted.

35 changes: 0 additions & 35 deletions services/ui-src/src/hooks/authHooks/requestOptions.test.js

This file was deleted.

14 changes: 3 additions & 11 deletions services/ui-src/src/hooks/authHooks/userProvider.jsx
Original file line number Diff line number Diff line change
@@ -1,23 +1,15 @@
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { useLocation } from "react-router-dom";
import {
signInWithRedirect,
signOut,
fetchAuthSession,
} from "aws-amplify/auth";
import { UserContext } from "./userContext";
import { AppRoles, IdmRoles } from "../../types";
import { loadUser } from "../../actions/initial";
import { useDispatch } from "react-redux";
import config from "../../config";
import { authenticateWithIDM, getTokens, logoutUser } from "../../util/apiLib";

const cartsProdDomain = "https://mdctcarts.cms.gov";
const tempEndpoint = "https://dt4brcxdimpa0.cloudfront.net";

const authenticateWithIDM = async () => {
await signInWithRedirect({ provider: { custom: "Okta" } });
};

export const UserProvider = ({ children }) => {
const location = useLocation();
const isProduction =
Expand All @@ -32,7 +24,7 @@ export const UserProvider = ({ children }) => {
try {
setUser(null);
localStorage.removeItem("mdctcarts_session_exp");
await signOut();
await logoutUser();
} catch (error) {
console.log("error signing out: ", error); // eslint-disable-line no-console
}
Expand All @@ -47,7 +39,7 @@ export const UserProvider = ({ children }) => {

// Authenticate
try {
const tokens = (await fetchAuthSession()).tokens;
const tokens = await getTokens();
if (!tokens?.idToken) {
throw new Error("Missing tokens auth session.");
}
Expand Down
8 changes: 2 additions & 6 deletions services/ui-src/src/setupTests.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,7 @@ jest.mock("aws-amplify/api", () => ({
}),
})),
del: jest.fn().mockImplementation(() => ({
response: Promise.resolve({
body: {
text: () => Promise.resolve(`{"json":"blob"}`),
},
}),
response: Promise.resolve({}),
})),
}));

Expand All @@ -79,7 +75,7 @@ jest.mock("aws-amplify/auth", () => ({
}),
configure: () => {},
signOut: jest.fn().mockImplementation(() => Promise.resolve()),
federatedSignIn: () => {},
signInWithRedirect: jest.fn(),
}));

jest.mock("aws-amplify/utils", () => ({
Expand Down
Loading
Loading