MotorSignal-App/website/components/firebase-link.tsx

29 lines
1.5 KiB
TypeScript

'use client';
import { signInWithPopup } from 'firebase/auth';
import { useState } from 'react';
import { firebaseAuth, googleProvider } from '../lib/firebase-client';
export function FirebaseLink({ linked }: { linked: boolean }) {
const [busy, setBusy] = useState(false);
const [message, setMessage] = useState(linked ? 'Google app account connected.' : '');
async function connect() {
setBusy(true);
setMessage('');
try {
const credential = await signInWithPopup(firebaseAuth, googleProvider);
const response = await fetch('/api/account/firebase-link', {
method: 'POST', headers: { 'content-type': 'application/json' },
body: JSON.stringify({ id_token: await credential.user.getIdToken() }),
});
const body = await response.json().catch(() => ({}));
if (!response.ok) throw new Error(body.detail ?? 'Unable to connect Google account.');
setMessage('Google app account connected.');
window.location.reload();
} catch (error) {
setMessage(error instanceof Error ? error.message : 'Unable to connect Google account.');
} finally { setBusy(false); }
}
return <div><p>{linked ? 'Your website account is linked to MotorSignal app data.' : 'Connect the Google account used in the MotorSignal app.'}</p>{!linked && <button className="button" disabled={busy} type="button" onClick={() => void connect()}>{busy ? 'Connecting...' : 'Connect Google app account'}</button>}{message && <p className="form-message" role="status">{message}</p>}</div>;
}