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(stage): add auth stage #9

Merged
merged 13 commits into from
Jun 10, 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
1 change: 0 additions & 1 deletion src/App.module.css
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
.app {
display: flex;
}

.app-loginBtn {
Expand Down
78 changes: 38 additions & 40 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { useEffect } from 'react'

import AuthContext from '@/contexts/AuthContext'
import { getPKCEStatus } from '@/utils/auth'
import { clearSearchParams, getSearchParams } from '@/utils/route'
import { deleteStateCookie } from '@/utils/stateCookie'
import AuthContext from '@/contexts/AuthContext'
import { AuthStage } from '@/types'

import LoginButton from '@/components/LoginButton'

Expand All @@ -11,72 +13,68 @@ import useGetAccessToken from '@/hooks/useGetAccessToken'

import s from './App.module.css'
import LogoutButton from './components/LogoutButton'
import { getAuthStage } from './utils/authStage'

function App() {
const params = new URLSearchParams(window.location.search)
const state = params.get('state')
const code = params.get('code')


const { state, code } = getSearchParams()
const { codeVerifier } = getPKCEStatus(state)

const {
isLoading, error, tokens,
getATWithAuthCode, getATWithRefreshToken
} = useGetAccessToken()
const authContext = useAuthContextValue(tokens)

const authStage = getAuthStage({
state, code, codeVerifier,
accessToken: authContext.accessToken,
refreshToken: authContext.refreshToken,
})

useEffect(() => {
if (authContext.refreshToken && !authContext.accessToken) {
getATWithRefreshToken(authContext.refreshToken)
} else if (code && codeVerifier) {
getATWithAuthCode(code, codeVerifier)
if (authStage.stage === AuthStage.AFTER_AUTH_CODE) {
deleteStateCookie(authStage.state)
clearSearchParams()
} else if (authStage.stage === AuthStage.BEFORE_REFRESH_TOKEN) {
getATWithRefreshToken(authStage.refreshToken)
} else if (authStage.stage === AuthStage.BEFORE_AUTH_CODE) {
getATWithAuthCode(authStage.state, authStage.code, authStage.codeVerifier)
}
// once on mount only
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])

const justDoneAuthCodeRequest =
state && codeVerifier && tokens?.accessToken && tokens?.refreshToken
useEffect(() => {
if (justDoneAuthCodeRequest) {
deleteStateCookie(state)
window.history.replaceState({}, document.title, '/')
}
}, [justDoneAuthCodeRequest, state])

const status = state && code && codeVerifier ? [
`state: ${state}`,
`code: ${code}`,
`codeVerifier: ${codeVerifier}`
] : []
}, [authStage.stage])

const isLoggedIn = !!authContext.accessToken
const statuses = {
accessToken: authContext.accessToken,
refreshToken: authContext.refreshToken,
state,
code,
codeVerifier,
}
const isLoggedIn = authStage.stage === AuthStage.LOGGED_IN
|| authStage.stage === AuthStage.AFTER_AUTH_CODE

return (
<AuthContext.Provider value={authContext}>
<main className={s['app']}>
{isLoggedIn
? <LogoutButton className={s['app-loginBtn']} />
: <LoginButton className={s['app-loginBtn']} />
{
isLoggedIn ? <LogoutButton className={s['app-loginBtn']} />
: <LoginButton className={s['app-loginBtn']} />
}
<h1>Stage: {authStage.stage}</h1>
<pre>
{!isLoading && <>
<table>
<tbody>
<tr>
<td className='debug-itemName'>accessToken</td>
<td className="debug-longText">{`${authContext.accessToken}`}</td>
</tr>
<tr>
<td className='debug-itemName'>refreshToken</td>
<td className="debug-longText">{`${authContext.refreshToken}`}</td>
</tr>
{Object.entries(statuses).filter(([, v]) => !!v).map(([key, value]) => (
<tr key={key}>
<td className='debug-itemName'>{key}</td>
<td className="debug-longText">{`${value}`}</td>
</tr>
))}
</tbody>
</table>
</>
}
{status && status.map(s => <div key={s}>{s}</div>)}
{error && <div className='debug-error'>{error}</div>}
</pre>
</main>
Expand Down
6 changes: 4 additions & 2 deletions src/components/LogoutButton.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import { deleteRefreshToken } from "@/utils/token"
import { deleteRefreshToken } from "@/utils/refreshToken"
import { useCallback } from "react"

import { reload } from '@/utils/route'

type LogoutButtonProps = {
className?: string
}
const LogoutButton = ({ className }: LogoutButtonProps) => {
const handleLogout = useCallback(() => {
deleteRefreshToken()
window.location.reload()
reload()
}, [])

return (
Expand Down
2 changes: 1 addition & 1 deletion src/hooks/__tests__/useAuthContextValue.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ describe("useAuthContextValue", () => {
refreshToken: "refreshToken"
}))

vi.waitFor(() => {
await vi.waitFor(() => {
expect(result.current.accessToken).toBe("accessToken")
expect(result.current.refreshToken).toBe("refreshToken")
})
Expand Down
156 changes: 118 additions & 38 deletions src/hooks/__tests__/useGetAccessToken.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
import { describe, test, expect, vi } from "vitest"
import { describe, test, expect, vi, afterEach } from "vitest"
import { act, renderHook } from "@testing-library/react"

import useGetAccessToken from "@/hooks/useGetAccessToken"
import { deleteRefreshToken } from "@/utils/refreshToken"
import { deleteStateCookie } from "@/utils/stateCookie"

describe("useGetAccessToken", () => {
test("returns null state", () => {
afterEach(() => {
vi.unstubAllGlobals()
vi.resetAllMocks()
})

test("returns initial state", () => {
const { result } = renderHook(() => useGetAccessToken())
expect(result.current).toEqual({
getATWithAuthCode: expect.any(Function),
Expand All @@ -17,57 +25,129 @@ describe("useGetAccessToken", () => {
})
})

test("returns access tokens", async () => {
vi.mock("@/apis/token", async () => ({
postToken: vi.fn(() => Promise.resolve({
refresh_token: "refresh_token_jwt", access_token: "access_token_jwt"

describe("auth token", () => {
test("returns access tokens", async () => {
const mockResponse = {
access_token: 'access_token_jwt',
refresh_token: 'refresh_token_jwt',
expires_at: 1234567890
}
// FIXME unstable module mocking was replaced by fetch mock
vi.stubGlobal('fetch', () => Promise.resolve({
ok: true,
json: () => Promise.resolve(mockResponse)
}))
}))

const { result } = renderHook(
() => useGetAccessToken()
)
const { result } = renderHook(() => useGetAccessToken())

act(() => {
result.current.getATWithAuthCode("state", "code", "codeVerifier")
})
expect(result.current.isLoading).toBeTruthy()
expect(result.current.error).toBeFalsy()

act(() => {
result.current.getATWithAuthCode("code", "codeVerifier")
await vi.waitFor(() => {
expect(result.current.tokens).toEqual({
accessToken: "access_token_jwt",
refreshToken: "refresh_token_jwt"
})
expect(result.current.isLoading).toBeFalsy()
expect(result.current.error).toBeFalsy()
})
})

expect(result.current.isLoading).toBeTruthy()
expect(result.current.error).toBeFalsy()
test("captures error and delete state cookie", async () => {
// FIXME unstable module mocking was replaced by fetch mock
vi.stubGlobal('fetch', () => Promise.resolve({
ok: false,
status: 400,
statusText: 'Bad Request'
}))
vi.mock('@/utils/stateCookie', () => ({
deleteStateCookie: vi.fn()
}))

const { result } = renderHook(() => useGetAccessToken())

vi.waitFor(() => {
expect(result.current.tokens).toEqual({
accessToken: "access_token_jwt",
refreshToken: "refresh_token_jwt"
act(() => {
result.current.getATWithAuthCode("state", "code", "codeVerifier")
})
expect(result.current.isLoading).toBeFalsy()
expect(result.current.error).toBeFalsy()
})

vi.unmock("@/apis/token")
expect(result.current.isLoading).toBeTruthy()
expect(result.current.error).toBeNull()

await vi.waitFor(() => {
expect(result.current.tokens).toEqual({
accessToken: null,
refreshToken: null
})
expect(result.current.isLoading).toBeFalsy()
expect(result.current.error).toBe("Bad Request")
expect(deleteStateCookie).toHaveBeenCalled()
})
})
})
describe("refresh token", () => {
test("returns access tokens", async () => {
const mockResponse = {
access_token: 'access_token_jwt',
refresh_token: 'refresh_token_jwt',
expires_at: 1234567890
}
// FIXME unstable module mocking was replaced by fetch mock
vi.stubGlobal('fetch', () => Promise.resolve({
ok: true,
json: () => Promise.resolve(mockResponse)
}))

test("captures error", async () => {
vi.mock("@/apis/token", async () => ({
postToken: vi.fn(() => Promise.reject(new Error("error")))
}))
const { result } = renderHook(() => useGetAccessToken())

const { result } = renderHook(() =>
useGetAccessToken()
)
act(() => {
result.current.getATWithAuthCode("state", "code", "codeVerifier")
})
expect(result.current.isLoading).toBeTruthy()
expect(result.current.error).toBeFalsy()

act(() => {
result.current.getATWithAuthCode("code", "codeVerifier")
await vi.waitFor(() => {
expect(result.current.tokens).toEqual({
accessToken: "access_token_jwt",
refreshToken: "refresh_token_jwt"
})
expect(result.current.isLoading).toBeFalsy()
expect(result.current.error).toBeFalsy()
})
})

expect(result.current.isLoading).toBeTruthy()
expect(result.current.error).toBeNull()
test("captures error and delete refresh token", async () => {
// FIXME unstable module mocking was replaced by fetch mock
vi.stubGlobal('fetch', () => Promise.resolve({
ok: false,
status: 400,
statusText: 'Bad Request'
}))
vi.mock('@/utils/refreshToken', () => ({
deleteRefreshToken: vi.fn()
}))

vi.waitFor(() => {
expect(result.current.tokens).toBeNull()
expect(result.current.isLoading).toBeFalsy()
expect(result.current.error).toBe("error")
const { result } = renderHook(() => useGetAccessToken())

act(() => {
result.current.getATWithRefreshToken("mock_refresh_token")
})

expect(result.current.isLoading).toBeTruthy()
expect(result.current.error).toBeNull()

await vi.waitFor(() => {
expect(result.current.tokens).toEqual({
accessToken: null,
refreshToken: null
})
expect(result.current.isLoading).toBeFalsy()
expect(result.current.error).toBe("Bad Request")
expect(deleteRefreshToken).toHaveBeenCalled()
})
})
vi.unmock("@/apis/token")
})
})
3 changes: 2 additions & 1 deletion src/hooks/useAuthContextValue.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { useState, useMemo, useEffect } from 'react'

import { getRefreshToken, setRefreshToken } from '@/utils/token'
import { getRefreshToken, setRefreshToken } from '@/utils/refreshToken'
import { AuthTokens } from '@/types'

const useAuthContextValue = (tokens: AuthTokens) => {
// access token in memory
const [accessToken, setAccessToken] = useState<string | null>(null)

useEffect(() => {
Expand Down
13 changes: 9 additions & 4 deletions src/hooks/useGetAccessToken.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { useCallback, useState } from 'react'

import { postTokenWithAuthCode, postTokenWithRefreshToken } from '@/apis/token'
import { AuthTokens, PostTokenResponse } from '@/types'
import { deleteRefreshToken } from '@/utils/refreshToken'
import { deleteStateCookie } from '@/utils/stateCookie'

const useGetAccessToken = () => {
const [isLoading, setIsLoading] = useState(false)
Expand All @@ -12,6 +14,7 @@ const useGetAccessToken = () => {
const [error, setError] = useState<string | null>(null)

const getATWithAuthCode = useCallback(async (
state: string,
code: string,
codeVerifier: string
) => {
Expand All @@ -24,12 +27,13 @@ const useGetAccessToken = () => {
refreshToken: res.refresh_token
})
})
.catch((err) =>
.catch((err) => {
deleteStateCookie(state)
setError(
err?.message
?? 'getATWithAuthCode - An unknown error occurred'
)
)
})
.finally(() => {
setIsLoading(false)
})
Expand All @@ -46,12 +50,13 @@ const useGetAccessToken = () => {
refreshToken: res.refresh_token
})
})
.catch((err) =>
.catch((err) => {
deleteRefreshToken()
setError(
err?.message
?? 'getATWithRefreshToken - An unknown error occurred'
)
)
})
.finally(() => {
setIsLoading(false)
})
Expand Down
Loading