feat: rewrite project GET/PATCH to use NextAuth session + Postgres
This commit is contained in:
@@ -1,5 +1,7 @@
|
|||||||
import { NextResponse } from 'next/server';
|
import { NextResponse } from 'next/server';
|
||||||
import { getAdminAuth, getAdminDb } from '@/lib/firebase/admin';
|
import { getServerSession } from 'next-auth';
|
||||||
|
import { authOptions } from '@/lib/auth/authOptions';
|
||||||
|
import { query } from '@/lib/db-postgres';
|
||||||
|
|
||||||
export async function GET(
|
export async function GET(
|
||||||
request: Request,
|
request: Request,
|
||||||
@@ -7,49 +9,29 @@ export async function GET(
|
|||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
const { projectId } = await params;
|
const { projectId } = await params;
|
||||||
|
|
||||||
// Authentication (skip in development if no auth header)
|
|
||||||
const authHeader = request.headers.get('Authorization');
|
|
||||||
const isDevelopment = process.env.NODE_ENV === 'development';
|
|
||||||
|
|
||||||
if (!isDevelopment || authHeader?.startsWith('Bearer ')) {
|
|
||||||
if (!authHeader?.startsWith('Bearer ')) {
|
|
||||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const token = authHeader.substring(7);
|
const session = await getServerSession(authOptions);
|
||||||
const auth = getAdminAuth();
|
if (!session?.user?.email) {
|
||||||
const decoded = await auth.verifyIdToken(token);
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||||
|
|
||||||
if (!decoded?.uid) {
|
|
||||||
return NextResponse.json({ error: 'Invalid token' }, { status: 401 });
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fetch project from Firestore
|
const rows = await query<{ id: string; data: any }>(`
|
||||||
const adminDb = getAdminDb();
|
SELECT p.id, p.data
|
||||||
const projectDoc = await adminDb.collection('projects').doc(projectId).get();
|
FROM fs_projects p
|
||||||
|
JOIN fs_users u ON u.id = p.user_id
|
||||||
if (!projectDoc.exists) {
|
WHERE p.id = $1 AND u.data->>'email' = $2
|
||||||
|
LIMIT 1
|
||||||
|
`, [projectId, session.user.email]);
|
||||||
|
|
||||||
|
if (rows.length === 0) {
|
||||||
return NextResponse.json({ error: 'Project not found' }, { status: 404 });
|
return NextResponse.json({ error: 'Project not found' }, { status: 404 });
|
||||||
}
|
}
|
||||||
|
|
||||||
const projectData = projectDoc.data();
|
return NextResponse.json({ success: true, project: { id: rows[0].id, ...rows[0].data } });
|
||||||
|
|
||||||
return NextResponse.json({
|
|
||||||
success: true,
|
|
||||||
project: {
|
|
||||||
id: projectDoc.id,
|
|
||||||
...projectData,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('[API /projects/:id] Error fetching project:', error);
|
console.error('[GET /api/projects/:id] Error:', error);
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{
|
{ error: 'Failed to fetch project', details: error instanceof Error ? error.message : String(error) },
|
||||||
error: 'Failed to fetch project',
|
|
||||||
details: error instanceof Error ? error.message : String(error)
|
|
||||||
},
|
|
||||||
{ status: 500 }
|
{ status: 500 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -62,54 +44,43 @@ export async function PATCH(
|
|||||||
try {
|
try {
|
||||||
const { projectId } = await params;
|
const { projectId } = await params;
|
||||||
const body = await request.json();
|
const body = await request.json();
|
||||||
|
|
||||||
// Authentication (skip in development if no auth header)
|
|
||||||
const authHeader = request.headers.get('Authorization');
|
|
||||||
const isDevelopment = process.env.NODE_ENV === 'development';
|
|
||||||
|
|
||||||
if (!isDevelopment || authHeader?.startsWith('Bearer ')) {
|
|
||||||
if (!authHeader?.startsWith('Bearer ')) {
|
|
||||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const token = authHeader.substring(7);
|
const session = await getServerSession(authOptions);
|
||||||
const auth = getAdminAuth();
|
if (!session?.user?.email) {
|
||||||
const decoded = await auth.verifyIdToken(token);
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||||
|
|
||||||
if (!decoded?.uid) {
|
|
||||||
return NextResponse.json({ error: 'Invalid token' }, { status: 401 });
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update project in Firestore
|
// Fetch current data (verify ownership)
|
||||||
const adminDb = getAdminDb();
|
const rows = await query<{ id: string; data: any }>(`
|
||||||
const updateData: 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]);
|
||||||
|
|
||||||
// Only update fields that are provided
|
if (rows.length === 0) {
|
||||||
if (body.vision !== undefined) updateData.vision = body.vision;
|
return NextResponse.json({ error: 'Project not found' }, { status: 404 });
|
||||||
if (body.description !== undefined) updateData.description = body.description;
|
}
|
||||||
if (body.name !== undefined) updateData.name = body.name;
|
|
||||||
if (body.githubRepo !== undefined) updateData.githubRepo = body.githubRepo;
|
|
||||||
|
|
||||||
updateData.updatedAt = new Date().toISOString();
|
const current = rows[0].data || {};
|
||||||
|
const updated = { ...current };
|
||||||
|
const allowedFields = ['vision', 'description', 'name', 'githubRepo', 'productVision', 'productName'];
|
||||||
|
for (const field of allowedFields) {
|
||||||
|
if (body[field] !== undefined) updated[field] = body[field];
|
||||||
|
}
|
||||||
|
updated.updatedAt = new Date().toISOString();
|
||||||
|
|
||||||
await adminDb.collection('projects').doc(projectId).update(updateData);
|
await query(`
|
||||||
|
UPDATE fs_projects SET data = $1::jsonb WHERE id = $2
|
||||||
return NextResponse.json({
|
`, [JSON.stringify(updated), projectId]);
|
||||||
success: true,
|
|
||||||
message: 'Project updated successfully',
|
|
||||||
updated: Object.keys(updateData)
|
|
||||||
});
|
|
||||||
|
|
||||||
|
return NextResponse.json({ success: true, message: 'Project updated successfully' });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('[API /projects/:id] Error updating project:', error);
|
console.error('[PATCH /api/projects/:id] Error:', error);
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{
|
{ error: 'Failed to update project', details: error instanceof Error ? error.message : String(error) },
|
||||||
error: 'Failed to update project',
|
|
||||||
details: error instanceof Error ? error.message : String(error)
|
|
||||||
},
|
|
||||||
{ status: 500 }
|
{ status: 500 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user