import { generateToken } from '~/server/utils/auth' import { users } from '~/server/utils/db' interface FirebaseUser { localId: string email: string displayName?: string photoUrl?: string } export default defineEventHandler(async (event) => { const body = await readBody(event) const { idToken } = body if (!idToken) { throw createError({ statusCode: 400, message: 'Firebase ID token required' }) } const config = useRuntimeConfig() const apiKey = config.firebaseApiKey || config.public.firebaseApiKey if (!apiKey) { throw createError({ statusCode: 500, message: 'Firebase API key not configured' }) } // Verify token via Firebase Auth REST API const verifyRes = await $fetch( `https://identitytoolkit.googleapis.com/v1/accounts:lookup?key=${apiKey}`, { method: 'POST', body: { idToken } } ).catch(() => null) if (!verifyRes?.users?.[0]) { throw createError({ statusCode: 401, message: 'Invalid Firebase token' }) } const fbUser: FirebaseUser = verifyRes.users[0] const email = fbUser.email const existing = users.get(email) let role = 'user' let userId = fbUser.localId if (existing) { // Update existing users.set(email, { ...existing, id: userId, email, username: fbUser.displayName || email.split('@')[0] }) role = existing.role || 'user' } else { // Create new user users.set(email, { id: userId, email, username: fbUser.displayName || email.split('@')[0], password: 'firebase-managed', role: 'user' }) } const token = generateToken({ id: userId, email, username: fbUser.displayName || email.split('@')[0], role }) return { message: 'Google sign-in successful', token, user: { id: userId, email, username: fbUser.displayName || email.split('@')[0], role, photoUrl: fbUser.photoUrl } } })