Skip to content

Commit

Permalink
chore(react): Expose refreshToken() via useAuth()
Browse files Browse the repository at this point in the history
  • Loading branch information
mvantellingen committed Nov 1, 2024
1 parent f2a59d7 commit 3d43b40
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 7 deletions.
5 changes: 5 additions & 0 deletions .changeset/slow-eels-fry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@labdigital/federated-token-react": patch
---

Expose refreshToken() via `useAuth()`
16 changes: 9 additions & 7 deletions packages/react/src/provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ type AuthContextType = {
logout: () => Promise<void>;
validateLocalToken: () => void;
checkToken: () => Promise<void>;
refreshToken: () => Promise<boolean>;
};

const AuthContext = createContext<AuthContextType | undefined>(undefined);
Expand Down Expand Up @@ -92,7 +93,7 @@ export function AuthProvider({
options: AuthProviderProps;
}) {
const [authState, setAuthState] = useState<
Omit<AuthContextType, "logout" | "validateLocalToken" | "checkToken">
Omit<AuthContextType, "logout" | "validateLocalToken" | "checkToken" | "refreshToken">
>({
isAuthenticated: false,
hasToken: false,
Expand Down Expand Up @@ -275,15 +276,17 @@ export function AuthProvider({
Cookie.get(cookieNames.userRefreshTokenExists) ??
Cookie.get(cookieNames.guestRefreshTokenExists);
if (hasRefreshToken) {
await refreshAccessToken();
return getJWT();
const success = await refreshAccessToken();
if (success) {
return getJWT();
}
}

// No token exists
return undefined;
};

const refreshAccessToken = async () => {
const refreshAccessToken = async (): Promise<boolean> => {
// Since we are storing the refresh token in a cookie this will be sent
// automatically by the browser.
const response = await fetch(options.authEndpoint, {
Expand All @@ -295,9 +298,7 @@ export function AuthProvider({
credentials: "include",
});

if (!response.ok) {
throw new Error(`Failed to refresh token: ${response.statusText}`);
}
return response.ok
};

const clearTokens = async () => {
Expand All @@ -323,6 +324,7 @@ export function AuthProvider({
logout,
validateLocalToken,
checkToken,
refreshToken: refreshAccessToken,
}}
>
{children}
Expand Down

0 comments on commit 3d43b40

Please sign in to comment.