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

Add useSignInWithCredentialMutation #114

Open
wants to merge 4 commits into
base: next
Choose a base branch
from
Open
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
8 changes: 5 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,14 @@
},
"devDependencies": {
"@tanstack/react-query": "^5.55.4",
"@types/jsonwebtoken": "^9.0.7",
"@vitest/coverage-istanbul": "^2.0.5",
"firebase": "^10.13.1",
"happy-dom": "^15.7.3",
"jsonwebtoken": "^9.0.2",
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

introduced jsonwebtoken because while trying to generate an id token thats required by GoogleAuthProvider.credential ,other formats were being rejected with the error below
image

"react": "^18.3.1",
"tsup": "^8.2.4",
"typescript": "^5.6.2",
"vitest": "^2.0.5",
"happy-dom": "^15.7.3",
"@vitest/coverage-istanbul": "^2.0.5"
"vitest": "^2.0.5"
}
}
3 changes: 1 addition & 2 deletions packages/react/src/auth/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
// useSendPasswordResetEmailMutation
// useSendSignInLinkToEmailMutation
export { useSignInAnonymouslyMutation } from "./useSignInAnonymouslyMutation";
// useSignInWithCredentialMutation
export { useSignInWithCredentialMutation } from "./useSignInWithCredentialMutation";
// useSignInWithCustomTokenMutation
// useSignInWithEmailAndPasswordMutation
// useSignInWithEmailLinkMutation
Expand All @@ -46,4 +46,3 @@ export { useSignInAnonymouslyMutation } from "./useSignInAnonymouslyMutation";
// useUpdatePasswordMutation
// useUpdateProfileMutation
// useVerifyBeforeUpdateEmailMutation

160 changes: 160 additions & 0 deletions packages/react/src/auth/useSignInWithCredentialMutation.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
import React from "react";
import { describe, expect, test, beforeEach, afterEach, vi } from "vitest";
import { renderHook, act, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useSignInWithCredentialMutation } from "./useSignInWithCredentialMutation";
import { auth, expectFirebaseError, wipeAuth } from "~/testing-utils";
import { GoogleAuthProvider } from "firebase/auth";
import jwt from "jsonwebtoken";

const secret = "something-secret";
const payload = {
email: "[email protected]",
sub: "tanstack-query-firebase",
};

const mockIdToken = jwt.sign(payload, secret, { expiresIn: "1h" });

const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
mutations: { retry: false },
},
});

const wrapper = ({ children }: { children: React.ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
);

describe("useSignInWithCredentialMutation", () => {
beforeEach(async () => {
queryClient.clear();
await wipeAuth();
});

afterEach(async () => {
await auth.signOut();
});

const credential = GoogleAuthProvider.credential(mockIdToken);

test("successfully signs in with credentials", async () => {
const { result } = renderHook(
() => useSignInWithCredentialMutation(auth, credential),
{ wrapper }
);

act(() => result.current.mutate());

await waitFor(() => expect(result.current.isSuccess).toBe(true));

expect(result.current.data).toHaveProperty("user");
expect(result.current.data?.user).toHaveProperty("uid");
expect(result.current.data?.user).toHaveProperty("email");
expect(result.current.data?.user.email).toBe(
"[email protected]"
);
expect(result.current.data?.user.isAnonymous).toBe(false);
});

test("handles sign-in error with invalid credential", async () => {
const invalidCredential = GoogleAuthProvider.credential("invalid-token");

const { result } = renderHook(
() => useSignInWithCredentialMutation(auth, invalidCredential),
{ wrapper }
);

act(() => {
result.current.mutate();
});

await waitFor(() => expect(result.current.isError).toBe(true));

expectFirebaseError(result.current.error, "auth/invalid-credential");
});

test("resets mutation state correctly", async () => {
const { result } = renderHook(
() => useSignInWithCredentialMutation(auth, credential),
{ wrapper }
);

act(() => result.current.mutate());

await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
expect(result.current.data).toBeDefined();
});

act(() => {
result.current.reset();
});

await waitFor(() => {
expect(result.current.isIdle).toBe(true);
expect(result.current.data).toBeUndefined();
expect(result.current.error).toBeNull();
});
});

test("allows multiple sequential sign-ins", async () => {
const { result } = renderHook(
() => useSignInWithCredentialMutation(auth, credential),
{ wrapper }
);

// First sign-in
act(() => result.current.mutate());
await waitFor(() => expect(result.current.isSuccess).toBe(true));

// Reset state
act(() => result.current.reset());
await waitFor(() => expect(result.current.isIdle).toBe(true));

// Second sign-in
act(() => result.current.mutate());
await waitFor(() => expect(result.current.isSuccess).toBe(true));
});

test("handles concurrent sign-in attempts", async () => {
const { result } = renderHook(
() => useSignInWithCredentialMutation(auth, credential),
{ wrapper }
);

const promise1 = act(() => result.current.mutate());
const promise2 = act(() => result.current.mutate());

await Promise.all([promise1, promise2]);

await waitFor(() => expect(result.current.isSuccess).toBe(true));

expect(result.current.data?.user.email).toBe(
"[email protected]"
);
});

test("respects custom mutation options", async () => {
const onSuccess = vi.fn();
const onError = vi.fn();

const { result } = renderHook(
() =>
useSignInWithCredentialMutation(auth, credential, {
onSuccess,
onError,
}),
{ wrapper }
);

act(() => {
result.current.mutate();
});

await waitFor(() => expect(result.current.isSuccess).toBe(true));

expect(onSuccess).toHaveBeenCalled();
expect(onError).not.toHaveBeenCalled();
});
});
24 changes: 24 additions & 0 deletions packages/react/src/auth/useSignInWithCredentialMutation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { useMutation, type UseMutationOptions } from "@tanstack/react-query";
import {
type Auth,
type AuthCredential,
type AuthError,
signInWithCredential,
type UserCredential,
} from "firebase/auth";

type AuthUseMutationOptions<TData = unknown, TError = Error> = Omit<
UseMutationOptions<TData, TError, void>,
"mutationFn"
>;

export function useSignInWithCredentialMutation(
auth: Auth,
credential: AuthCredential,
options?: AuthUseMutationOptions<UserCredential, AuthError>
) {
return useMutation<UserCredential, AuthError, void>({
...options,
mutationFn: () => signInWithCredential(auth, credential),
});
}
Loading