database wf 14

This commit is contained in:
alma 2025-04-17 13:44:57 +02:00
parent ec8304cd38
commit 264842e9d3
3 changed files with 95 additions and 51 deletions

View File

@ -1,16 +1,19 @@
import { NextResponse } from 'next/server'; import { NextResponse } from 'next/server';
import { ImapFlow } from 'imapflow'; import { ImapFlow } from 'imapflow';
import { cookies } from 'next/headers'; import { getServerSession } from 'next-auth';
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
interface StoredCredentials { import { prisma } from '@/lib/prisma';
email: string;
password: string;
host: string;
port: number;
}
export async function POST(request: Request) { export async function POST(request: Request) {
try { try {
const session = await getServerSession(authOptions);
if (!session?.user?.id) {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
);
}
const { email, password, host, port } = await request.json(); const { email, password, host, port } = await request.json();
if (!email || !password || !host || !port) { if (!email || !password || !host || !port) {
@ -37,22 +40,24 @@ export async function POST(request: Request) {
await client.connect(); await client.connect();
await client.mailboxOpen('INBOX'); await client.mailboxOpen('INBOX');
// Store credentials in cookie // Store or update credentials in database
const cookieStore = cookies(); await prisma.mailCredentials.upsert({
const credentials: StoredCredentials = { where: {
userId: session.user.id
},
update: {
email, email,
password, password,
host, host,
port: parseInt(port) port: parseInt(port)
}; },
create: {
// Set the cookie with proper security options userId: session.user.id,
cookieStore.set('imap_credentials', JSON.stringify(credentials), { email,
httpOnly: true, password,
secure: process.env.NODE_ENV === 'production', host,
sameSite: 'lax', port: parseInt(port)
path: '/', }
maxAge: 30 * 24 * 60 * 60 // 30 days
}); });
return NextResponse.json({ success: true }); return NextResponse.json({ success: true });
@ -90,25 +95,38 @@ export async function POST(request: Request) {
} }
export async function GET() { export async function GET() {
const cookieStore = cookies(); try {
const credentialsCookie = cookieStore.get('imap_credentials'); const session = await getServerSession(authOptions);
if (!session?.user?.id) {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
);
}
if (!credentialsCookie?.value) { const credentials = await prisma.mailCredentials.findUnique({
where: {
userId: session.user.id
},
select: {
email: true,
host: true,
port: true
}
});
if (!credentials) {
return NextResponse.json( return NextResponse.json(
{ error: 'No stored credentials found' }, { error: 'No stored credentials found' },
{ status: 404 } { status: 404 }
); );
} }
try { return NextResponse.json(credentials);
const credentials = JSON.parse(credentialsCookie.value);
// Return credentials without password for security
const { password, ...safeCredentials } = credentials;
return NextResponse.json(safeCredentials);
} catch (error) { } catch (error) {
return NextResponse.json( return NextResponse.json(
{ error: 'Invalid credentials format' }, { error: 'Failed to retrieve credentials' },
{ status: 400 } { status: 500 }
); );
} }
} }

View File

@ -1,30 +1,41 @@
import { NextResponse } from 'next/server'; import { NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { ImapFlow } from 'imapflow'; import { ImapFlow } from 'imapflow';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
import { prisma } from '@/lib/prisma';
export async function GET() { export async function GET() {
try { try {
const cookieStore = cookies(); const session = await getServerSession(authOptions);
const credentials = cookieStore.get('imap_credentials'); if (!session?.user?.id) {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
);
}
const credentials = await prisma.mailCredentials.findUnique({
where: {
userId: session.user.id
}
});
if (!credentials) { if (!credentials) {
return NextResponse.json( return NextResponse.json(
{ error: 'No credentials found. Please login to your email account first.' }, { error: 'No mail credentials found. Please configure your email account.' },
{ status: 401 } { status: 401 }
); );
} }
let client; let client;
try { try {
const { email, password, host, port } = JSON.parse(credentials.value);
client = new ImapFlow({ client = new ImapFlow({
host, host: credentials.host,
port: parseInt(port), port: credentials.port,
secure: true, secure: true,
auth: { auth: {
user: email, user: credentials.email,
pass: password, pass: credentials.password,
}, },
logger: false, logger: false,
emitLogs: false emitLogs: false
@ -50,7 +61,7 @@ export async function GET() {
if (error instanceof Error) { if (error instanceof Error) {
if (error.message.includes('Invalid login')) { if (error.message.includes('Invalid login')) {
return NextResponse.json( return NextResponse.json(
{ error: 'Invalid email credentials. Please login again.' }, { error: 'Invalid email credentials. Please update your email settings.' },
{ status: 401 } { status: 401 }
); );
} }

View File

@ -19,6 +19,7 @@ model User {
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
calendars Calendar[] calendars Calendar[]
events Event[] events Event[]
mailCredentials MailCredentials?
} }
model Calendar { model Calendar {
@ -53,3 +54,17 @@ model Event {
@@index([calendarId]) @@index([calendarId])
@@index([userId]) @@index([userId])
} }
model MailCredentials {
id String @id @default(uuid())
userId String @unique
email String
password String
host String
port Int
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@index([userId])
}