deckhearth/pages/api/user/delete.js
Randall Stillwell a7ee884d02 🖼️ Complete Avatar Upload System with Vercel Blob
📤 Avatar Upload API (/api/user/avatar):
- File upload with multipart form data parsing
- Comprehensive validation (file type, size limits)
- Support for JPEG, PNG, GIF, WebP images up to 5MB
- Automatic cleanup of old avatars before new uploads
- Vercel Blob integration with public access
- Database tracking in user_avatars table
- Error handling for upload failures

🎨 Avatar Generation API (/api/user/avatar/generate):
- Custom avatar generation using DiceBear API
- Fire-themed color scheme (matching app branding)
- Personalized based on user initials/username/email
- SVG format for crisp display at any size
- Automatic fallback if generation fails
- Same cleanup and storage workflow as uploads

🗑️ Account Deletion API (/api/user/delete):
- Complete user data cleanup including Vercel Blob files
- Cascading deletion respecting foreign key constraints
- Admin account protection (prevents self-deletion)
- Comprehensive cleanup order:
  * User avatars from Vercel Blob storage
  * Deck cards, decks, collection cards, collections
  * User cards, avatar records, settings
  * Finally the user account itself
- Detailed logging for audit trail
- Graceful error handling with specific error messages

🔧 Technical Features:
- Custom multipart form data parser for file uploads
- Vercel Blob put/del operations with error handling
- Unique filename generation with timestamps
- Database transaction-like cleanup for deletions
- File type validation and size limits
- Proper CORS headers for all endpoints

🎯 Integration Ready:
- Works seamlessly with existing profile page UI
- Supports both upload and generate avatar buttons
- Returns avatar URLs for immediate display
- Database consistency with user profile system
- Production-ready error handling and validation

The avatar system is now fully functional with Vercel Blob! 📸
2025-07-26 21:39:42 -05:00

115 lines
No EOL
4 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) {
// Set CORS headers
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
// Handle preflight requests
if (req.method === 'OPTIONS') {
res.status(200).end();
return;
}
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' });
}
}