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

feat: DAH-2987 Reset password api #2461

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
99 changes: 99 additions & 0 deletions app/javascript/__tests__/__util__/accountUtils.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import React from "react"
import UserContext, { ContextProps } from "../../authentication/context/UserContext"
import { User } from "../../authentication/user"

export const mockProfileStub: User = {
uid: "abc123",
email: "[email protected]",
created_at: new Date(),
updated_at: new Date(),
DOB: "1999-01-01",
firstName: "FirstName",
lastName: "LastName",
middleName: "MiddleName",
}

export const setupUserContext = ({
loggedIn,
setUpMockLocation = true,
saveProfileMock = jest.fn(),
mockProfile = mockProfileStub,
}: {
loggedIn: boolean
setUpMockLocation?: boolean
saveProfileMock?: jest.Mock
mockProfile?: ContextProps["profile"]
}) => {
const originalUseContext = React.useContext
const originalLocation = window.location
const mockContextValue: ContextProps = {
profile: loggedIn ? mockProfile : undefined,
signIn: jest.fn(),
signOut: jest.fn(),
timeOut: jest.fn(),
saveProfile: saveProfileMock || jest.fn(),
loading: false,
initialStateLoaded: true,
}

jest.spyOn(React, "useContext").mockImplementation((context) => {
if (context === UserContext) {
return mockContextValue
}
return originalUseContext(context)
})

if (!loggedIn && setUpMockLocation) {
// Allows for a redirect to the Sign In page
// eslint-disable-next-line @typescript-eslint/no-explicit-any
delete (window as any)?.location
;(window as Window).location = {
...originalLocation,
href: "http://dahlia.com",
assign: jest.fn(),
replace: jest.fn(),
reload: jest.fn(),
toString: jest.fn(),
}
}

return originalUseContext
}

export const setupLocationAndRouteMock = () => {
const originalLocation = window.location

const customLocation = {
...originalLocation,
href: "http://dahlia.com",
assign: jest.fn(),
replace: jest.fn(),
reload: jest.fn(),
toString: jest.fn(),
}

Object.defineProperty(window, "location", {
configurable: true,
enumerable: true,
writable: true,
value: customLocation,
})

// Redefine the href setter to resolve relative URLs
Object.defineProperty(window.location, "href", {
configurable: true,
enumerable: true,
set: function (href: string) {
const base = "http://dahlia.com"
try {
const newUrl = new URL(href, base)
this._href = newUrl.href
} catch {
this._href = href
}
},
get: function () {
return this._href || "http://dahlia.com"
},
})
}
16 changes: 16 additions & 0 deletions app/javascript/__tests__/api/authApiService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
updatePassword,
getApplications,
deleteApplication,
resetPassword,
} from "../../api/authApiService"

jest.mock("axios")
Expand Down Expand Up @@ -100,6 +101,21 @@ describe("authApiService", () => {
})
})

describe("resetPassword", () => {
it("calls apiService put", async () => {
const url = "/api/v1/auth/password"
const newPassword = "abc123"
await resetPassword(newPassword)
expect(authenticatedPut).toHaveBeenCalledWith(
url,
expect.objectContaining({
password: newPassword,
password_confirmation: newPassword,
})
)
})
})

