Make Google OAuth redirect_uri dynamic based on request origin to support both shahikitchen.se and www.shahikitchen.se
This commit is contained in:
@@ -19,8 +19,8 @@ export const dynamic = 'force-dynamic';
|
||||
|
||||
const OAUTH_STATE_COOKIE = 'shahi_google_oauth_state';
|
||||
|
||||
function redirectToLogin(error: string, returnTo?: string) {
|
||||
const loginUrl = new URL('/login', getOrigin());
|
||||
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') {
|
||||
@@ -29,13 +29,22 @@ function redirectToLogin(error: string, returnTo?: string) {
|
||||
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';
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
if (!isGoogleOAuthConfigured()) {
|
||||
return redirectToLogin('google_not_configured');
|
||||
return redirectToLogin('google_not_configured', undefined, request);
|
||||
}
|
||||
|
||||
const url = new URL(request.url);
|
||||
@@ -48,21 +57,21 @@ export async function GET(request: Request) {
|
||||
cookieStore.delete(getOAuthReturnCookieName());
|
||||
|
||||
if (oauthError) {
|
||||
return redirectToLogin('google_denied', returnTo);
|
||||
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);
|
||||
return redirectToLogin('invalid_state', returnTo, request);
|
||||
}
|
||||
|
||||
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) {
|
||||
return redirectToLogin('google_failed', returnTo);
|
||||
}
|
||||
@@ -73,7 +82,7 @@ export async function GET(request: Request) {
|
||||
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');
|
||||
return response;
|
||||
}
|
||||
Reference in New Issue
Block a user