From 4d247131086d5f6f10d0f7633c53709aaa9b394d Mon Sep 17 00:00:00 2001 From: Bangbay Siboliban Date: Mon, 21 Oct 2024 17:05:24 -0400 Subject: [PATCH] Refactor amplify methods to single file --- .../components/logins/LoginCognito.test.tsx | 13 +-- .../src/components/logins/LoginCognito.tsx | 6 +- .../src/utils/api/request/request.test.ts | 108 ++++++++++++++++++ .../ui-src/src/utils/api/request/request.ts | 106 +++++++++++++++++ .../utils/api/requestMethods/banner.test.ts | 37 +++--- .../src/utils/api/requestMethods/banner.ts | 38 +----- .../requestMethods/getRequestHeaders.test.ts | 32 ------ .../api/requestMethods/getRequestHeaders.ts | 13 --- .../api/requestMethods/getTemplateUrl.test.ts | 9 +- .../api/requestMethods/getTemplateUrl.ts | 15 +-- .../utils/api/requestMethods/report.test.ts | 58 ++++++---- .../src/utils/api/requestMethods/report.ts | 84 ++------------ .../src/utils/auth/UserProvider.test.tsx | 14 ++- .../ui-src/src/utils/auth/UserProvider.tsx | 14 ++- .../ui-src/src/utils/auth/authLifecycle.tsx | 6 +- services/ui-src/src/utils/index.ts | 2 +- 16 files changed, 322 insertions(+), 233 deletions(-) create mode 100644 services/ui-src/src/utils/api/request/request.test.ts create mode 100644 services/ui-src/src/utils/api/request/request.ts delete mode 100644 services/ui-src/src/utils/api/requestMethods/getRequestHeaders.test.ts delete mode 100644 services/ui-src/src/utils/api/requestMethods/getRequestHeaders.ts diff --git a/services/ui-src/src/components/logins/LoginCognito.test.tsx b/services/ui-src/src/components/logins/LoginCognito.test.tsx index 839583cd2..25f50c288 100644 --- a/services/ui-src/src/components/logins/LoginCognito.test.tsx +++ b/services/ui-src/src/components/logins/LoginCognito.test.tsx @@ -7,8 +7,10 @@ import { LoginCognito } from "components"; import { RouterWrappedComponent } from "utils/testing/setupJest"; const mockSignIn = jest.fn(); -jest.mock("aws-amplify/auth", () => ({ - signIn: (credentials: any) => mockSignIn(credentials), + +jest.mock("utils", () => ({ + loginUser: (username: string, password: string) => + mockSignIn(username, password), })); const mockUseNavigate = jest.fn(); @@ -30,12 +32,9 @@ describe("Test LoginCognito", () => { const passwordInput = screen.getByLabelText("Password"); const submitButton = screen.getByRole("button"); await userEvent.type(emailInput, "email@address.com"); - await userEvent.type(passwordInput, "p@$$w0rd"); //pragma: allowlist secret + await userEvent.type(passwordInput, "test"); await userEvent.click(submitButton); - expect(mockSignIn).toHaveBeenCalledWith({ - username: "email@address.com", - password: "p@$$w0rd", //pragma: allowlist secret - }); + expect(mockSignIn).toHaveBeenCalledWith("email@address.com", "test"); expect(mockUseNavigate).toHaveBeenCalledWith("/"); }); }); diff --git a/services/ui-src/src/components/logins/LoginCognito.tsx b/services/ui-src/src/components/logins/LoginCognito.tsx index 187d954d4..20459d093 100644 --- a/services/ui-src/src/components/logins/LoginCognito.tsx +++ b/services/ui-src/src/components/logins/LoginCognito.tsx @@ -1,10 +1,10 @@ import { useState } from "react"; import { useNavigate } from "react-router-dom"; -import { signIn } from "aws-amplify/auth"; // components import { Box, Button, Heading, Input, Stack, Text } from "@chakra-ui/react"; import { ErrorAlert } from "components"; import { ErrorVerbiage } from "types"; +import { loginUser } from "utils"; const useFormFields = (initialState: any) => { const [fields, setValues] = useState(initialState); @@ -32,8 +32,8 @@ export const LoginCognito = () => { const handleLogin = async (event: any) => { event.preventDefault(); try { - await signIn({ username: fields.email, password: fields.password }); - navigate(`/`); + await loginUser(fields.email, fields.password); + navigate("/"); } catch (error: any) { setError(error.message); } diff --git a/services/ui-src/src/utils/api/request/request.test.ts b/services/ui-src/src/utils/api/request/request.test.ts new file mode 100644 index 000000000..822322923 --- /dev/null +++ b/services/ui-src/src/utils/api/request/request.test.ts @@ -0,0 +1,108 @@ +import { + deleteApi, + getApi, + getRequestHeaders, + getTokens, + loginUser, + logoutUser, + postApi, + putApi, + refreshSession, +} from "utils"; + +const mockResponse = { response: { body: { json: () => jest.fn() } } }; +const mockDelete = jest.fn().mockImplementation(() => mockResponse); +const mockGet = jest.fn().mockImplementation(() => mockResponse); +const mockPost = jest.fn().mockImplementation(() => mockResponse); +const mockPut = jest.fn().mockImplementation(() => mockResponse); +const mockSession = jest.fn(); +const mockSignIn = jest.fn(); +const mockSignOut = jest.fn(); + +jest.mock("aws-amplify/api", () => ({ + del: () => mockDelete(), + get: () => mockGet(), + post: () => mockPost(), + put: () => mockPut(), +})); + +jest.mock("aws-amplify/auth", () => ({ + fetchAuthSession: () => mockSession(), + signIn: () => mockSignIn(), + signOut: () => mockSignOut(), +})); + +describe("request", () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + describe("getRequestHeaders()", () => { + test("Logs error to console if Auth throws error", async () => { + jest.spyOn(console, "log").mockImplementation(jest.fn()); + const spy = jest.spyOn(console, "log"); + + mockSession.mockImplementation(() => { + throw new Error(); + }); + + await getRequestHeaders(); + + expect(spy).toHaveBeenCalled(); + }); + + test("Returns token if current idToken exists", async () => { + mockSession.mockResolvedValue({ + tokens: { + idToken: { + toString: () => "stringToken", + }, + }, + }); + + const result = await getRequestHeaders(); + + expect(result).toStrictEqual({ "x-api-key": "stringToken" }); + }); + }); + + test("getTokens()", async () => { + await getTokens(); + expect(mockSession).toHaveBeenCalledTimes(1); + }); + + test("loginUser()", async () => { + await loginUser("email@address.com", "test"); + expect(mockSignIn).toHaveBeenCalledTimes(1); + }); + + test("logoutUser()", async () => { + await logoutUser(); + expect(mockSignOut).toHaveBeenCalledTimes(1); + }); + + test("refreshSession()", async () => { + await refreshSession(); + expect(mockSession).toHaveBeenCalledTimes(1); + }); + + test("deleteApi()", async () => { + await deleteApi("/"); + expect(mockDelete).toHaveBeenCalledTimes(1); + }); + + test("getApi()", async () => { + await getApi("/"); + expect(mockGet).toHaveBeenCalledTimes(1); + }); + + test("postApi()", async () => { + await postApi("/", { body: "" }); + expect(mockPost).toHaveBeenCalledTimes(1); + }); + + test("putApi()", async () => { + await putApi("/"); + expect(mockPut).toHaveBeenCalledTimes(1); + }); +}); diff --git a/services/ui-src/src/utils/api/request/request.ts b/services/ui-src/src/utils/api/request/request.ts new file mode 100644 index 000000000..8fc3bab1e --- /dev/null +++ b/services/ui-src/src/utils/api/request/request.ts @@ -0,0 +1,106 @@ +import { del, get, post, put } from "aws-amplify/api"; +import { + AuthTokens, + fetchAuthSession, + signIn, + signOut, +} from "aws-amplify/auth"; + +const apiName = "mcr"; + +interface RequestHeaders { + "x-api-key": string | undefined; +} + +export const getRequestHeaders = async (): Promise< + RequestHeaders | undefined +> => { + try { + const tokens = await getTokens(); + const headers = { + "x-api-key": tokens?.idToken?.toString(), + }; + + return headers; + } catch (error) { + console.log(error); //eslint-disable-line no-console + return; + } +}; + +export const getTokens = async (): Promise => { + return (await fetchAuthSession()).tokens; +}; + +export const loginUser = async ( + username: string, + password: string +): Promise => { + await signIn({ username, password }); +}; + +export const logoutUser = async (): Promise => { + await signOut(); +}; + +export const refreshSession = async (): Promise => { + await fetchAuthSession({ forceRefresh: true }); +}; + +export const deleteApi = async (path: string, opts?: any): Promise => { + const requestHeaders = await getRequestHeaders(); + const options = { + headers: { ...requestHeaders }, + ...opts, + }; + await del({ + apiName, + path, + options, + }).response; +}; + +export const getApi = async (path: string, opts?: any): Promise => { + const requestHeaders = await getRequestHeaders(); + const options = { + headers: { ...requestHeaders }, + ...opts, + }; + const { body } = await get({ + apiName, + path, + options, + }).response; + + return (await body.json()) as T; +}; + +export const postApi = async (path: string, opts?: any): Promise => { + const requestHeaders = await getRequestHeaders(); + const options = { + headers: { ...requestHeaders }, + ...opts, + }; + const { body } = await post({ + apiName, + path, + options, + }).response; + + return (await body.json()) as T; +}; + +export const putApi = async (path: string, opts?: any): Promise => { + const requestHeaders = await getRequestHeaders(); + const options = { + headers: { ...requestHeaders }, + ...opts, + }; + const { body } = await put({ + apiName, + path, + options, + }).response; + + return (await body.json()) as T; +}; diff --git a/services/ui-src/src/utils/api/requestMethods/banner.test.ts b/services/ui-src/src/utils/api/requestMethods/banner.test.ts index 398fb4f9f..9fee1859d 100644 --- a/services/ui-src/src/utils/api/requestMethods/banner.test.ts +++ b/services/ui-src/src/utils/api/requestMethods/banner.test.ts @@ -3,33 +3,38 @@ import { getBanner, writeBanner, deleteBanner } from "./banner"; import { bannerId } from "../../../constants"; import { mockBannerData } from "utils/testing/setupJest"; -const mockAmplifyApi = require("aws-amplify/api"); +const mockDelete = jest.fn(); +const mockGet = jest.fn(); +const mockPost = jest.fn(); +const mockTimeout = jest.fn(); -jest.mock("utils/auth/authLifecycle", () => ({ - updateTimeout: jest.fn(), - initAuthManager: jest.fn(), - refreshCredentials: jest.fn(), +jest.mock("utils", () => ({ + deleteApi: () => mockDelete(), + getApi: () => mockGet(), + postApi: () => mockPost(), + updateTimeout: () => mockTimeout(), })); -describe("Test banner methods", () => { +describe("banner", () => { beforeEach(() => { jest.clearAllMocks(); }); - test("getBanner", async () => { - const apiSpy = jest.spyOn(mockAmplifyApi, "get"); - expect(await getBanner(bannerId)).toBeTruthy(); - expect(apiSpy).toHaveBeenCalledTimes(1); + + test("getBanner()", async () => { + await getBanner(bannerId); + expect(mockGet).toHaveBeenCalledTimes(1); + expect(mockTimeout).toHaveBeenCalledTimes(1); }); - test("postBanner", async () => { - const apiSpy = jest.spyOn(mockAmplifyApi, "post"); + test("postBanner()", async () => { await writeBanner(mockBannerData); - expect(apiSpy).toHaveBeenCalledTimes(1); + expect(mockPost).toHaveBeenCalledTimes(1); + expect(mockTimeout).toHaveBeenCalledTimes(1); }); - test("delBanner", async () => { - const apiSpy = jest.spyOn(mockAmplifyApi, "del"); + test("deleteBanner()", async () => { await deleteBanner(bannerId); - expect(apiSpy).toHaveBeenCalledTimes(1); + expect(mockDelete).toHaveBeenCalledTimes(1); + expect(mockTimeout).toHaveBeenCalledTimes(1); }); }); diff --git a/services/ui-src/src/utils/api/requestMethods/banner.ts b/services/ui-src/src/utils/api/requestMethods/banner.ts index 02558bb34..8353a13d2 100644 --- a/services/ui-src/src/utils/api/requestMethods/banner.ts +++ b/services/ui-src/src/utils/api/requestMethods/banner.ts @@ -1,55 +1,25 @@ -import { get, post, del } from "aws-amplify/api"; -import { getRequestHeaders } from "./getRequestHeaders"; import { AdminBannerData } from "types/banners"; -import { updateTimeout } from "utils"; - -const apiName = "mcr"; +import { deleteApi, getApi, postApi, updateTimeout } from "utils"; async function getBanner(bannerKey: string) { - const requestHeaders = await getRequestHeaders(); - const options = { - headers: { ...requestHeaders }, - }; const path = `/banners/${bannerKey}`; - updateTimeout(); - const { body } = await get({ - apiName, - path, - options, - }).response; - return (await body.json()) as unknown as { Item: AdminBannerData }; + return getApi(path); } async function writeBanner(bannerData: AdminBannerData) { - const requestHeaders = await getRequestHeaders(); const options = { - headers: { ...requestHeaders }, body: bannerData, }; const path = `/banners/${bannerData.key}`; - updateTimeout(); - await post({ - apiName, - path, - options, - }).response; + return postApi(path, options); } async function deleteBanner(bannerKey: string) { - const requestHeaders = await getRequestHeaders(); - const options = { - headers: { ...requestHeaders }, - }; const path = `/banners/${bannerKey}`; - updateTimeout(); - await del({ - apiName, - path, - options, - }).response; + return deleteApi(path); } export { getBanner, writeBanner, deleteBanner }; diff --git a/services/ui-src/src/utils/api/requestMethods/getRequestHeaders.test.ts b/services/ui-src/src/utils/api/requestMethods/getRequestHeaders.test.ts deleted file mode 100644 index 9918f6dae..000000000 --- a/services/ui-src/src/utils/api/requestMethods/getRequestHeaders.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { getRequestHeaders } from "./getRequestHeaders"; - -const mockAmplify = require("aws-amplify/auth"); - -describe("Test getRequestHeaders error handling", () => { - it("Logs error to console if Auth throws error", async () => { - jest.spyOn(console, "log").mockImplementation(jest.fn()); - const spy = jest.spyOn(console, "log"); - - mockAmplify.fetchAuthSession = jest.fn().mockImplementation(() => { - throw new Error(); - }); - - await getRequestHeaders(); - - await expect(spy).toHaveBeenCalled(); - }); - - it("Returns token if current idToken exists", async () => { - mockAmplify.fetchAuthSession = jest.fn().mockResolvedValue({ - tokens: { - idToken: { - toString: () => "stringToken", - }, - }, - }); - - const result = await getRequestHeaders(); - - expect(result).toStrictEqual({ "x-api-key": "stringToken" }); - }); -}); diff --git a/services/ui-src/src/utils/api/requestMethods/getRequestHeaders.ts b/services/ui-src/src/utils/api/requestMethods/getRequestHeaders.ts deleted file mode 100644 index 0149cee6c..000000000 --- a/services/ui-src/src/utils/api/requestMethods/getRequestHeaders.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { fetchAuthSession } from "aws-amplify/auth"; - -export const getRequestHeaders = async (): Promise => { - try { - const { idToken } = (await fetchAuthSession()).tokens ?? {}; - const headers = { - "x-api-key": idToken?.toString(), - }; - return headers; - } catch (error) { - console.log(error); //eslint-disable-line no-console - } -}; diff --git a/services/ui-src/src/utils/api/requestMethods/getTemplateUrl.test.ts b/services/ui-src/src/utils/api/requestMethods/getTemplateUrl.test.ts index a58373423..b2f56928f 100644 --- a/services/ui-src/src/utils/api/requestMethods/getTemplateUrl.test.ts +++ b/services/ui-src/src/utils/api/requestMethods/getTemplateUrl.test.ts @@ -2,12 +2,15 @@ import { getSignedTemplateUrl } from "./getTemplateUrl"; const testTemplateName = "TestName"; -const mockAmplifyApi = require("aws-amplify/api"); +const mockGet = jest.fn(); + +jest.mock("utils", () => ({ + getApi: () => mockGet(), +})); describe("Test template methods", () => { test("getSignedTemplateUrl", async () => { - const apiSpy = jest.spyOn(mockAmplifyApi, "get"); await getSignedTemplateUrl(testTemplateName); - expect(apiSpy).toHaveBeenCalledTimes(1); + expect(mockGet).toHaveBeenCalledTimes(1); }); }); diff --git a/services/ui-src/src/utils/api/requestMethods/getTemplateUrl.ts b/services/ui-src/src/utils/api/requestMethods/getTemplateUrl.ts index dafc75f5b..320783b04 100644 --- a/services/ui-src/src/utils/api/requestMethods/getTemplateUrl.ts +++ b/services/ui-src/src/utils/api/requestMethods/getTemplateUrl.ts @@ -1,16 +1,5 @@ -import { get } from "aws-amplify/api"; -import { getRequestHeaders } from "./getRequestHeaders"; +import { getApi } from "utils"; export async function getSignedTemplateUrl(templateName: string) { - const requestHeaders = await getRequestHeaders(); - const options = { - headers: { ...requestHeaders }, - }; - - const { body } = await get({ - apiName: "mcr", - path: `/templates/${templateName}`, - options, - }).response; - return (await body.json()) as string; + return getApi(`/templates/${templateName}`); } diff --git a/services/ui-src/src/utils/api/requestMethods/report.test.ts b/services/ui-src/src/utils/api/requestMethods/report.test.ts index 0693d333d..1b370c2f2 100644 --- a/services/ui-src/src/utils/api/requestMethods/report.test.ts +++ b/services/ui-src/src/utils/api/requestMethods/report.test.ts @@ -11,53 +11,67 @@ import { import { mockReportKeys, mockMcparReport } from "utils/testing/setupJest"; import { initAuthManager } from "utils/auth/authLifecycle"; -const mockAmplifyApi = require("aws-amplify/api"); +const mockDelete = jest.fn(); +const mockGet = jest.fn(); +const mockPost = jest.fn(); +const mockPut = jest.fn(); +const mockTimeout = jest.fn(); -describe("Test report status methods", () => { +jest.mock("utils", () => ({ + deleteApi: () => mockDelete(), + getApi: () => mockGet(), + postApi: () => mockPost(), + putApi: () => mockPut(), + updateTimeout: () => mockTimeout(), +})); + +describe("report", () => { beforeEach(() => { jest.useFakeTimers(); initAuthManager(); jest.runAllTimers(); jest.clearAllMocks(); }); - test("archiveReport", async () => { - const apiSpy = jest.spyOn(mockAmplifyApi, "put"); + + test("archiveReport()", async () => { await archiveReport(mockReportKeys); - expect(apiSpy).toHaveBeenCalledTimes(1); + expect(mockPut).toHaveBeenCalledTimes(1); + expect(mockTimeout).toHaveBeenCalledTimes(1); }); - test("getReport", async () => { - const apiSpy = jest.spyOn(mockAmplifyApi, "get"); + test("getReport()", async () => { await getReport(mockReportKeys); - expect(apiSpy).toHaveBeenCalledTimes(1); + expect(mockGet).toHaveBeenCalledTimes(1); + expect(mockTimeout).toHaveBeenCalledTimes(1); }); - test("getReportsByState", async () => { - const apiSpy = jest.spyOn(mockAmplifyApi, "get"); + test("getReportsByState()", async () => { await getReportsByState("MCPAR", "AB"); - expect(apiSpy).toHaveBeenCalledTimes(1); + expect(mockGet).toHaveBeenCalledTimes(1); + expect(mockTimeout).toHaveBeenCalledTimes(1); }); - test("postReport", async () => { - const apiSpy = jest.spyOn(mockAmplifyApi, "post"); + test("postReport()", async () => { await postReport("MCPAR", "AB", mockMcparReport); - expect(apiSpy).toHaveBeenCalledTimes(1); + expect(mockPost).toHaveBeenCalledTimes(1); + expect(mockTimeout).toHaveBeenCalledTimes(1); }); - test("putReport", async () => { - const apiSpy = jest.spyOn(mockAmplifyApi, "put"); + test("putReport()", async () => { await putReport(mockReportKeys, mockMcparReport); - expect(apiSpy).toHaveBeenCalledTimes(1); + expect(mockPut).toHaveBeenCalledTimes(1); + expect(mockTimeout).toHaveBeenCalledTimes(1); }); - test("releaseReport", async () => { - const apiSpy = jest.spyOn(mockAmplifyApi, "put"); + + test("releaseReport()", async () => { await releaseReport(mockReportKeys); - expect(apiSpy).toHaveBeenCalledTimes(1); + expect(mockPut).toHaveBeenCalledTimes(1); + expect(mockTimeout).toHaveBeenCalledTimes(1); }); test("submitReport", async () => { - const apiSpy = jest.spyOn(mockAmplifyApi, "post"); await submitReport(mockReportKeys); - expect(apiSpy).toHaveBeenCalledTimes(1); + expect(mockPost).toHaveBeenCalledTimes(1); + expect(mockTimeout).toHaveBeenCalledTimes(1); }); }); diff --git a/services/ui-src/src/utils/api/requestMethods/report.ts b/services/ui-src/src/utils/api/requestMethods/report.ts index b7b7a03d0..50f0a0a80 100644 --- a/services/ui-src/src/utils/api/requestMethods/report.ts +++ b/services/ui-src/src/utils/api/requestMethods/report.ts @@ -1,90 +1,38 @@ -import { get, post, put } from "aws-amplify/api"; import { ReportKeys, ReportShape } from "types"; -import { getRequestHeaders } from "./getRequestHeaders"; -import { updateTimeout } from "utils"; - -const apiName = "mcr"; +import { getApi, postApi, putApi, updateTimeout } from "utils"; async function archiveReport(reportKeys: ReportKeys) { - const requestHeaders = await getRequestHeaders(); - const options = { - headers: { ...requestHeaders }, - }; const { reportType, state, id } = reportKeys; const path = `/reports/archive/${reportType}/${state}/${id}`; - updateTimeout(); - await put({ - apiName, - path, - options, - }).response; + return putApi(path); } async function releaseReport(reportKeys: ReportKeys) { - const requestHeaders = await getRequestHeaders(); - const options = { - headers: { ...requestHeaders }, - }; const { reportType, state, id } = reportKeys; const path = `/reports/release/${reportType}/${state}/${id}`; - updateTimeout(); - await put({ - apiName, - path, - options, - }).response; + return putApi(path); } async function submitReport(reportKeys: ReportKeys) { - const requestHeaders = await getRequestHeaders(); - const options = { - headers: { ...requestHeaders }, - }; const { reportType, state, id } = reportKeys; const path = `/reports/submit/${reportType}/${state}/${id}`; - updateTimeout(); - const { body } = await post({ - apiName, - path, - options, - }).response; - return (await body.json()) as unknown as ReportShape; + return postApi(path); } async function getReport(reportKeys: ReportKeys) { - const requestHeaders = await getRequestHeaders(); - const options = { - headers: { ...requestHeaders }, - }; const { reportType, state, id } = reportKeys; const path = `/reports/${reportType}/${state}/${id}`; - updateTimeout(); - const { body } = await get({ - apiName, - path, - options, - }).response; - return (await body.json()) as unknown as ReportShape; + return getApi(path); } async function getReportsByState(reportType: string, state: string) { - const requestHeaders = await getRequestHeaders(); - const options = { - headers: { ...requestHeaders }, - }; const path = `/reports/${reportType}/${state}`; - updateTimeout(); - const { body } = await get({ - apiName, - path, - options, - }).response; - return (await body.json()) as unknown as ReportShape[]; + return getApi(path); } async function postReport( @@ -92,38 +40,22 @@ async function postReport( state: string, report: ReportShape ) { - const requestHeaders = await getRequestHeaders(); const options: any = { - headers: { ...requestHeaders }, body: { ...report }, }; const path = `/reports/${reportType}/${state}`; - updateTimeout(); - const { body } = await post({ - apiName, - path, - options, - }).response; - return (await body.json()) as unknown as ReportShape; + return postApi(path, options); } async function putReport(reportKeys: ReportKeys, report: ReportShape) { - const requestHeaders = await getRequestHeaders(); const options: any = { - headers: { ...requestHeaders }, body: { ...report }, }; const { reportType, state, id } = reportKeys; const path = `/reports/${reportType}/${state}/${id}`; - updateTimeout(); - const { body } = await put({ - apiName, - path, - options, - }).response; - return (await body.json()) as unknown as ReportShape; + return putApi(path, options); } export { diff --git a/services/ui-src/src/utils/auth/UserProvider.test.tsx b/services/ui-src/src/utils/auth/UserProvider.test.tsx index fb3b1cbef..2057f3b3a 100644 --- a/services/ui-src/src/utils/auth/UserProvider.test.tsx +++ b/services/ui-src/src/utils/auth/UserProvider.test.tsx @@ -69,10 +69,12 @@ const setWindowOrigin = (windowOrigin: string) => { }; const breakCheckAuthState = async () => { - const mockAmplify = require("aws-amplify/auth"); - mockAmplify.fetchAuthSession = jest.fn().mockImplementation(() => { - throw new Error(); - }); + jest.mock("utils", () => ({ + refeshTokens: () => + jest.fn().mockImplementation(() => { + throw new Error(); + }), + })); }; // TESTS @@ -119,7 +121,7 @@ describe("", () => { setWindowOrigin("mdctmcr.cms.gov"); await breakCheckAuthState(); await act(async () => { - await render(testComponent); + render(testComponent); }); expect(window.location.origin).toContain("mdctmcr.cms.gov"); expect(screen.getByTestId("testdiv")).toHaveTextContent("User Test"); @@ -132,7 +134,7 @@ describe("", () => { setWindowOrigin("wherever"); await breakCheckAuthState(); await act(async () => { - await render(testComponent); + render(testComponent); }); expect(window.location.origin).toContain("wherever"); const showLocalLogins = screen.getByTestId("show-local-logins"); diff --git a/services/ui-src/src/utils/auth/UserProvider.tsx b/services/ui-src/src/utils/auth/UserProvider.tsx index 17bd096e4..d676fe379 100644 --- a/services/ui-src/src/utils/auth/UserProvider.tsx +++ b/services/ui-src/src/utils/auth/UserProvider.tsx @@ -6,10 +6,16 @@ import { useMemo, } from "react"; import { useLocation } from "react-router-dom"; -import { fetchAuthSession, signOut } from "aws-amplify/auth"; import config from "config"; // utils -import { initAuthManager, updateTimeout, getExpiration, useStore } from "utils"; +import { + getExpiration, + getTokens, + initAuthManager, + logoutUser, + updateTimeout, + useStore, +} from "utils"; import { PRODUCTION_HOST_DOMAIN } from "../../constants"; // types import { MCRUser, UserContextShape, UserRoles } from "types/users"; @@ -49,7 +55,7 @@ export const UserProvider = ({ children }: Props) => { try { setUser(undefined); clearSelectedReportCache(); - await signOut(); + await logoutUser(); localStorage.clear(); } catch (error) { console.log(error); // eslint-disable-line no-console @@ -65,7 +71,7 @@ export const UserProvider = ({ children }: Props) => { } try { - const tokens = (await fetchAuthSession()).tokens; + const tokens = await getTokens(); if (!tokens?.idToken) { throw new Error("Missing tokens auth session."); } diff --git a/services/ui-src/src/utils/auth/authLifecycle.tsx b/services/ui-src/src/utils/auth/authLifecycle.tsx index 7cfcb88c0..9cf131f74 100644 --- a/services/ui-src/src/utils/auth/authLifecycle.tsx +++ b/services/ui-src/src/utils/auth/authLifecycle.tsx @@ -1,7 +1,7 @@ import { Hub } from "aws-amplify/utils"; -import { fetchAuthSession, signOut } from "aws-amplify/auth"; import { add } from "date-fns"; import { IDLE_WINDOW } from "../../constants"; +import { logoutUser, refreshSession } from "utils"; let authManager: AuthManager; @@ -19,7 +19,7 @@ class AuthManager { expiration && new Date(expiration).valueOf() < Date.now().valueOf(); if (isExpired) { localStorage.removeItem("mdctmcr_session_exp"); - signOut().then(() => { + logoutUser().then(() => { window.location.href = "/"; }); } @@ -48,7 +48,7 @@ class AuthManager { * Manual refresh of credentials paired with an instant timer clear */ refreshCredentials = async () => { - await fetchAuthSession({ forceRefresh: true }); // Force a token refresh + await refreshSession(); // Force a token refresh this.setTimer(); }; diff --git a/services/ui-src/src/utils/index.ts b/services/ui-src/src/utils/index.ts index 6c293bb54..f8122f0c6 100644 --- a/services/ui-src/src/utils/index.ts +++ b/services/ui-src/src/utils/index.ts @@ -1,7 +1,7 @@ // api export * from "./api/providers/ApiProvider"; +export * from "./api/request/request"; export * from "./api/requestMethods/banner"; -export * from "./api/requestMethods/getRequestHeaders"; export * from "./api/requestMethods/getTemplateUrl"; export * from "./api/requestMethods/report"; // auth