import { NextResponse } from 'next/server'; import Imap from 'imap'; import { cookies } from 'next/headers'; interface StoredCredentials { email: string; password: string; host: string; port: number; } export async function POST(request: Request) { try { const { email, password, host, port } = await request.json(); if (!email || !password || !host || !port) { return NextResponse.json( { error: 'Missing required fields' }, { status: 400 } ); } // Test IMAP connection const imap = new Imap({ user: email, password, host, port: parseInt(port), tls: true, tlsOptions: { rejectUnauthorized: false, servername: host }, authTimeout: 10000, connTimeout: 10000, debug: console.log }); return new Promise((resolve, reject) => { imap.once('ready', () => { imap.end(); // Store credentials in cookie const cookieStore = cookies(); const credentials: StoredCredentials = { email, password, host, port: parseInt(port) }; // Set the cookie with proper security options cookieStore.set('imap_credentials', JSON.stringify(credentials), { httpOnly: true, secure: process.env.NODE_ENV === 'production', sameSite: 'lax', path: '/', maxAge: 30 * 24 * 60 * 60 // 30 days }); resolve(NextResponse.json({ success: true })); }); imap.once('error', (err: Error) => { imap.end(); if (err.message.includes('Invalid login or password')) { reject(new Error('Invalid login or password')); } else { reject(new Error(`IMAP connection error: ${err.message}`)); } }); imap.connect(); }); } catch (error) { console.error('Error in login handler:', error); if (error instanceof Error) { if (error.message.includes('Invalid login or password')) { return NextResponse.json( { error: 'Invalid login or password', details: error.message }, { status: 401 } ); } return NextResponse.json( { error: 'Failed to connect to email server', details: error.message }, { status: 500 } ); } return NextResponse.json( { error: 'Unknown error occurred' }, { status: 500 } ); } } export async function GET() { const cookieStore = cookies(); const credentialsCookie = cookieStore.get('imap_credentials'); if (!credentialsCookie?.value) { return NextResponse.json( { error: 'No stored credentials found' }, { status: 404 } ); } try { const credentials = JSON.parse(credentialsCookie.value); // Return credentials without password for security const { password, ...safeCredentials } = credentials; return NextResponse.json(safeCredentials); } catch (error) { return NextResponse.json( { error: 'Invalid credentials format' }, { status: 400 } ); } }