-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: extract AuthProvider from AuthContext and add tests
- Loading branch information
Showing
7 changed files
with
93 additions
and
58 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,66 +1,12 @@ | ||
import { createContext, useState, useEffect, useMemo } from "react"; | ||
import { IdToken, useAuth0, User } from "@auth0/auth0-react"; | ||
import { jwtDecode } from "jwt-decode"; | ||
|
||
interface DecodedToken { | ||
exp: number; | ||
iat: number; | ||
iss: string; | ||
sub: string; | ||
aud: string; | ||
} | ||
import { createContext } from "react"; | ||
import { User } from "@auth0/auth0-react"; | ||
|
||
interface AuthContextProps { | ||
token: string | null; | ||
user: User | undefined; | ||
} | ||
|
||
interface AuthProviderProps { | ||
children: React.ReactNode; | ||
} | ||
|
||
export const AuthContext = createContext<AuthContextProps>({ | ||
token: null, | ||
user: undefined, | ||
}); | ||
|
||
const refreshToken = ( | ||
getIdTokenClaims: () => Promise<IdToken | undefined>, | ||
setToken: (token: string | null) => void | ||
) => { | ||
getIdTokenClaims().then((claims) => { | ||
if (claims) { | ||
const idToken = claims.__raw; // The raw id_token | ||
localStorage.setItem("auth0.token", idToken); | ||
setToken(idToken); | ||
|
||
try { | ||
const decodedToken: DecodedToken = jwtDecode(idToken); | ||
const expiryTime = decodedToken.exp * 1000; // Convert to milliseconds | ||
const timeoutDuration = expiryTime - Date.now() - 60 * 1000; // Refresh 1 minute before expiry | ||
|
||
setTimeout( | ||
() => refreshToken(getIdTokenClaims, setToken), | ||
timeoutDuration | ||
); | ||
} catch (error) { | ||
console.error("Invalid token", error); | ||
} | ||
} | ||
}); | ||
}; | ||
|
||
export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => { | ||
const { user, getIdTokenClaims } = useAuth0(); | ||
const [token, setToken] = useState<string | null>(null); | ||
|
||
useEffect(() => { | ||
if (user && getIdTokenClaims) { | ||
refreshToken(getIdTokenClaims, setToken); | ||
} | ||
}, [user, getIdTokenClaims]); | ||
|
||
const value = useMemo(() => ({ token, user }), [token, user]); | ||
|
||
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
import { render, act, screen } from "@testing-library/react"; | ||
import { AuthProvider } from "./AuthProvider"; | ||
import { useAuth0 } from "@auth0/auth0-react"; | ||
import { vi } from "vitest"; | ||
|
||
vi.mock("@auth0/auth0-react", () => ({ | ||
useAuth0: vi.fn().mockReturnValue({ | ||
user: { name: "Test User" }, | ||
getIdTokenClaims: vi.fn().mockResolvedValue({ | ||
__raw: | ||
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c", | ||
}), | ||
}), | ||
})); | ||
|
||
describe("AuthProvider", () => { | ||
it("provides auth context", async () => { | ||
await act(async () => { | ||
render( | ||
<AuthProvider> | ||
<div>Test</div> | ||
</AuthProvider> | ||
); | ||
}); | ||
|
||
expect(screen.getByText("Test")).toBeInTheDocument(); | ||
expect(useAuth0().getIdTokenClaims).toHaveBeenCalled(); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
import { useState, useEffect, useMemo } from "react"; | ||
import { IdToken, useAuth0 } from "@auth0/auth0-react"; | ||
import { jwtDecode } from "jwt-decode"; | ||
import { AuthContext } from "./AuthContext"; | ||
|
||
interface DecodedToken { | ||
exp: number; | ||
iat: number; | ||
iss: string; | ||
sub: string; | ||
aud: string; | ||
} | ||
|
||
interface AuthProviderProps { | ||
children: React.ReactNode; | ||
} | ||
const refreshToken = async ( | ||
getIdTokenClaims: () => Promise<IdToken | undefined>, | ||
setToken: (token: string | null) => void | ||
) => { | ||
if (getIdTokenClaims) { | ||
const claims = await getIdTokenClaims(); | ||
if (claims) { | ||
const idToken = claims.__raw; // The raw id_token | ||
localStorage.setItem("auth0.token", idToken); | ||
setToken(idToken); | ||
|
||
try { | ||
const decodedToken: DecodedToken = jwtDecode(idToken); | ||
const expiryTime = decodedToken.exp * 1000; // Convert to milliseconds | ||
const timeoutDuration = expiryTime - Date.now() - 60 * 1000; // Refresh 1 minute before expiry | ||
|
||
setTimeout(() => { | ||
refreshToken(getIdTokenClaims, setToken); | ||
}, timeoutDuration); | ||
} catch (error) { | ||
console.error("Invalid token", error); | ||
} | ||
} | ||
} | ||
}; | ||
|
||
export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => { | ||
const { user, getIdTokenClaims } = useAuth0(); | ||
const [token, setToken] = useState<string | null>(null); | ||
|
||
useEffect(() => { | ||
if (user && getIdTokenClaims) { | ||
refreshToken(getIdTokenClaims, setToken); | ||
} | ||
}, [user, getIdTokenClaims]); | ||
|
||
const value = useMemo(() => ({ token, user }), [token, user]); | ||
|
||
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1,3 @@ | ||
export * from "./AuthContext"; | ||
export * from "./AuthProvider"; | ||
export * from "./useAuth"; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters