panel 2 courier api restore
This commit is contained in:
parent
91994cd7e2
commit
8a4a18c1c7
@ -3,129 +3,147 @@ import { ImapFlow } from 'imapflow';
|
|||||||
import { getServerSession } from 'next-auth';
|
import { getServerSession } from 'next-auth';
|
||||||
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
|
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
|
||||||
import { prisma } from '@/lib/prisma';
|
import { prisma } from '@/lib/prisma';
|
||||||
import { LRUCache } from 'lru-cache';
|
|
||||||
|
|
||||||
// Simple in-memory cache for email content
|
export async function POST(request: Request) {
|
||||||
const emailContentCache = new LRUCache<string, any>({
|
|
||||||
max: 100,
|
|
||||||
ttl: 1000 * 60 * 15, // 15 minutes
|
|
||||||
});
|
|
||||||
|
|
||||||
export async function GET(
|
|
||||||
request: Request,
|
|
||||||
{ params }: { params: { id: string } }
|
|
||||||
) {
|
|
||||||
try {
|
try {
|
||||||
// 1. Properly await params to avoid Next.js error
|
console.log('Processing login POST request');
|
||||||
const { id } = await Promise.resolve(params);
|
|
||||||
|
|
||||||
// 2. Authentication check
|
|
||||||
const session = await getServerSession(authOptions);
|
const session = await getServerSession(authOptions);
|
||||||
if (!session?.user?.id) {
|
if (!session?.user?.id) {
|
||||||
|
console.log('No authenticated session found');
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: 'Unauthorized' },
|
{ error: 'Unauthorized' },
|
||||||
{ status: 401 }
|
{ status: 401 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. Check cache first
|
const { email, password, host, port } = await request.json();
|
||||||
const cacheKey = `email:${session.user.id}:${id}`;
|
console.log('Login attempt for:', email, 'to server:', host);
|
||||||
const cachedEmail = emailContentCache.get(cacheKey);
|
|
||||||
if (cachedEmail) {
|
|
||||||
return NextResponse.json(cachedEmail);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 4. Get credentials from database
|
if (!email || !password || !host || !port) {
|
||||||
const credentials = await prisma.mailCredentials.findUnique({
|
console.log('Missing required login fields');
|
||||||
where: {
|
|
||||||
userId: session.user.id
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!credentials) {
|
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: 'No mail credentials found. Please configure your email account.' },
|
{ error: 'Missing required fields' },
|
||||||
{ status: 401 }
|
{ status: 400 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 5. Create IMAP client
|
// Test IMAP connection
|
||||||
|
console.log('Testing IMAP connection to:', host, port);
|
||||||
const client = new ImapFlow({
|
const client = new ImapFlow({
|
||||||
host: credentials.host,
|
host: host,
|
||||||
port: credentials.port,
|
port: parseInt(port),
|
||||||
secure: true,
|
secure: true,
|
||||||
auth: {
|
auth: {
|
||||||
user: credentials.email,
|
user: email,
|
||||||
pass: credentials.password,
|
pass: password,
|
||||||
},
|
},
|
||||||
logger: false,
|
logger: false,
|
||||||
emitLogs: false,
|
emitLogs: false,
|
||||||
tls: {
|
tls: {
|
||||||
rejectUnauthorized: false
|
rejectUnauthorized: false
|
||||||
},
|
}
|
||||||
disableAutoIdle: true
|
|
||||||
});
|
});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await client.connect();
|
await client.connect();
|
||||||
|
console.log('IMAP connection successful');
|
||||||
// 6. Open INBOX
|
|
||||||
await client.mailboxOpen('INBOX');
|
await client.mailboxOpen('INBOX');
|
||||||
|
console.log('INBOX opened successfully');
|
||||||
|
|
||||||
// 7. Fetch the email with UID search
|
// Store or update credentials in database
|
||||||
const options = {
|
await prisma.mailCredentials.upsert({
|
||||||
uid: true, // This is crucial - we must specify uid:true to fetch by UID
|
where: {
|
||||||
source: true,
|
userId: session.user.id
|
||||||
envelope: true,
|
},
|
||||||
bodyStructure: true,
|
update: {
|
||||||
flags: true
|
email,
|
||||||
};
|
password,
|
||||||
|
host,
|
||||||
|
port: parseInt(port)
|
||||||
|
},
|
||||||
|
create: {
|
||||||
|
userId: session.user.id,
|
||||||
|
email,
|
||||||
|
password,
|
||||||
|
host,
|
||||||
|
port: parseInt(port)
|
||||||
|
}
|
||||||
|
});
|
||||||
|
console.log('Credentials stored in database');
|
||||||
|
|
||||||
// Fetch by UID
|
return NextResponse.json({ success: true });
|
||||||
console.log('Fetching email with UID:', id);
|
} catch (error) {
|
||||||
const message = await client.fetchOne(id, options);
|
console.error('IMAP connection error:', error);
|
||||||
|
if (error instanceof Error) {
|
||||||
if (!message) {
|
if (error.message.includes('Invalid login')) {
|
||||||
console.error('Email not found with UID:', id);
|
return NextResponse.json(
|
||||||
|
{ error: 'Invalid login or password' },
|
||||||
|
{ status: 401 }
|
||||||
|
);
|
||||||
|
}
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: 'Email not found' },
|
{ error: `IMAP connection error: ${error.message}` },
|
||||||
{ status: 404 }
|
{ status: 500 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
return NextResponse.json(
|
||||||
// 8. Parse the email content
|
{ error: 'Failed to connect to email server' },
|
||||||
const emailContent = {
|
{ status: 500 }
|
||||||
id: message.uid.toString(),
|
);
|
||||||
from: message.envelope.from?.[0]?.address || '',
|
|
||||||
fromName: message.envelope.from?.[0]?.name ||
|
|
||||||
message.envelope.from?.[0]?.address?.split('@')[0] || '',
|
|
||||||
to: message.envelope.to?.map((addr: any) => addr.address).join(', ') || '',
|
|
||||||
subject: message.envelope.subject || '(No subject)',
|
|
||||||
date: message.envelope.date?.toISOString() || new Date().toISOString(),
|
|
||||||
content: message.source?.toString() || '',
|
|
||||||
read: message.flags.has('\\Seen'),
|
|
||||||
starred: message.flags.has('\\Flagged'),
|
|
||||||
flags: Array.from(message.flags),
|
|
||||||
hasAttachments: message.bodyStructure?.type === 'multipart'
|
|
||||||
};
|
|
||||||
|
|
||||||
// 9. Cache the email content
|
|
||||||
emailContentCache.set(cacheKey, emailContent);
|
|
||||||
|
|
||||||
// 10. Return the email content
|
|
||||||
return NextResponse.json(emailContent);
|
|
||||||
} finally {
|
} finally {
|
||||||
// 11. Close the connection
|
|
||||||
try {
|
try {
|
||||||
await client.logout();
|
await client.logout();
|
||||||
|
console.log('IMAP client logged out');
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('Error during IMAP logout:', e);
|
console.error('Error during logout:', e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error fetching email:', error);
|
console.error('Error in login handler:', error);
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: 'Failed to fetch email content' },
|
{ error: 'An unexpected error occurred' },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
try {
|
||||||
|
console.log('Fetching mail credentials');
|
||||||
|
const session = await getServerSession(authOptions);
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
console.log('No authenticated session found');
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'Unauthorized' },
|
||||||
|
{ status: 401 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const credentials = await prisma.mailCredentials.findUnique({
|
||||||
|
where: {
|
||||||
|
userId: session.user.id
|
||||||
|
},
|
||||||
|
select: {
|
||||||
|
email: true,
|
||||||
|
host: true,
|
||||||
|
port: true
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!credentials) {
|
||||||
|
console.log('No mail credentials found for user');
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'No stored credentials found' },
|
||||||
|
{ status: 404 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('Credentials found for:', credentials.email);
|
||||||
|
return NextResponse.json(credentials);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching credentials:', error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'Failed to retrieve credentials' },
|
||||||
{ status: 500 }
|
{ status: 500 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user