41 lines
1.2 KiB
TypeScript
41 lines
1.2 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import { getServerSession } from 'next-auth';
|
|
import { authOptions } from "@/app/api/auth/options";
|
|
import { getMicrosoftAuthUrl } from '@/lib/services/microsoft-oauth';
|
|
|
|
// Endpoint to initiate Microsoft OAuth flow
|
|
export async function GET(request: Request) {
|
|
try {
|
|
// Authenticate user
|
|
const session = await getServerSession(authOptions);
|
|
if (!session?.user?.id) {
|
|
return NextResponse.json(
|
|
{ error: 'Unauthorized' },
|
|
{ status: 401 }
|
|
);
|
|
}
|
|
|
|
// Create a state parameter with the user's ID to prevent CSRF
|
|
const state = Buffer.from(JSON.stringify({
|
|
userId: session.user.id,
|
|
timestamp: Date.now()
|
|
})).toString('base64');
|
|
|
|
// Generate the authorization URL
|
|
const authUrl = getMicrosoftAuthUrl(state);
|
|
|
|
return NextResponse.json({
|
|
authUrl,
|
|
state
|
|
});
|
|
} catch (error) {
|
|
console.error('Error initiating Microsoft OAuth flow:', error);
|
|
return NextResponse.json(
|
|
{
|
|
error: 'Failed to initiate Microsoft OAuth flow',
|
|
details: error instanceof Error ? error.message : 'Unknown error'
|
|
},
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|