88 lines
2.6 KiB
TypeScript
88 lines
2.6 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import { cookies } from 'next/headers';
|
|
import {
|
|
createCustomerSessionToken,
|
|
CUSTOMER_SESSION_COOKIE,
|
|
getCustomerSessionCookieOptions,
|
|
} from '@/infrastructure/auth/customer-session';
|
|
import {
|
|
fetchGoogleUserFromCode,
|
|
isGoogleOAuthConfigured,
|
|
verifyOAuthState,
|
|
} 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';
|
|
|
|
function redirectToLogin(error: string, returnTo?: string, req?: Request) {
|
|
const loginUrl = new URL('/login', getOrigin(req));
|
|
loginUrl.searchParams.set('tab', 'customer');
|
|
loginUrl.searchParams.set('error', error);
|
|
if (returnTo && returnTo !== '/account') {
|
|
loginUrl.searchParams.set('returnTo', returnTo);
|
|
}
|
|
return NextResponse.redirect(loginUrl);
|
|
}
|
|
|
|
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 ?? 'https://shahikitchen.se';
|
|
}
|
|
|
|
export async function GET(request: Request) {
|
|
if (!isGoogleOAuthConfigured()) {
|
|
return redirectToLogin('google_not_configured', undefined, request);
|
|
}
|
|
|
|
const url = new URL(request.url);
|
|
const code = url.searchParams.get('code');
|
|
const state = url.searchParams.get('state');
|
|
const oauthError = url.searchParams.get('error');
|
|
|
|
const cookieStore = await cookies();
|
|
const returnTo = sanitizeOAuthReturnPath(cookieStore.get(getOAuthReturnCookieName())?.value);
|
|
cookieStore.delete(getOAuthReturnCookieName());
|
|
|
|
if (oauthError) {
|
|
return redirectToLogin('google_denied', returnTo, request);
|
|
}
|
|
|
|
const storedState = cookieStore.get(OAUTH_STATE_COOKIE)?.value;
|
|
cookieStore.delete(OAUTH_STATE_COOKIE);
|
|
|
|
if (!verifyOAuthState(state) || state !== storedState) {
|
|
return redirectToLogin('invalid_state', returnTo, request);
|
|
}
|
|
|
|
if (!code) {
|
|
return redirectToLogin('missing_code', returnTo, request);
|
|
}
|
|
|
|
const user = await fetchGoogleUserFromCode(code, request);
|
|
if (!user) {
|
|
return redirectToLogin('google_failed', returnTo);
|
|
}
|
|
|
|
cookieStore.set(
|
|
CUSTOMER_SESSION_COOKIE,
|
|
createCustomerSessionToken(user),
|
|
getCustomerSessionCookieOptions(),
|
|
);
|
|
|
|
const response = NextResponse.redirect(new URL(returnTo, getOrigin(request)));
|
|
response.headers.set('Cache-Control', 'no-store');
|
|
return response;
|
|
} |