64 lines
2.0 KiB
TypeScript
64 lines
2.0 KiB
TypeScript
"use client";
|
|||
|
|
|
||
|
|
import Script from "next/script";
|
||
|
|
import { useRouter } from "next/navigation";
|
||
|
|
import { useCallback, useEffect, useRef, useState } from "react";
|
||
|
|
|
||
|
|
import { api, errorText } from "@/lib/api";
|
||
|
|
|
||
|
|
export function GoogleLogin({ clientId, target }: { clientId: string; target: string }) {
|
||
|
|
const router = useRouter();
|
||
|
|
const slot = useRef<HTMLDivElement>(null);
|
||
|
|
const [ready, setReady] = useState(false);
|
||
|
|
const [error, setError] = useState<string | null>(null);
|
||
|
|
const [busy, setBusy] = useState(false);
|
||
|
|
|
||
|
|
const onCredential = useCallback(
|
||
|
|
async (response: GoogleCredentialResponse) => {
|
||
|
|
setBusy(true);
|
||
|
|
setError(null);
|
||
|
|
try {
|
||
|
|
await api("/auth/google", { body: { id_token: response.credential } });
|
||
|
|
router.replace(target);
|
||
|
|
router.refresh();
|
||
|
|
} catch (e) {
|
||
|
|
setError(errorText(e));
|
||
|
|
setBusy(false);
|
||
|
|
}
|
||
|
|
},
|
||
|
|
[router, target],
|
||
|
|
);
|
||
|
|
|
||
|
|
useEffect(() => {
|
||
|
|
const google = window.google;
|
||
|
|
if (!ready || !google || !slot.current) return;
|
||
|
|
google.accounts.id.initialize({ client_id: clientId, callback: onCredential, ux_mode: "popup", itp_support: true });
|
||
|
|
google.accounts.id.renderButton(slot.current, {
|
||
|
|
theme: "filled_black",
|
||
|
|
size: "large",
|
||
|
|
text: "continue_with",
|
||
|
|
shape: "rectangular",
|
||
|
|
locale: "hu",
|
||
|
|
width: Math.min(400, slot.current.clientWidth || 400),
|
||
|
|
});
|
||
|
|
}, [ready, clientId, onCredential]);
|
||
|
|
|
||
|
|
return (
|
||
|
|
<div className="field">
|
||
|
|
<Script
|
||
|
|
src="https://accounts.google.com/gsi/client"
|
||
|
|
strategy="afterInteractive"
|
||
|
|
onReady={() => setReady(true)}
|
||
|
|
onError={() => setError("Nem sikerült betölteni a Google-belépést. Ellenőrizd a hálózatot vagy a reklámblokkolót.")}
|
||
|
|
/>
|
||
|
|
<div ref={slot} className="gsi-slot" aria-busy={busy} />
|
||
|
|
{busy && <p className="msg muted">Belépés…</p>}
|
||
|
|
{error && (
|
||
|
|
<p className="msg msg-error" role="alert">
|
||
|
|
{error}
|
||
|
|
</p>
|
||
|
|
)}
|
||
|
|
</div>
|
||
|
|
);
|
||
|
|
}
|