Skip to content

Commit

Permalink
feat(react): support passing handlers for actions
Browse files Browse the repository at this point in the history
Support passing custom handlers for logout and refresh actions
  • Loading branch information
mvantellingen committed Dec 17, 2024
1 parent 7ff7c65 commit e04dd55
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
5 changes: 5 additions & 0 deletions .changeset/little-kids-rule.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@labdigital/federated-token-react": minor
---

Support passing custom handlers for logout and refresh actions
29 changes: 25 additions & 4 deletions packages/react/src/provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,15 @@ type AuthContextType = {
const AuthContext = createContext<AuthContextType | undefined>(undefined);

export type AuthProviderProps = {
refreshTokenEndpoint: string;
refreshTokenMutation: string;
logoutEndpoint: string;
logoutMutation: string;
cookieNames?: CookieNames;
logoutHandler?: () => void;
refreshHandler?: () => Promise<boolean>;

// Deprecated
refreshTokenEndpoint?: string;
refreshTokenMutation?: string;
logoutEndpoint?: string;
logoutMutation?: string;
};

/**
Expand Down Expand Up @@ -291,6 +295,14 @@ export function AuthProvider({
};

const refreshAccessToken = async (): Promise<boolean> => {
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, {
Expand Down Expand Up @@ -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, {
Expand Down

0 comments on commit e04dd55

Please sign in to comment.