deckhearth/pages/api/user/delete.js
varutasu da50d78406
fix(security): drop wildcard CORS + redundant OPTIONS from 24 API routes (P0 #5)
Closes P0 #5 from PARTIAL to RESOLVED. Sweeps the remaining 24 pages/api/** handlers that carried the identical scaffolded wildcard-CORS + OPTIONS preflight pattern (Brief 4 cleaned login + register; this finishes the job). Adds a blocking forbidden-cors-headers CI job modeled on forbidden-endpoints to lock the cleanup against future regression. 25 files changed (+29/-261). Local: lint 128 baseline, vitest 21/21, zero CORS matches, YAML valid. CI: Playwright smoke 3/3 in 3.3s against post-removal preview (login/verify flow still works), new forbidden-cors-headers job passes in 4s, all gates green. PR #19 architect-commit ec22b70, implementer-commit a843736.
2026-05-24 20:41:38 -05:00

104 lines
No EOL
3.6 KiB
JavaScript

import { del } from '@vercel/blob';
import { sql } from '@vercel/postgres';
import { getUserFromRequest } from '../../../lib/permission-middleware';
export default async function handler(req, res) {
if (req.method !== 'DELETE') {
return res.status(405).json({ error: 'Method not allowed' });
}
try {
// Get authenticated user
const user = await getUserFromRequest(req);
if (!user) {
return res.status(401).json({ error: 'Authentication required' });
}
// Prevent admin users from deleting their own accounts
if (user.role === 'admin') {
return res.status(403).json({
error: 'Admin accounts cannot be self-deleted. Please contact another administrator.'
});
}
try {
// Start transaction-like cleanup
console.log(`Starting account deletion for user ${user.userId}`);
// 1. Delete user avatars from Vercel Blob
const avatarsResult = await sql`
SELECT file_path FROM user_avatars
WHERE user_id = ${user.userId} AND is_active = true
`;
for (const avatar of avatarsResult.rows) {
try {
await del(avatar.file_path);
console.log(`Deleted avatar: ${avatar.file_path}`);
} catch (blobError) {
console.warn(`Failed to delete avatar blob: ${avatar.file_path}`, blobError);
// Continue with deletion even if blob cleanup fails
}
}
// 2. Delete user data in correct order (respecting foreign key constraints)
// Delete deck cards first
await sql`DELETE FROM deck_cards WHERE deck_id IN (SELECT id FROM decks WHERE user_id = ${user.userId})`;
console.log('Deleted deck cards');
// Delete decks
await sql`DELETE FROM decks WHERE user_id = ${user.userId}`;
console.log('Deleted decks');
// Delete collection cards
await sql`DELETE FROM collection_cards WHERE collection_id IN (SELECT id FROM collections WHERE user_id = ${user.userId})`;
console.log('Deleted collection cards');
// Delete collections
await sql`DELETE FROM collections WHERE user_id = ${user.userId}`;
console.log('Deleted collections');
// Delete user cards
await sql`DELETE FROM user_cards WHERE user_id = ${user.userId}`;
console.log('Deleted user cards');
// Delete user avatars records
await sql`DELETE FROM user_avatars WHERE user_id = ${user.userId}`;
console.log('Deleted user avatar records');
// Delete user settings
await sql`DELETE FROM user_settings WHERE user_id = ${user.userId}`;
console.log('Deleted user settings');
// Finally, delete the user account
const deleteResult = await sql`DELETE FROM users WHERE id = ${user.userId}`;
console.log('Deleted user account');
if (deleteResult.rowCount === 0) {
return res.status(404).json({ error: 'User not found' });
}
console.log(`Successfully deleted account for user ${user.userId}`);
res.status(200).json({
message: 'Account deleted successfully. All your data has been permanently removed.'
});
} catch (deleteError) {
console.error('Account deletion error:', deleteError);
// Check if it's a foreign key constraint error
if (deleteError.code === '23503') {
return res.status(400).json({
error: 'Cannot delete account due to data dependencies. Please contact support.'
});
}
res.status(500).json({ error: 'Failed to delete account. Please try again or contact support.' });
}
} catch (error) {
console.error('Account deletion API error:', error);
res.status(500).json({ error: 'Internal server error' });
}
}