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:
@@ -1,151 +1,96 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { getAdminAuth, getAdminDb } from '@/lib/firebase/admin';
|
||||
import { FieldValue } from 'firebase-admin/firestore';
|
||||
import { getServerSession } from 'next-auth';
|
||||
import { authOptions } from '@/lib/auth/authOptions';
|
||||
import { query } from '@/lib/db-postgres';
|
||||
|
||||
/**
|
||||
* Store GitHub connection for authenticated user
|
||||
* Encrypts and stores the access token securely
|
||||
*/
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const authHeader = request.headers.get('Authorization');
|
||||
if (!authHeader?.startsWith('Bearer ')) {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session?.user?.email) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const idToken = authHeader.split('Bearer ')[1];
|
||||
const adminAuth = getAdminAuth();
|
||||
const adminDb = getAdminDb();
|
||||
|
||||
let userId: string;
|
||||
try {
|
||||
const decodedToken = await adminAuth.verifyIdToken(idToken);
|
||||
userId = decodedToken.uid;
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: 'Invalid token' }, { status: 401 });
|
||||
}
|
||||
|
||||
const { accessToken, githubUser } = await request.json();
|
||||
|
||||
if (!accessToken || !githubUser) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Missing required fields' },
|
||||
{ status: 400 }
|
||||
);
|
||||
return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
|
||||
}
|
||||
|
||||
// TODO: Encrypt the access token before storing
|
||||
// For now, we'll store it directly (should use crypto.subtle or a library)
|
||||
const encryptedToken = accessToken; // PLACEHOLDER
|
||||
await query(
|
||||
`UPDATE fs_users
|
||||
SET data = data || $1::jsonb, updated_at = NOW()
|
||||
WHERE data->>'email' = $2`,
|
||||
[
|
||||
JSON.stringify({
|
||||
githubConnected: true,
|
||||
githubUserId: githubUser.id,
|
||||
githubUsername: githubUser.login,
|
||||
githubName: githubUser.name,
|
||||
githubEmail: githubUser.email,
|
||||
githubAvatarUrl: githubUser.avatar_url,
|
||||
githubAccessToken: accessToken,
|
||||
githubConnectedAt: new Date().toISOString(),
|
||||
}),
|
||||
session.user.email,
|
||||
]
|
||||
);
|
||||
|
||||
// Store GitHub connection
|
||||
const connectionRef = adminDb.collection('githubConnections').doc(userId);
|
||||
await connectionRef.set({
|
||||
userId,
|
||||
githubUserId: githubUser.id,
|
||||
githubUsername: githubUser.login,
|
||||
githubName: githubUser.name,
|
||||
githubEmail: githubUser.email,
|
||||
githubAvatarUrl: githubUser.avatar_url,
|
||||
accessToken: encryptedToken,
|
||||
connectedAt: FieldValue.serverTimestamp(),
|
||||
lastSyncedAt: null,
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
githubUsername: githubUser.login,
|
||||
});
|
||||
return NextResponse.json({ success: true, githubUsername: githubUser.login });
|
||||
} catch (error) {
|
||||
console.error('[GitHub Connect] Error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to store GitHub connection' },
|
||||
{ status: 500 }
|
||||
);
|
||||
return NextResponse.json({ error: 'Failed to store GitHub connection' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get GitHub connection status for authenticated user
|
||||
*/
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
const authHeader = request.headers.get('Authorization');
|
||||
if (!authHeader?.startsWith('Bearer ')) {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session?.user?.email) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const idToken = authHeader.split('Bearer ')[1];
|
||||
const adminAuth = getAdminAuth();
|
||||
const adminDb = getAdminDb();
|
||||
const rows = await query<{ data: any }>(
|
||||
`SELECT data FROM fs_users WHERE data->>'email' = $1 LIMIT 1`,
|
||||
[session.user.email]
|
||||
);
|
||||
|
||||
let userId: string;
|
||||
try {
|
||||
const decodedToken = await adminAuth.verifyIdToken(idToken);
|
||||
userId = decodedToken.uid;
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: 'Invalid token' }, { status: 401 });
|
||||
}
|
||||
|
||||
const connectionDoc = await adminDb
|
||||
.collection('githubConnections')
|
||||
.doc(userId)
|
||||
.get();
|
||||
|
||||
if (!connectionDoc.exists) {
|
||||
if (rows.length === 0 || !rows[0].data?.githubConnected) {
|
||||
return NextResponse.json({ connected: false });
|
||||
}
|
||||
|
||||
const data = connectionDoc.data()!;
|
||||
|
||||
const d = rows[0].data;
|
||||
return NextResponse.json({
|
||||
connected: true,
|
||||
githubUsername: data.githubUsername,
|
||||
githubName: data.githubName,
|
||||
githubAvatarUrl: data.githubAvatarUrl,
|
||||
connectedAt: data.connectedAt,
|
||||
lastSyncedAt: data.lastSyncedAt,
|
||||
githubUsername: d.githubUsername,
|
||||
githubName: d.githubName,
|
||||
githubAvatarUrl: d.githubAvatarUrl,
|
||||
connectedAt: d.githubConnectedAt,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('[GitHub Connect] Error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to fetch GitHub connection' },
|
||||
{ status: 500 }
|
||||
);
|
||||
return NextResponse.json({ error: 'Failed to fetch GitHub connection' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Disconnect GitHub account
|
||||
*/
|
||||
export async function DELETE(request: Request) {
|
||||
try {
|
||||
const authHeader = request.headers.get('Authorization');
|
||||
if (!authHeader?.startsWith('Bearer ')) {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session?.user?.email) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const idToken = authHeader.split('Bearer ')[1];
|
||||
const adminAuth = getAdminAuth();
|
||||
const adminDb = getAdminDb();
|
||||
|
||||
let userId: string;
|
||||
try {
|
||||
const decodedToken = await adminAuth.verifyIdToken(idToken);
|
||||
userId = decodedToken.uid;
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: 'Invalid token' }, { status: 401 });
|
||||
}
|
||||
|
||||
await adminDb.collection('githubConnections').doc(userId).delete();
|
||||
await query(
|
||||
`UPDATE fs_users
|
||||
SET data = data - 'githubConnected' - 'githubUserId' - 'githubUsername'
|
||||
- 'githubName' - 'githubEmail' - 'githubAvatarUrl'
|
||||
- 'githubAccessToken' - 'githubConnectedAt',
|
||||
updated_at = NOW()
|
||||
WHERE data->>'email' = $1`,
|
||||
[session.user.email]
|
||||
);
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (error) {
|
||||
console.error('[GitHub Disconnect] Error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to disconnect GitHub' },
|
||||
{ status: 500 }
|
||||
);
|
||||
return NextResponse.json({ error: 'Failed to disconnect GitHub' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user