Add Google login to checkout login form
Some checks failed
linter / quality (push) Has been cancelled
tests / ci (push) Has been cancelled
tests / ui (push) Has been cancelled

This commit is contained in:
Codex Agent
2026-01-23 14:17:12 +01:00
parent 72dd1409e8
commit d629b745c4
4 changed files with 249 additions and 32 deletions

View File

@@ -1,4 +1,4 @@
import React, { useEffect, useState } from "react";
import React, { useEffect, useMemo, useState } from "react";
import { usePage } from "@inertiajs/react";
import { useTranslation } from "react-i18next";
import toast from "react-hot-toast";
@@ -51,6 +51,20 @@ export default function LoginForm({ onSuccess, canResetPassword = true, locale,
const loginEndpoint = '/checkout/login';
const canUseGoogle = typeof packageId === "number" && !Number.isNaN(packageId);
const googleHref = useMemo(() => {
if (!canUseGoogle) {
return "";
}
const params = new URLSearchParams({
package_id: String(packageId),
locale: resolvedLocale,
});
return `/checkout/auth/google?${params.toString()}`;
}, [canUseGoogle, packageId, resolvedLocale]);
const [values, setValues] = useState({
identifier: "",
password: "",
@@ -58,6 +72,7 @@ export default function LoginForm({ onSuccess, canResetPassword = true, locale,
});
const [errors, setErrors] = useState<FieldErrors>({});
const [isSubmitting, setIsSubmitting] = useState(false);
const [isRedirectingToGoogle, setIsRedirectingToGoogle] = useState(false);
const [hasTriedSubmit, setHasTriedSubmit] = useState(false);
const [shouldFocusError, setShouldFocusError] = useState(false);
@@ -164,6 +179,15 @@ export default function LoginForm({ onSuccess, canResetPassword = true, locale,
}
};
const handleGoogleLogin = () => {
if (!googleHref) {
return;
}
setIsRedirectingToGoogle(true);
window.location.href = googleHref;
};
return (
<form onSubmit={submit} className="flex flex-col gap-6" noValidate>
<div className="grid gap-6">
@@ -219,6 +243,30 @@ export default function LoginForm({ onSuccess, canResetPassword = true, locale,
</Button>
</div>
{canUseGoogle && (
<div className="space-y-3">
<div className="flex items-center gap-3 text-xs font-semibold uppercase tracking-[0.3em] text-muted-foreground">
<span className="h-px flex-1 bg-gray-200 dark:bg-gray-800" aria-hidden />
{t("login.oauth_divider", "oder")}
<span className="h-px flex-1 bg-gray-200 dark:bg-gray-800" aria-hidden />
</div>
<Button
type="button"
variant="outline"
onClick={handleGoogleLogin}
disabled={isSubmitting || isRedirectingToGoogle}
className="flex w-full items-center justify-center gap-2"
>
{isRedirectingToGoogle ? (
<LoaderCircle className="h-4 w-4 animate-spin" />
) : (
<GoogleIcon className="h-4 w-4" />
)}
<span>{t("login.google_cta")}</span>
</Button>
</div>
)}
{Object.values(errors).some(Boolean) && (
<div className="p-4 bg-red-50 border border-red-200 rounded-md">
<p className="text-sm text-red-800">{Object.values(errors).filter(Boolean).join(" \u2022 ")}</p>
@@ -227,3 +275,14 @@ export default function LoginForm({ onSuccess, canResetPassword = true, locale,
</form>
);
}
function GoogleIcon({ className }: { className?: string }) {
return (
<svg className={className} viewBox="0 0 24 24" aria-hidden>
<path
fill="#EA4335"
d="M12 11.999v4.8h6.7c-.3 1.7-2 4.9-6.7 4.9-4 0-7.4-3.3-7.4-7.4S8 6 12 6c2.3 0 3.9 1 4.8 1.9l3.3-3.2C18.1 2.6 15.3 1 12 1 5.9 1 1 5.9 1 12s4.9 11 11 11c6.3 0 10.5-4.4 10.5-10.6 0-.7-.1-1.2-.2-1.8H12z"
/>
</svg>
);
}

View File

@@ -0,0 +1,53 @@
import React from 'react';
import { describe, expect, it, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
class ResizeObserverMock {
observe() {}
unobserve() {}
disconnect() {}
}
global.ResizeObserver = ResizeObserverMock as unknown as typeof ResizeObserver;
vi.mock('@inertiajs/react', () => ({
usePage: () => ({ props: { locale: 'de' } }),
Link: ({ children, ...props }: { children: React.ReactNode }) => <a {...props}>{children}</a>,
}));
vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string, fallback?: string | Record<string, unknown>) => {
if (typeof fallback === 'string') {
return fallback;
}
if (fallback && typeof fallback === 'object' && typeof fallback.defaultValue === 'string') {
return fallback.defaultValue;
}
return key;
},
}),
}));
vi.mock('react-hot-toast', () => ({
default: {
error: vi.fn(),
success: vi.fn(),
},
}));
import LoginForm from '../LoginForm';
describe('LoginForm', () => {
it('renders Google login option when packageId is provided', () => {
render(<LoginForm packageId={12} />);
expect(screen.getByText('login.google_cta')).toBeInTheDocument();
});
it('does not render Google login option without packageId', () => {
render(<LoginForm />);
expect(screen.queryByText('login.google_cta')).not.toBeInTheDocument();
});
});

View File

@@ -0,0 +1,90 @@
import React from 'react';
import { describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen } from '@testing-library/react';
vi.mock('@inertiajs/react', () => ({
usePage: () => ({ props: { locale: 'de', googleAuth: {} } }),
}));
vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string, fallback?: string | Record<string, unknown>) => {
if (typeof fallback === 'string') {
return fallback;
}
if (fallback && typeof fallback === 'object' && typeof fallback.defaultValue === 'string') {
return fallback.defaultValue;
}
return key;
},
}),
Trans: ({ i18nKey }: { i18nKey: string }) => <span>{i18nKey}</span>,
}));
vi.mock('react-hot-toast', () => ({
default: {
error: vi.fn(),
success: vi.fn(),
},
}));
vi.mock('@/components/ui/button', () => ({
Button: ({ children, onClick, ...props }: { children: React.ReactNode; onClick?: () => void }) => (
<button type="button" onClick={onClick} {...props}>
{children}
</button>
),
}));
vi.mock('@/components/ui/alert', () => ({
Alert: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
AlertDescription: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
AlertTitle: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
}));
vi.mock('@/components/ui/collapsible', () => ({
Collapsible: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
CollapsibleContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
CollapsibleTrigger: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
}));
vi.mock('@/lib/utils', () => ({
cn: (...args: Array<string | boolean | undefined>) => args.filter(Boolean).join(' '),
}));
vi.mock('../../../auth/LoginForm', () => ({
default: () => <div>LoginForm</div>,
}));
vi.mock('../../../auth/RegisterForm', () => ({
default: () => <div>RegisterForm</div>,
}));
vi.mock('../WizardContext', () => ({
useCheckoutWizard: () => ({
isAuthenticated: false,
authUser: null,
setAuthUser: vi.fn(),
nextStep: vi.fn(),
selectedPackage: { id: 1, name: 'Starter', price: 0, type: 'endcustomer', features: [] },
}),
}));
vi.mock('lucide-react', () => ({
ChevronDown: () => <span>chevron</span>,
LoaderCircle: () => <span>loader</span>,
}));
import { AuthStep } from '../steps/AuthStep';
describe('AuthStep Google controls', () => {
it('hides the top Google button when switching to login mode', () => {
render(<AuthStep privacyHtml="" />);
expect(screen.getByText('checkout.auth_step.continue_with_google')).toBeInTheDocument();
fireEvent.click(screen.getByText('checkout.auth_step.switch_to_login'));
expect(screen.queryByText('checkout.auth_step.continue_with_google')).not.toBeInTheDocument();
});
});

