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(react): support passing handlers for actions #73

Merged
merged 1 commit into from
Dec 17, 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
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
Loading