Make Google OAuth redirect_uri dynamic based on request origin to support both shahikitchen.se and www.shahikitchen.se

This commit is contained in:
root
2026-07-03 03:06:44 +00:00
parent 8ccf033329
commit 8120a09a0c
3 changed files with 47 additions and 18 deletions
+18 -9
View File
@@ -19,8 +19,8 @@ export const dynamic = 'force-dynamic';
const OAUTH_STATE_COOKIE = 'shahi_google_oauth_state'; const OAUTH_STATE_COOKIE = 'shahi_google_oauth_state';
function redirectToLogin(error: string, returnTo?: string) { function redirectToLogin(error: string, returnTo?: string, req?: Request) {
const loginUrl = new URL('/login', getOrigin()); const loginUrl = new URL('/login', getOrigin(req));
loginUrl.searchParams.set('tab', 'customer'); loginUrl.searchParams.set('tab', 'customer');
loginUrl.searchParams.set('error', error); loginUrl.searchParams.set('error', error);
if (returnTo && returnTo !== '/account') { if (returnTo && returnTo !== '/account') {
@@ -29,13 +29,22 @@ function redirectToLogin(error: string, returnTo?: string) {
return NextResponse.redirect(loginUrl); return NextResponse.redirect(loginUrl);
} }
function getOrigin(): string { 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'; return process.env.NEXT_PUBLIC_SITE_URL ?? 'http://localhost:3000';
} }
export async function GET(request: Request) { export async function GET(request: Request) {
if (!isGoogleOAuthConfigured()) { if (!isGoogleOAuthConfigured()) {
return redirectToLogin('google_not_configured'); return redirectToLogin('google_not_configured', undefined, request);
} }
const url = new URL(request.url); const url = new URL(request.url);
@@ -48,21 +57,21 @@ export async function GET(request: Request) {
cookieStore.delete(getOAuthReturnCookieName()); cookieStore.delete(getOAuthReturnCookieName());
if (oauthError) { if (oauthError) {
return redirectToLogin('google_denied', returnTo); return redirectToLogin('google_denied', returnTo, request);
} }
const storedState = cookieStore.get(OAUTH_STATE_COOKIE)?.value; const storedState = cookieStore.get(OAUTH_STATE_COOKIE)?.value;
cookieStore.delete(OAUTH_STATE_COOKIE); cookieStore.delete(OAUTH_STATE_COOKIE);
if (!verifyOAuthState(state) || state !== storedState) { if (!verifyOAuthState(state) || state !== storedState) {
return redirectToLogin('invalid_state', returnTo); return redirectToLogin('invalid_state', returnTo, request);
} }
if (!code) { if (!code) {
return redirectToLogin('missing_code', returnTo); return redirectToLogin('missing_code', returnTo, request);
} }
const user = await fetchGoogleUserFromCode(code); const user = await fetchGoogleUserFromCode(code, request);
if (!user) { if (!user) {
return redirectToLogin('google_failed', returnTo); return redirectToLogin('google_failed', returnTo);
} }
@@ -73,7 +82,7 @@ export async function GET(request: Request) {
getCustomerSessionCookieOptions(), getCustomerSessionCookieOptions(),
); );
const response = NextResponse.redirect(new URL(returnTo, getOrigin())); const response = NextResponse.redirect(new URL(returnTo, getOrigin(request)));
response.headers.set('Cache-Control', 'no-store'); response.headers.set('Cache-Control', 'no-store');
return response; return response;
} }
+12 -3
View File
@@ -16,7 +16,7 @@ const OAUTH_STATE_COOKIE = 'shahi_google_oauth_state';
export async function GET(request: Request) { export async function GET(request: Request) {
if (!isGoogleOAuthConfigured()) { if (!isGoogleOAuthConfigured()) {
return NextResponse.redirect(new URL('/login?tab=customer&error=google_not_configured', getOrigin())); return NextResponse.redirect(new URL('/login?tab=customer&error=google_not_configured', getOrigin(request)));
} }
const url = new URL(request.url); const url = new URL(request.url);
@@ -39,9 +39,18 @@ export async function GET(request: Request) {
maxAge: 600, maxAge: 600,
}); });
return NextResponse.redirect(buildGoogleAuthUrl(state)); return NextResponse.redirect(buildGoogleAuthUrl(state, request));
} }
function getOrigin(): string { 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'; return process.env.NEXT_PUBLIC_SITE_URL ?? 'http://localhost:3000';
} }
+17 -6
View File
@@ -8,12 +8,22 @@ export function isGoogleOAuthConfigured(): boolean {
return Boolean(process.env.GOOGLE_CLIENT_ID && process.env.GOOGLE_CLIENT_SECRET); return Boolean(process.env.GOOGLE_CLIENT_ID && process.env.GOOGLE_CLIENT_SECRET);
} }
export function getSiteOrigin(): string { export function getSiteOrigin(req?: Request): string {
if (req) {
try {
const url = new URL(req.url);
// In production behind nginx, prefer https even if internal request is http
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'; return process.env.NEXT_PUBLIC_SITE_URL ?? 'http://localhost:3000';
} }
export function getGoogleRedirectUri(): string { export function getGoogleRedirectUri(req?: Request): string {
return `${getSiteOrigin()}/api/auth/callback/google`; return `${getSiteOrigin(req)}/api/auth/callback/google`;
} }
function getOAuthStateSecret(): string { function getOAuthStateSecret(): string {
@@ -38,10 +48,10 @@ export function verifyOAuthState(state: string | null | undefined): boolean {
return timingSafeEqual(sigBuffer, expectedBuffer); return timingSafeEqual(sigBuffer, expectedBuffer);
} }
export function buildGoogleAuthUrl(state: string): string { export function buildGoogleAuthUrl(state: string, req?: Request): string {
const params = new URLSearchParams({ const params = new URLSearchParams({
client_id: process.env.GOOGLE_CLIENT_ID!, client_id: process.env.GOOGLE_CLIENT_ID!,
redirect_uri: getGoogleRedirectUri(), redirect_uri: getGoogleRedirectUri(req),
response_type: 'code', response_type: 'code',
scope: 'openid email profile', scope: 'openid email profile',
access_type: 'online', access_type: 'online',
@@ -65,6 +75,7 @@ interface GoogleUserInfo {
export async function fetchGoogleUserFromCode( export async function fetchGoogleUserFromCode(
code: string, code: string,
req?: Request,
): Promise<{ email: string; name?: string } | null> { ): Promise<{ email: string; name?: string } | null> {
const tokenResponse = await fetch(GOOGLE_TOKEN_URL, { const tokenResponse = await fetch(GOOGLE_TOKEN_URL, {
method: 'POST', method: 'POST',
@@ -73,7 +84,7 @@ export async function fetchGoogleUserFromCode(
code, code,
client_id: process.env.GOOGLE_CLIENT_ID!, client_id: process.env.GOOGLE_CLIENT_ID!,
client_secret: process.env.GOOGLE_CLIENT_SECRET!, client_secret: process.env.GOOGLE_CLIENT_SECRET!,
redirect_uri: getGoogleRedirectUri(), redirect_uri: getGoogleRedirectUri(req),
grant_type: 'authorization_code', grant_type: 'authorization_code',
}), }),
}); });