View File

@@ -46,6 +46,7 @@ export const AuthStep: React.FC<AuthStepProps> = ({ privacyHtml, googleProfile,
const [mode, setMode] = useState<'login' | 'register'>('register');
const [isRedirectingToGoogle, setIsRedirectingToGoogle] = useState(false);
const [showGoogleHelper, setShowGoogleHelper] = useState(false);
const showGoogleControls = mode === 'register';
useEffect(() => {
if (googleAuth?.status === 'signin') {
@@ -60,6 +61,16 @@ export const AuthStep: React.FC<AuthStepProps> = ({ privacyHtml, googleProfile,
}
}, [googleAuth?.error]);
useEffect(() => {
if (mode !== 'login') {
return;
}
if (showGoogleHelper) {
setShowGoogleHelper(false);
}
}, [mode, showGoogleHelper]);
const handleLoginSuccess = (payload: AuthUserPayload | null) => {
if (!payload) {
return;
@@ -148,6 +159,7 @@ export const AuthStep: React.FC<AuthStepProps> = ({ privacyHtml, googleProfile,
>
{t('checkout.auth_step.switch_to_login')}
</Button>
{showGoogleControls && (
<div className="flex flex-1 justify-start gap-2 sm:flex-none">
<Button
variant="outline"
@@ -175,12 +187,15 @@ export const AuthStep: React.FC<AuthStepProps> = ({ privacyHtml, googleProfile,
</button>
</CollapsibleTrigger>
</div>
)}
</div>
{showGoogleControls && (
<CollapsibleContent>
<Alert className="border-dashed border-muted/60 bg-muted/20 text-xs sm:text-sm">
<AlertDescription>{t('checkout.auth_step.google_helper')}</AlertDescription>
</Alert>
</CollapsibleContent>
)}
</Collapsible>
{googleAuth?.error && (