Make Google OAuth redirect_uri dynamic based on request origin to support both shahikitchen.se and www.shahikitchen.se
This commit is contained in:
@@ -8,12 +8,22 @@ export function isGoogleOAuthConfigured(): boolean {
|
||||
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';
|
||||
}
|
||||
|
||||
export function getGoogleRedirectUri(): string {
|
||||
return `${getSiteOrigin()}/api/auth/callback/google`;
|
||||
export function getGoogleRedirectUri(req?: Request): string {
|
||||
return `${getSiteOrigin(req)}/api/auth/callback/google`;
|
||||
}
|
||||
|
||||
function getOAuthStateSecret(): string {
|
||||
@@ -38,10 +48,10 @@ export function verifyOAuthState(state: string | null | undefined): boolean {
|
||||
return timingSafeEqual(sigBuffer, expectedBuffer);
|
||||
}
|
||||
|
||||
export function buildGoogleAuthUrl(state: string): string {
|
||||
export function buildGoogleAuthUrl(state: string, req?: Request): string {
|
||||
const params = new URLSearchParams({
|
||||
client_id: process.env.GOOGLE_CLIENT_ID!,
|
||||
redirect_uri: getGoogleRedirectUri(),
|
||||
redirect_uri: getGoogleRedirectUri(req),
|
||||
response_type: 'code',
|
||||
scope: 'openid email profile',
|
||||
access_type: 'online',
|
||||
@@ -65,6 +75,7 @@ interface GoogleUserInfo {
|
||||
|
||||
export async function fetchGoogleUserFromCode(
|
||||
code: string,
|
||||
req?: Request,
|
||||
): Promise<{ email: string; name?: string } | null> {
|
||||
const tokenResponse = await fetch(GOOGLE_TOKEN_URL, {
|
||||
method: 'POST',
|
||||
@@ -73,7 +84,7 @@ export async function fetchGoogleUserFromCode(
|
||||
code,
|
||||
client_id: process.env.GOOGLE_CLIENT_ID!,
|
||||
client_secret: process.env.GOOGLE_CLIENT_SECRET!,
|
||||
redirect_uri: getGoogleRedirectUri(),
|
||||
redirect_uri: getGoogleRedirectUri(req),
|
||||
grant_type: 'authorization_code',
|
||||
}),
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user