migrate: replace Firebase with PostgreSQL across core routes

- chat-context.ts: session history now from fs_sessions
- /api/sessions: reads from fs_sessions (NextAuth session auth)
- /api/github/connect: NextAuth session + stores in fs_users.data
- /api/user/api-key: NextAuth session + stores in fs_users.data
- /api/projects/[id]/vision: PATCH to fs_projects JSONB
- /api/projects/[id]/knowledge/items: reads from fs_knowledge_items
- /api/projects/[id]/knowledge/import-ai-chat: uses pg createKnowledgeItem
- lib/server/knowledge.ts: fully rewritten to use PostgreSQL
- entrypoint.sh: add fs_knowledge_items and chat_conversations tables

Made-with: Cursor
This commit is contained in:
2026-02-27 13:25:38 -08:00
parent 3ce10dc45b
commit ef7a88e913
9 changed files with 267 additions and 360 deletions

View File

@@ -1,76 +1,41 @@
import { NextResponse } from 'next/server';
import { adminAuth, adminDb } from '@/lib/firebase/admin';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth/authOptions';
import { query } from '@/lib/db-postgres';
import { v4 as uuidv4 } from 'uuid';
import { FieldValue } from 'firebase-admin/firestore';
export async function GET(request: Request) {
try {
console.log('[API] Getting API key...');
// Get the authorization header
const authHeader = request.headers.get('authorization');
if (!authHeader?.startsWith('Bearer ')) {
console.error('[API] No authorization header');
return NextResponse.json(
{ error: 'No authorization token provided' },
{ status: 401 }
);
const session = await getServerSession(authOptions);
if (!session?.user?.email) {
return NextResponse.json({ error: 'No authorization token provided' }, { status: 401 });
}
const token = authHeader.substring(7);
console.log('[API] Token received, verifying...');
// Verify the Firebase ID token
const decodedToken = await adminAuth.verifyIdToken(token);
const userId = decodedToken.uid;
console.log('[API] Token verified, userId:', userId);
const rows = await query<{ data: any }>(
`SELECT data FROM fs_users WHERE data->>'email' = $1 LIMIT 1`,
[session.user.email]
);
// Check if user already has an API key
console.log('[API] Checking for existing API key...');
const userDoc = await adminDb.collection('users').doc(userId).get();
if (userDoc.exists && userDoc.data()?.apiKey) {
console.log('[API] Found existing API key');
return NextResponse.json({
apiKey: userDoc.data()!.apiKey,
});
if (rows.length > 0 && rows[0].data?.apiKey) {
return NextResponse.json({ apiKey: rows[0].data.apiKey });
}
// Generate new API key
console.log('[API] Generating new API key...');
// Generate new API key and store it
const apiKey = `vibn_${uuidv4().replace(/-/g, '')}`;
// Store API key document
console.log('[API] Storing API key in Firestore...');
await adminDb.collection('apiKeys').doc(apiKey).set({
key: apiKey,
userId,
createdAt: FieldValue.serverTimestamp(),
isActive: true,
});
// Update user document with API key reference (or create if doesn't exist)
console.log('[API] Updating user document...');
await adminDb.collection('users').doc(userId).set({
apiKey,
updatedAt: FieldValue.serverTimestamp(),
}, { merge: true });
console.log('[API] API key created successfully:', apiKey);
return NextResponse.json({
apiKey,
isNew: true,
});
await query(
`UPDATE fs_users
SET data = data || $1::jsonb, updated_at = NOW()
WHERE data->>'email' = $2`,
[JSON.stringify({ apiKey, apiKeyCreatedAt: new Date().toISOString() }), session.user.email]
);
return NextResponse.json({ apiKey, isNew: true });
} catch (error) {
console.error('[API] Error getting/creating API key:', error);
console.error('[API] Error stack:', error instanceof Error ? error.stack : 'No stack trace');
return NextResponse.json(
{
error: 'Failed to get API key',
details: error instanceof Error ? error.message : String(error),
},
{ error: 'Failed to get API key', details: error instanceof Error ? error.message : String(error) },
{ status: 500 }
);
}
}