Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 | /** * Email Unsubscribe API * * Handles one-click unsubscribe from marketing emails. * Redirects to success or error page after processing. */ import { NextRequest, NextResponse } from 'next/server'; import { prisma } from '@/lib/prisma'; import { verifyUnsubscribeToken, isValidUnsubscribeType } from '@/lib/email/tokens'; import { logger } from '@/lib/logging'; // Prevent static generation export const dynamic = 'force-dynamic'; /** * GET /api/email/unsubscribe?token=xxx&type=all * * Process unsubscribe request from email link */ export async function GET(request: NextRequest): Promise<NextResponse> { const { searchParams } = new URL(request.url); const token = searchParams.get('token'); const typeParam = searchParams.get('type'); const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || process.env.NEXTAUTH_URL || 'http://localhost:3000'; // Validate token is present if (!token) { logger.warn('Unsubscribe attempt without token', { category: 'EMAIL' }); return NextResponse.redirect(`${baseUrl}/unsubscribe-error?reason=missing-token`); } // Verify and decode token const payload = verifyUnsubscribeToken(token); if (!payload) { logger.warn('Invalid or expired unsubscribe token', { category: 'EMAIL' }); return NextResponse.redirect(`${baseUrl}/unsubscribe-error?reason=invalid-token`); } // Use type from query param if valid, otherwise use type from token const unsubscribeType = (typeParam && isValidUnsubscribeType(typeParam)) ? typeParam : payload.type; try { // Build update data based on type const updateData: Record<string, boolean> = {}; switch (unsubscribeType) { case 'all': updateData.unsubscribeAll = true; updateData.promotions = false; updateData.newsletters = false; updateData.productAlerts = false; break; case 'promotions': updateData.promotions = false; break; case 'newsletters': updateData.newsletters = false; break; case 'productAlerts': updateData.productAlerts = false; break; } // Update or create email preferences await prisma.emailPreference.upsert({ where: { userId: payload.userId }, create: { userId: payload.userId, ...updateData }, update: updateData }); logger.info(`User ${payload.userId} unsubscribed from ${unsubscribeType} emails`, { category: 'EMAIL' }); // Redirect to success page return NextResponse.redirect( `${baseUrl}/unsubscribe-success?type=${unsubscribeType}` ); } catch (error) { logger.error('Unsubscribe failed', error instanceof Error ? error : new Error(String(error)), { category: 'EMAIL' }); return NextResponse.redirect(`${baseUrl}/unsubscribe-error?reason=server-error`); } } /** * POST /api/email/unsubscribe * * Alternative method for unsubscribe (for forms) */ export async function POST(request: NextRequest): Promise<NextResponse> { try { const body = await request.json(); const { token, type } = body; if (!token) { return NextResponse.json( { error: 'Missing token' }, { status: 400 } ); } const payload = verifyUnsubscribeToken(token); if (!payload) { return NextResponse.json( { error: 'Invalid or expired token' }, { status: 400 } ); } const unsubscribeType = (type && isValidUnsubscribeType(type)) ? type : payload.type; // Build update data const updateData: Record<string, boolean> = {}; switch (unsubscribeType) { case 'all': updateData.unsubscribeAll = true; updateData.promotions = false; updateData.newsletters = false; updateData.productAlerts = false; break; case 'promotions': updateData.promotions = false; break; case 'newsletters': updateData.newsletters = false; break; case 'productAlerts': updateData.productAlerts = false; break; } await prisma.emailPreference.upsert({ where: { userId: payload.userId }, create: { userId: payload.userId, ...updateData }, update: updateData }); logger.info(`User ${payload.userId} unsubscribed from ${unsubscribeType} emails (POST)`, { category: 'EMAIL' }); return NextResponse.json({ success: true, message: `Successfully unsubscribed from ${unsubscribeType} emails` }); } catch (error) { logger.error('Unsubscribe POST failed', error instanceof Error ? error : new Error(String(error)), { category: 'EMAIL' }); return NextResponse.json( { error: 'Failed to process unsubscribe request' }, { status: 500 } ); } } |