feat: rewrite project create to use NextAuth session + Postgres

This commit is contained in:
2026-02-18 01:24:47 +00:00
parent 3fa242076b
commit 710a24a2fb

View File

@@ -1,26 +1,29 @@
import { NextResponse } from 'next/server'; import { NextResponse } from 'next/server';
import { getAdminAuth, getAdminDb } from '@/lib/firebase/admin'; import { getServerSession } from 'next-auth';
import { FieldValue } from 'firebase-admin/firestore'; import { authOptions } from '@/lib/auth/authOptions';
import { query } from '@/lib/db-postgres';
import { randomUUID } from 'crypto';
import type { ProjectPhaseData, ProjectPhaseScores } from '@/lib/types/project-artifacts'; import type { ProjectPhaseData, ProjectPhaseScores } from '@/lib/types/project-artifacts';
export async function POST(request: Request) { export async function POST(request: Request) {
try { try {
const authHeader = request.headers.get('Authorization'); const session = await getServerSession(authOptions);
if (!authHeader?.startsWith('Bearer ')) { if (!session?.user?.email) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
} }
const idToken = authHeader.split('Bearer ')[1]; const email = session.user.email;
const adminAuth = getAdminAuth();
const adminDb = getAdminDb();
let userId: string; // Resolve Firebase user ID and workspace from fs_users
try { const users = await query<{ id: string; data: any }>(`
const decodedToken = await adminAuth.verifyIdToken(idToken); SELECT id, data FROM fs_users WHERE data->>'email' = $1 LIMIT 1
userId = decodedToken.uid; `, [email]);
} catch (error) {
return NextResponse.json({ error: 'Invalid token' }, { status: 401 }); const firebaseUserId = users[0]?.id || session.user.id || randomUUID();
} const userData = users[0]?.data || {};
const workspace =
userData.workspace ||
email.split('@')[0].toLowerCase().replace(/[^a-z0-9]+/g, '-') + '-account';
const body = await request.json(); const body = await request.json();
const { const {
@@ -29,111 +32,81 @@ export async function POST(request: Request) {
slug, slug,
vision, vision,
product, product,
workspacePath, // Optional: if coming from association prompt workspacePath,
chatgptUrl, // Optional: if from ChatGPT chatgptUrl,
githubRepo, // Optional: if from GitHub githubRepo,
githubRepoId, githubRepoId,
githubRepoUrl, githubRepoUrl,
githubDefaultBranch, githubDefaultBranch,
} = body; } = body;
// Check if slug is available // Check slug uniqueness
const existingProject = await adminDb const existing = await query(`SELECT id FROM fs_projects WHERE slug = $1 LIMIT 1`, [slug]);
.collection('projects') if (existing.length > 0) {
.where('slug', '==', slug) return NextResponse.json({ error: 'Project slug already exists' }, { status: 400 });
.limit(1)
.get();
if (!existingProject.empty) {
return NextResponse.json(
{ error: 'Project slug already exists' },
{ status: 400 }
);
} }
// Get user data const projectId = randomUUID();
const userDoc = await adminDb.collection('users').doc(userId).get(); const now = new Date().toISOString();
const userData = userDoc.data();
const workspace = userData?.workspace || 'my-workspace';
// Create project const projectData = {
const projectRef = adminDb.collection('projects').doc(); id: projectId,
await projectRef.set({
id: projectRef.id,
name: projectName, name: projectName,
slug, slug,
userId, userId: firebaseUserId,
workspace, workspace,
projectType, projectType,
productName: product.name, productName: product?.name || projectName,
productVision: vision || '', productVision: vision || '',
isForClient: product.isForClient || false, isForClient: product?.isForClient || false,
hasLogo: product.hasLogo || false, hasLogo: product?.hasLogo || false,
hasDomain: product.hasDomain || false, hasDomain: product?.hasDomain || false,
hasWebsite: product.hasWebsite || false, hasWebsite: product?.hasWebsite || false,
hasGithub: !!githubRepo, hasGithub: !!githubRepo,
hasChatGPT: !!chatgptUrl, hasChatGPT: !!chatgptUrl,
workspacePath: workspacePath || null, workspacePath: workspacePath || null,
workspaceName: workspacePath ? workspacePath.split('/').pop() : null, workspaceName: workspacePath ? workspacePath.split('/').pop() : null,
// GitHub data
githubRepo: githubRepo || null, githubRepo: githubRepo || null,
githubRepoId: githubRepoId || null, githubRepoId: githubRepoId || null,
githubRepoUrl: githubRepoUrl || null, githubRepoUrl: githubRepoUrl || null,
githubDefaultBranch: githubDefaultBranch || null, githubDefaultBranch: githubDefaultBranch || null,
// ChatGPT data
chatgptUrl: chatgptUrl || null, chatgptUrl: chatgptUrl || null,
// Extension tracking
extensionLinked: false, extensionLinked: false,
status: 'active', status: 'active',
// Pipeline tracking
currentPhase: 'collector', currentPhase: 'collector',
phaseStatus: 'not_started', phaseStatus: 'not_started',
phaseData: {} as ProjectPhaseData, phaseData: {} as ProjectPhaseData,
phaseScores: {} as ProjectPhaseScores, phaseScores: {} as ProjectPhaseScores,
createdAt: FieldValue.serverTimestamp(), createdAt: now,
updatedAt: FieldValue.serverTimestamp(), updatedAt: now,
}); };
console.log(`[API] Created project ${projectRef.id} (${slug})`); await query(`
INSERT INTO fs_projects (id, data, user_id, workspace, slug)
VALUES ($1, $2::jsonb, $3, $4, $5)
`, [projectId, JSON.stringify(projectData), firebaseUserId, workspace, slug]);
// If workspacePath provided, associate existing sessions // Associate unlinked sessions for this workspace path
if (workspacePath) { if (workspacePath) {
const sessionsSnapshot = await adminDb await query(`
.collection('sessions') UPDATE fs_sessions
.where('userId', '==', userId) SET data = jsonb_set(
.where('workspacePath', '==', workspacePath) jsonb_set(data, '{projectId}', $1::jsonb),
.where('needsProjectAssociation', '==', true) '{needsProjectAssociation}', 'false'
.get(); )
WHERE user_id = $2
if (!sessionsSnapshot.empty) { AND data->>'workspacePath' = $3
const batch = adminDb.batch(); AND (data->>'needsProjectAssociation')::boolean = true
sessionsSnapshot.docs.forEach((doc) => { `, [JSON.stringify(projectId), firebaseUserId, workspacePath]);
batch.update(doc.ref, {
projectId: projectRef.id,
needsProjectAssociation: false,
updatedAt: FieldValue.serverTimestamp(),
});
});
await batch.commit();
console.log(`[API] Associated ${sessionsSnapshot.size} sessions with project`);
}
} }
return NextResponse.json({ console.log('[API] Created project', projectId, slug);
success: true, return NextResponse.json({ success: true, projectId, slug, workspace });
projectId: projectRef.id,
slug,
workspace,
});
} catch (error) { } catch (error) {
console.error('Error creating project:', error); console.error('[POST /api/projects/create] Error:', error);
return NextResponse.json( return NextResponse.json(
{ { error: 'Failed to create project', details: error instanceof Error ? error.message : String(error) },
error: 'Failed to create project',
details: error instanceof Error ? error.message : String(error),
},
{ status: 500 } { status: 500 }
); );
} }
} }