← back to Dear Bubbe Nextjs
app/api/delete-account/route.ts
93 lines
import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import fs from 'fs/promises'
import path from 'path'
export async function DELETE(request: NextRequest) {
try {
// Get the user session
const session = await getServerSession(authOptions)
if (!session || !session.user?.email) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const userEmail = session.user.email
console.log(`[DELETE ACCOUNT] Processing deletion for: ${userEmail}`)
// Define data directories
const profilesDir = path.join(process.cwd(), 'data', 'profiles')
const emailsDir = path.join(process.cwd(), 'data', 'emails')
const discountsDir = path.join(process.cwd(), 'data', 'discounts')
// Delete user profile
const profilePath = path.join(profilesDir, `${userEmail}.json`)
try {
await fs.unlink(profilePath)
console.log(`[DELETE ACCOUNT] Deleted profile: ${profilePath}`)
} catch (error) {
console.log(`[DELETE ACCOUNT] No profile found for ${userEmail}`)
}
// Delete user emails
try {
const emailFiles = await fs.readdir(emailsDir)
for (const file of emailFiles) {
if (file.includes(userEmail.replace('@', '_at_'))) {
await fs.unlink(path.join(emailsDir, file))
console.log(`[DELETE ACCOUNT] Deleted email record: ${file}`)
}
}
} catch (error) {
console.log(`[DELETE ACCOUNT] No emails found for ${userEmail}`)
}
// Delete user discount codes
try {
const discountFiles = await fs.readdir(discountsDir)
for (const file of discountFiles) {
const discountPath = path.join(discountsDir, file)
const content = await fs.readFile(discountPath, 'utf-8')
const discount = JSON.parse(content)
if (discount.email === userEmail) {
await fs.unlink(discountPath)
console.log(`[DELETE ACCOUNT] Deleted discount: ${file}`)
}
}
} catch (error) {
console.log(`[DELETE ACCOUNT] No discounts found for ${userEmail}`)
}
// Clear local storage items (client-side will handle this)
// Log the deletion for audit purposes
const deletionLog = {
email: userEmail,
deletedAt: new Date().toISOString(),
ip: request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip') || 'unknown'
}
const logsDir = path.join(process.cwd(), 'data', 'deletion-logs')
try {
await fs.mkdir(logsDir, { recursive: true })
const logFile = path.join(logsDir, `${Date.now()}_${userEmail}.json`)
await fs.writeFile(logFile, JSON.stringify(deletionLog, null, 2))
} catch (error) {
console.error('[DELETE ACCOUNT] Failed to write deletion log:', error)
}
console.log(`[DELETE ACCOUNT] ✅ Successfully deleted all data for: ${userEmail}`)
return NextResponse.json({
success: true,
message: 'Account and all associated data have been deleted'
})
} catch (error) {
console.error('[DELETE ACCOUNT] Error:', error)
return NextResponse.json({
error: 'Failed to delete account',
details: error instanceof Error ? error.message : 'Unknown error'
}, { status: 500 })
}
}