91 lines
2.3 KiB
TypeScript
91 lines
2.3 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import Imap from 'imap';
|
|
|
|
interface StoredCredentials {
|
|
user: string;
|
|
password: string;
|
|
host: string;
|
|
port: string;
|
|
}
|
|
|
|
export let storedCredentials: StoredCredentials | null = null;
|
|
|
|
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
|
|
storedCredentials = { user: email, password, host, port };
|
|
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() {
|
|
if (!storedCredentials) {
|
|
return NextResponse.json(
|
|
{ error: 'No stored credentials found' },
|
|
{ status: 404 }
|
|
);
|
|
}
|
|
|
|
// Return credentials without password
|
|
const { password, ...safeCredentials } = storedCredentials;
|
|
return NextResponse.json(safeCredentials);
|
|
}
|