describe("updatePassword", () => {
it("calls apiService put", async () => {
const url = "/api/v1/auth/password"
Expand Down
134 changes: 134 additions & 0 deletions app/javascript/__tests__/authentication/context/UserProvider.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
import React, { useContext } from "react"
import { act, render, screen, waitFor } from "@testing-library/react"
import UserProvider from "../../../authentication/context/UserProvider"
import UserContext, { ContextProps } from "../../../authentication/context/UserContext"
import { getProfile, signIn } from "../../../api/authApiService"
import { isTokenValid } from "../../../authentication/token"
import { renderAndLoadAsync } from "../../__util__/renderUtils"
import { mockProfileStub } from "../../__util__/accountUtils"

jest.mock("../../../api/authApiService", () => ({
getProfile: jest.fn(),
signIn: jest.fn(),
}))

jest.mock("../../../authentication/token", () => {
const actualTokenModule = jest.requireActual("../../../authentication/token")
return {
...actualTokenModule,
isTokenValid: jest.fn(),
}
})

const mockGetItem = jest.fn()
const mockSetItem = jest.fn()
const mockRemoveItem = jest.fn()
Object.defineProperty(window, "sessionStorage", {
value: {
getItem: (...args: string[]) => mockGetItem(...args),
setItem: (...args: string[]) => mockSetItem(...args),
removeItem: (...args: string[]) => mockRemoveItem(...args),
},
})

const TestComponent = () => {
const { signIn, signOut, profile, initialStateLoaded } = useContext(UserContext) as ContextProps

return (
<div>
{initialStateLoaded && <p>Initial state loaded</p>}
{profile ? (
<div>
<p>Signed in as {profile.uid}</p>
<button onClick={signOut}>Sign Out</button>
</div>
) : (
<button
onClick={() => {
signIn("[email protected]", "password")
.then(() => {})
.catch(() => {})
}}
>
Sign In
</button>
)}
</div>
)
}

describe("UserProvider", () => {
beforeEach(() => {
jest.clearAllMocks()
})

it("should load profile on mount if access token is available", async () => {
;(getProfile as jest.Mock).mockResolvedValue(mockProfileStub)
;(isTokenValid as jest.Mock).mockReturnValue(true)

render(
<UserProvider>
<TestComponent />
</UserProvider>
)

await waitFor(() => expect(screen.getByText("Signed in as abc123")).not.toBeNull())
})

it("should sign in and sign out a user", async () => {
;(getProfile as jest.Mock).mockRejectedValue(undefined)
;(signIn as jest.Mock).mockResolvedValue(mockProfileStub)
;(isTokenValid as jest.Mock).mockReturnValueOnce(false).mockReturnValueOnce(true)

await renderAndLoadAsync(
<UserProvider>
<TestComponent />
</UserProvider>
)

act(() => {
screen.getByText("Sign In").click()
})

await waitFor(() => expect(screen.getByText("Signed in as abc123")).not.toBeNull())

act(() => {
screen.getByText("Sign Out").click()
})

await waitFor(() => expect(screen.getByText("Sign In")).not.toBeNull())
})

it("should handle token invalidation on initial load", async () => {
;(isTokenValid as jest.Mock).mockReturnValue(false)
;(getProfile as jest.Mock).mockResolvedValue(mockProfileStub)

await renderAndLoadAsync(
<UserProvider>
<TestComponent />
</UserProvider>
)

expect(screen.getByText("Initial state loaded")).not.toBeNull()
})

it("should handle temporary auth params from URL", async () => {
Object.defineProperty(window, "location", {
writable: true,
value: {
href: "http://localhost:3000/reset-password?access-token=DDDDD&client=CCCCC&client_id=BBBBB&config=default&expiry=100&reset_password=true&token=AAAAAA&uid=test%40test.com",
},
})
;(isTokenValid as jest.Mock).mockReturnValue(true)
;(getProfile as jest.Mock).mockResolvedValue(mockProfileStub)

await renderAndLoadAsync(
<UserProvider>
<TestComponent />
</UserProvider>
)

await waitFor(() => expect(screen.getByText("Signed in as abc123")).not.toBeNull())
expect(getProfile).toHaveBeenCalled()
})
})
37 changes: 37 additions & 0 deletions app/javascript/__tests__/authentication/token.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import {
clearHeaders,
clearHeadersTimeOut,
clearHeadersConnectionIssue,
getTemporaryAuthParamsFromUrl,
setAuthHeadersFromUrl,
} from "../../authentication/token"

const ACCESS_TOKEN_LOCAL_STORAGE_KEY = "auth_headers"
Expand Down Expand Up @@ -49,4 +51,39 @@ describe("token.ts", () => {
"There was a connection issue, so we signed you out. We do this for your security. Sign in again to continue."
)
})
it("getTemporaryAuthParamsFromURL", () => {
// Mock the window.location.href
Object.defineProperty(window, "location", {
writable: true,
value: {
href: "http://localhost:3000/reset-password?access-token=DDDDD&client=CCCCC&client_id=BBBBB&config=default&expiry=100&reset_password=true&token=AAAAAA&uid=test%40test.com",
},
})

const expectedParams = {
expiry: "100",
accessToken: "DDDDD",
client: "CCCCC",
uid: "[email protected]",
tokenType: "Bearer",
reset_password: "true",
}

const result = getTemporaryAuthParamsFromUrl()
expect(result).toEqual(expectedParams)

const setAuthReturn = setAuthHeadersFromUrl(result)

expect(setAuthReturn).toEqual(true)
expect(mockSetItem).toHaveBeenCalledWith(
ACCESS_TOKEN_LOCAL_STORAGE_KEY,
JSON.stringify({
expiry: "100",
"access-token": "DDDDD",
client: "CCCCC",
uid: "[email protected]",
"token-type": "Bearer",
})
)
})
})
Loading
Loading