Neah/app/api/mail/login/route.ts
2025-04-17 13:30:04 +02:00

114 lines
2.8 KiB
TypeScript

import { NextResponse } from 'next/server';
import { ImapFlow } from 'imapflow';
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 client = new ImapFlow({
host,
port: parseInt(port),
secure: true,
auth: {
user: email,
pass: password,
},
logger: false,
emitLogs: false
});
try {
await client.connect();
await client.mailboxOpen('INBOX');
// 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
});
return NextResponse.json({ success: true });
} catch (error) {
if (error instanceof Error) {
if (error.message.includes('Invalid login')) {
return NextResponse.json(
{ error: 'Invalid login or password' },
{ status: 401 }
);
}
return NextResponse.json(
{ error: `IMAP connection error: ${error.message}` },
{ status: 500 }
);
}
return NextResponse.json(
{ error: 'Failed to connect to email server' },
{ status: 500 }
);
} finally {
try {
await client.logout();
} catch (e) {
console.error('Error during logout:', e);
}
}
} catch (error) {
console.error('Error in login handler:', error);
return NextResponse.json(
{ error: 'An unexpected 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 }
);
}
}