11import { NextResponse } from 'next/server' ;
22import { createServerClient } from '@supabase/ssr' ;
33import { cookies } from 'next/headers' ;
4+ import { logSecurityEventDirect } from '../../security-actions' ;
45
56export async function GET ( request : Request ) {
67 const requestUrl = new URL ( request . url ) ;
@@ -17,6 +18,14 @@ export async function GET(request: Request) {
1718 const { searchParams } = requestUrl ;
1819 const code = searchParams . get ( 'code' ) ;
1920 const next = searchParams . get ( 'next' ) || '/admin' ;
21+ const provider = searchParams . get ( 'provider' ) ;
22+
23+ const forwardedFor = request . headers . get ( 'x-forwarded-for' ) ;
24+ const ip =
25+ forwardedFor ?. split ( ',' ) [ 0 ] . trim ( ) ||
26+ request . headers . get ( 'x-real-ip' ) ||
27+ 'unknown' ;
28+ const ua = request . headers . get ( 'user-agent' ) ;
2029
2130 if ( code ) {
2231 const cookieStore = await cookies ( ) ;
@@ -41,13 +50,33 @@ export async function GET(request: Request) {
4150 }
4251 ) ;
4352
44- const { error } = await supabase . auth . exchangeCodeForSession ( code ) ;
45- if ( ! error ) {
53+ const { data, error } = await supabase . auth . exchangeCodeForSession ( code ) ;
54+ if ( ! error && data . user ) {
55+ logSecurityEventDirect (
56+ process . env . NEXT_PUBLIC_SUPABASE_URL ! ,
57+ process . env . SUPABASE_SERVICE_ROLE_KEY || '' ,
58+ 'oauth_login' ,
59+ data . user . id ,
60+ ip ,
61+ ua ,
62+ { status : 'Success' , metadata : { provider : provider || 'unknown' } }
63+ ) . catch ( ( ) => { } ) ;
64+
4665 const redirectUrl = new URL ( next , origin ) ;
4766 return NextResponse . redirect ( redirectUrl . toString ( ) ) ;
4867 }
68+
69+ // Log failed OAuth exchange
70+ logSecurityEventDirect (
71+ process . env . NEXT_PUBLIC_SUPABASE_URL ! ,
72+ process . env . SUPABASE_SERVICE_ROLE_KEY || '' ,
73+ 'login_failed' ,
74+ '00000000-0000-0000-0000-000000000000' ,
75+ ip ,
76+ ua ,
77+ { status : 'Failed' , metadata : { method : 'oauth' , provider : provider || 'unknown' , reason : error ?. message || 'code_exchange_failed' } }
78+ ) . catch ( ( ) => { } ) ;
4979 }
5080
51- // Return the user to an error page with instructions
5281 return NextResponse . redirect ( new URL ( '/admin/login?error=auth_failed' , origin ) . toString ( ) ) ;
5382}
0 commit comments