Redirect after normalizing URL for VA (#183)

* Redirect after normalizing URL for VA

* Redirect after normalizing URL for VA
This commit is contained in:
Taran Vohra
2024-02-22 17:31:41 +05:30
committed by GitHub
parent 98d44f01c7
commit 64bb5ebf5a
2 changed files with 13 additions and 12 deletions
+2 -2
View File
@@ -39,9 +39,9 @@ export function getVisitorAuthCookieValue(basePath: string, token: string): stri
}
/**
* Sanitize the URL by removing the visitor authentication token from the query parameters (if present).
* Normalize the URL by removing the visitor authentication token from the query parameters (if present).
*/
export function sanitizeVisitorAuthURL(url: URL): URL {
export function normalizeVisitorAuthURL(url: URL): URL {
const withoutVAParam = new URL(url);
withoutVAParam.searchParams.delete(VISITOR_AUTH_PARAM);
return withoutVAParam;
+11 -10
View File
@@ -21,7 +21,7 @@ import {
getVisitorAuthCookieName,
getVisitorAuthCookieValue,
getVisitorAuthToken,
sanitizeVisitorAuthURL,
normalizeVisitorAuthURL,
} from '@/lib/visitor-auth';
export const config = {
@@ -120,6 +120,14 @@ export async function middleware(request: NextRequest) {
return writeCookies(NextResponse.redirect(resolved.redirect), resolved.cookies);
}
// Make sure the URL is clean of any va token after a successful lookup
// The token is stored in a cookie that is set on the redirect response
const normalizedVA = normalizeVisitorAuthURL(normalized);
if (normalizedVA.toString() !== normalized.toString()) {
console.log(`redirecting to ${normalizedVA.toString()}`);
return writeCookies(NextResponse.redirect(normalizedVA.toString()), resolved.cookies);
}
Sentry.setTag('space', resolved.space);
Sentry.setContext('content', {
space: resolved.space,
@@ -174,15 +182,8 @@ export async function middleware(request: NextRequest) {
headers.set('x-gitbook-api', apiEndpoint);
}
const rewrite = new URL(rewritePathname, request.nextUrl.toString());
rewrite.search = url.search;
// Make sure the target URL is clean of any va token before we use it for response
const target = sanitizeVisitorAuthURL(rewrite);
if (target.toString() !== rewrite.toString()) {
console.log(`redirecting to ${target.toString()}`);
return writeCookies(NextResponse.redirect(target.toString()), resolved.cookies);
}
const target = new URL(rewritePathname, request.nextUrl.toString());
target.search = url.search;
const response = writeCookies(
NextResponse.rewrite(target, {