feat(http): keep slashes in queryParams in redirects (#4928)
* refactor(http): extract logic into constructRedirectPath This allows us to easily test our redirect path construction logic where we get the relative path, the query string and construct a redirect path. By extracting this from `redirect`, we can easily test this logic in a unit test. I did this so we could test some logic where slashes in query strings should be made human-friendly for users. * feat(testing): add tests for constructRedirectPath Co-authored-by: Asher <ash@coder.com>
This commit is contained in:
@ -138,6 +138,21 @@ export const relativeRoot = (originalUrl: string): string => {
|
||||
return normalize("./" + (depth > 1 ? "../".repeat(depth - 1) : ""))
|
||||
}
|
||||
|
||||
/**
|
||||
* A helper function to construct a redirect path based on
|
||||
* an Express Request, query and a path to redirect to.
|
||||
*
|
||||
* Redirect path is relative to `/${to}`.
|
||||
*/
|
||||
export const constructRedirectPath = (req: express.Request, query: qs.ParsedQs, to: string): string => {
|
||||
const relativePath = normalize(`${relativeRoot(req.originalUrl)}/${to}`, true)
|
||||
// %2f or %2F are both equalivent to an encoded slash /
|
||||
const queryString = qs.stringify(query).replace(/%2[fF]/g, "/")
|
||||
const redirectPath = `${relativePath}${queryString ? `?${queryString}` : ""}`
|
||||
|
||||
return redirectPath
|
||||
}
|
||||
|
||||
/**
|
||||
* Redirect relatively to `/${to}`. Query variables on the current URI will be
|
||||
* preserved. `to` should be a simple path without any query parameters
|
||||
@ -156,9 +171,7 @@ export const redirect = (
|
||||
}
|
||||
})
|
||||
|
||||
const relativePath = normalize(`${relativeRoot(req.originalUrl)}/${to}`, true)
|
||||
const queryString = qs.stringify(query)
|
||||
const redirectPath = `${relativePath}${queryString ? `?${queryString}` : ""}`
|
||||
const redirectPath = constructRedirectPath(req, query, to)
|
||||
logger.debug(`redirecting from ${req.originalUrl} to ${redirectPath}`)
|
||||
res.redirect(redirectPath)
|
||||
}
|
||||
|
Reference in New Issue
Block a user