Neah/app/api/courrier/login/route.ts
2025-04-26 09:14:44 +02:00

102 lines
2.5 KiB
TypeScript

import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
import {
saveUserEmailCredentials,
getUserEmailCredentials,
testEmailConnection
} from '@/lib/services/email-service';
export async function POST(request: Request) {
try {
// Authenticate user
const session = await getServerSession(authOptions);
if (!session?.user?.id) {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
);
}
// Get credentials from request
const { email, password, host, port } = await request.json();
// Validate required fields
if (!email || !password || !host || !port) {
return NextResponse.json(
{ error: 'Missing required fields' },
{ status: 400 }
);
}
// Test connection before saving
const connectionSuccess = await testEmailConnection({
email,
password,
host,
port: parseInt(port)
});
if (!connectionSuccess) {
return NextResponse.json(
{ error: 'Failed to connect to email server. Please check your credentials.' },
{ status: 401 }
);
}
// Save credentials in the database
await saveUserEmailCredentials(session.user.id, {
email,
password,
host,
port: parseInt(port)
});
return NextResponse.json({ success: true });
} catch (error) {
console.error('Error in login handler:', error);
return NextResponse.json(
{
error: 'An unexpected error occurred',
details: error instanceof Error ? error.message : 'Unknown error'
},
{ status: 500 }
);
}
}
export async function GET() {
try {
// Authenticate user
const session = await getServerSession(authOptions);
if (!session?.user?.id) {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
);
}
// Get user credentials from database
const credentials = await getUserEmailCredentials(session.user.id);
if (!credentials) {
return NextResponse.json(
{ error: 'No stored credentials found' },
{ status: 404 }
);
}
// Return credentials without the password
return NextResponse.json({
email: credentials.email,
host: credentials.host,
port: credentials.port
});
} catch (error) {
console.error('Error fetching credentials:', error);
return NextResponse.json(
{ error: 'Failed to retrieve credentials' },
{ status: 500 }
);
}
}