96 lines
3.2 KiB
TypeScript
96 lines
3.2 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server';
|
|
import { getServerSession } from 'next-auth';
|
|
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
|
|
import { prisma } from '@/lib/prisma';
|
|
import { getTokens, getUserCalendars } from '@/lib/outlook-calendar';
|
|
|
|
export async function GET(request: NextRequest) {
|
|
try {
|
|
const session = await getServerSession(authOptions);
|
|
|
|
if (!session?.user?.email) {
|
|
return NextResponse.redirect(new URL('/auth/login', request.url));
|
|
}
|
|
|
|
const { searchParams } = new URL(request.url);
|
|
const code = searchParams.get('code');
|
|
const error = searchParams.get('error');
|
|
|
|
if (error) {
|
|
console.error('Outlook OAuth error:', error);
|
|
return NextResponse.redirect(new URL('/?error=outlook_auth_failed', request.url));
|
|
}
|
|
|
|
if (!code) {
|
|
return NextResponse.redirect(new URL('/?error=no_code', request.url));
|
|
}
|
|
|
|
// Exchange code for tokens
|
|
const tokenData = await getTokens(code);
|
|
const accessToken = tokenData.access_token;
|
|
const refreshToken = tokenData.refresh_token;
|
|
const expiresIn = tokenData.expires_in;
|
|
|
|
// Fetch user's calendars to store initial list
|
|
const calendars = await getUserCalendars(accessToken);
|
|
|
|
const user = await prisma.user.findUnique({
|
|
where: { email: session.user.email }
|
|
});
|
|
|
|
if (!user) {
|
|
return NextResponse.redirect(new URL('/auth/login', request.url));
|
|
}
|
|
|
|
// Calculate expiry date
|
|
const expiresAt = new Date();
|
|
expiresAt.setSeconds(expiresAt.getSeconds() + expiresIn);
|
|
|
|
// Check for existing connection
|
|
const existingConnection = await prisma.calendarConnection.findFirst({
|
|
where: {
|
|
userId: user.id,
|
|
provider: 'outlook'
|
|
}
|
|
});
|
|
|
|
const calendarData = calendars.map(cal => ({
|
|
id: cal.id,
|
|
title: cal.name,
|
|
isPrimary: cal.isDefaultCalendar,
|
|
selected: true,
|
|
editable: cal.canEdit
|
|
}));
|
|
|
|
if (existingConnection) {
|
|
await prisma.calendarConnection.update({
|
|
where: { id: existingConnection.id },
|
|
data: {
|
|
accessToken,
|
|
refreshToken,
|
|
expiresAt,
|
|
calendars: calendarData,
|
|
updatedAt: new Date()
|
|
}
|
|
});
|
|
} else {
|
|
// Create new connection
|
|
await prisma.calendarConnection.create({
|
|
data: {
|
|
userId: user.id,
|
|
provider: 'outlook',
|
|
accessToken,
|
|
refreshToken,
|
|
expiresAt,
|
|
calendars: calendarData,
|
|
}
|
|
});
|
|
}
|
|
|
|
return NextResponse.redirect(new URL('/tasks?calendar=connected', request.url));
|
|
} catch (error) {
|
|
console.error('Error in Outlook callback:', error);
|
|
return NextResponse.redirect(new URL('/auth/login?error=outlook_callback_failed', request.url));
|
|
}
|
|
}
|