65 lines
1.8 KiB
TypeScript
65 lines
1.8 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server';
|
|
import { cookies } from 'next/headers';
|
|
import { db } from '@/lib/db';
|
|
import { stripe } from '@/lib/stripe';
|
|
import { csrfProtection } from '@/lib/csrf';
|
|
|
|
export async function DELETE(request: NextRequest) {
|
|
try {
|
|
// CSRF Protection
|
|
const csrfCheck = csrfProtection(request);
|
|
if (!csrfCheck.valid) {
|
|
return NextResponse.json(
|
|
{ error: csrfCheck.error },
|
|
{ status: 403 }
|
|
);
|
|
}
|
|
|
|
const userId = cookies().get('userId')?.value;
|
|
if (!userId) {
|
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
|
}
|
|
|
|
// Get user data including Stripe information
|
|
const user = await db.user.findUnique({
|
|
where: { id: userId },
|
|
select: {
|
|
id: true,
|
|
stripeSubscriptionId: true,
|
|
stripeCustomerId: true,
|
|
plan: true,
|
|
},
|
|
});
|
|
|
|
if (!user) {
|
|
return NextResponse.json({ error: 'User not found' }, { status: 404 });
|
|
}
|
|
|
|
// Cancel Stripe subscription if user has one
|
|
if (user.stripeSubscriptionId && user.plan !== 'FREE') {
|
|
try {
|
|
await stripe.subscriptions.cancel(user.stripeSubscriptionId);
|
|
} catch (stripeError) {
|
|
console.error('Error canceling Stripe subscription:', stripeError);
|
|
// Continue with deletion even if Stripe cancellation fails
|
|
}
|
|
}
|
|
|
|
// Delete user and all related data (cascading deletes should handle QR codes, scans, etc.)
|
|
await db.user.delete({
|
|
where: { id: userId },
|
|
});
|
|
|
|
// Clear auth cookie
|
|
cookies().delete('userId');
|
|
|
|
return NextResponse.json({ success: true });
|
|
} catch (error) {
|
|
console.error('Error deleting account:', error);
|
|
return NextResponse.json(
|
|
{ error: 'Internal server error' },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|