From e04dd55cc0a895e4732c30dc47c168482358bc29 Mon Sep 17 00:00:00 2001 From: Michael van Tellingen Date: Tue, 17 Dec 2024 19:01:32 +0100 Subject: [PATCH] feat(react): support passing handlers for actions Support passing custom handlers for logout and refresh actions --- .changeset/little-kids-rule.md | 5 +++++ packages/react/src/provider.tsx | 29 +++++++++++++++++++++++++---- 2 files changed, 30 insertions(+), 4 deletions(-) create mode 100644 .changeset/little-kids-rule.md diff --git a/.changeset/little-kids-rule.md b/.changeset/little-kids-rule.md new file mode 100644 index 0000000..e84de2c --- /dev/null +++ b/.changeset/little-kids-rule.md @@ -0,0 +1,5 @@ +--- +"@labdigital/federated-token-react": minor +--- + +Support passing custom handlers for logout and refresh actions diff --git a/packages/react/src/provider.tsx b/packages/react/src/provider.tsx index 6dbcb9e..45c69bd 100644 --- a/packages/react/src/provider.tsx +++ b/packages/react/src/provider.tsx @@ -56,11 +56,15 @@ type AuthContextType = { const AuthContext = createContext(undefined); export type AuthProviderProps = { - refreshTokenEndpoint: string; - refreshTokenMutation: string; - logoutEndpoint: string; - logoutMutation: string; cookieNames?: CookieNames; + logoutHandler?: () => void; + refreshHandler?: () => Promise; + + // Deprecated + refreshTokenEndpoint?: string; + refreshTokenMutation?: string; + logoutEndpoint?: string; + logoutMutation?: string; }; /** @@ -291,6 +295,14 @@ export function AuthProvider({ }; const refreshAccessToken = async (): Promise => { + if (options.refreshHandler) { + return await options.refreshHandler(); + } + + if (!options.refreshTokenEndpoint || !options.refreshTokenMutation) { + throw new Error("No refresh token endpoint or mutation provided"); + } + // Since we are storing the refresh token in a cookie this will be sent // automatically by the browser. const response = await fetch(options.refreshTokenEndpoint, { @@ -319,6 +331,15 @@ export function AuthProvider({ }; const clearTokens = async () => { + if (options.logoutHandler) { + await options.logoutHandler(); + return; + } + + if (!options.logoutEndpoint || !options.logoutMutation) { + throw new Error("No logout endpoint or mutation provided"); + } + // Since we are storing the refresh token in a cookie this will be sent // automatically by the browser. const response = await fetch(options.logoutEndpoint, {