feat: rewrite project delete to use NextAuth session + Postgres

This commit is contained in:
2026-02-18 01:24:49 +00:00
parent 59415bb0d9
commit f7bbf2ea5e

View File

@@ -1,93 +1,57 @@
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';
/**
* Delete a project (soft delete - keeps sessions intact)
* Sessions will remain in the database but projectId will be set to null
*/
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 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 { projectId } = await request.json(); const { projectId } = await request.json();
if (!projectId) { if (!projectId) {
return NextResponse.json( return NextResponse.json({ error: 'Project ID is required' }, { status: 400 });
{ error: 'Project ID is required' },
{ status: 400 }
);
} }
// Verify project belongs to user // Verify ownership
const projectDoc = await adminDb.collection('projects').doc(projectId).get(); const rows = await query<{ id: string; data: any }>(`
SELECT p.id, p.data
FROM fs_projects p
JOIN fs_users u ON u.id = p.user_id
WHERE p.id = $1 AND u.data->>'email' = $2
LIMIT 1
`, [projectId, session.user.email]);
if (!projectDoc.exists) { if (rows.length === 0) {
return NextResponse.json( return NextResponse.json({ error: 'Project not found or unauthorized' }, { status: 404 });
{ error: 'Project not found' },
{ status: 404 }
);
} }
if (projectDoc.data()?.userId !== userId) { // Unlink sessions
return NextResponse.json( const sessionResult = await query(`
{ error: 'Unauthorized to delete this project' }, SELECT COUNT(*)::int AS count FROM fs_sessions WHERE data->>'projectId' = $1
{ status: 403 } `, [projectId]);
); const sessionCount = sessionResult[0]?.count || 0;
}
// Delete the project document await query(`
await adminDb.collection('projects').doc(projectId).delete(); UPDATE fs_sessions
SET data = jsonb_set(
jsonb_set(data, '{projectId}', 'null'),
'{needsProjectAssociation}', 'true'
)
WHERE data->>'projectId' = $1
`, [projectId]);
// Optional: Update sessions to remove project reference // Delete the project
// This makes sessions "orphaned" but keeps all the data await query(`DELETE FROM fs_projects WHERE id = $1`, [projectId]);
const sessionsSnapshot = await adminDb
.collection('sessions')
.where('projectId', '==', projectId)
.get();
if (!sessionsSnapshot.empty) { return NextResponse.json({ success: true, message: 'Project deleted successfully', sessionsPreserved: sessionCount });
const batch = adminDb.batch();
sessionsSnapshot.docs.forEach((doc) => {
batch.update(doc.ref, {
projectId: null,
// Flag these as needing reassignment if user wants to link them later
needsProjectAssociation: true,
updatedAt: FieldValue.serverTimestamp(),
});
});
await batch.commit();
}
return NextResponse.json({
success: true,
message: 'Project deleted successfully',
sessionsPreserved: sessionsSnapshot.size,
});
} catch (error) { } catch (error) {
console.error('[Project Delete] Error:', error); console.error('[POST /api/projects/delete] Error:', error);
return NextResponse.json( return NextResponse.json(
{ { error: 'Failed to delete project', details: error instanceof Error ? error.message : String(error) },
error: 'Failed to delete project',
details: error instanceof Error ? error.message : String(error),
},
{ status: 500 } { status: 500 }
); );
} }
} }