Files
shahikitchen-prod/app/api/auth/google/route.ts
T

56 lines
1.5 KiB
TypeScript

import { NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import {
buildGoogleAuthUrl,
createOAuthState,
isGoogleOAuthConfigured,
} from '@/infrastructure/auth/google-oauth';
import {
getOAuthReturnCookieName,
sanitizeOAuthReturnPath,
} from '@/infrastructure/auth/oauth-return';
export const dynamic = 'force-dynamic';
const OAUTH_STATE_COOKIE = 'shahi_google_oauth_state';
export async function GET(request: Request) {
if (!isGoogleOAuthConfigured()) {
return NextResponse.redirect(new URL('/login?tab=customer&error=google_not_configured', getOrigin(request)));
}
const url = new URL(request.url);
const returnTo = sanitizeOAuthReturnPath(url.searchParams.get('returnTo'));
const state = createOAuthState();
const cookieStore = await cookies();
cookieStore.set(OAUTH_STATE_COOKIE, state, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
path: '/',
maxAge: 600,
});
cookieStore.set(getOAuthReturnCookieName(), returnTo, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
path: '/',
maxAge: 600,
});
return NextResponse.redirect(buildGoogleAuthUrl(state, request));
}
function getOrigin(req?: Request): string {
if (req) {
try {
const url = new URL(req.url);
if (process.env.NODE_ENV === 'production' && url.protocol === 'http:') {
url.protocol = 'https:';
}
return url.origin;
} catch {}
}
return process.env.NEXT_PUBLIC_SITE_URL ?? 'http://localhost:3000';
}