Skip to content

Commit

Permalink
fix: fix protected routes when root path is different than /
Browse files Browse the repository at this point in the history
  • Loading branch information
dziraf committed May 12, 2022
1 parent 297d681 commit 9daf9e9
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 8 deletions.
20 changes: 14 additions & 6 deletions src/authentication/protected-routes.handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,26 +33,34 @@ export const withProtectedRoutesHandler = (
});
};

export const isAdminRoute = (url: string, adminRootPath: string): boolean => {
export const isAdminRoute = (
originalUrl: string,
adminRootPath: string
): boolean => {
const adminRoutes = AdminRouter.routes
.map((route) => convertToExpressRoute(route.path))
.filter((route) => route !== "");

let urlWithoutAdminRootPath = url.split("?")[0];
let urlWithoutAdminRootPath = originalUrl.split("?")[0];
if (adminRootPath !== "/") {
urlWithoutAdminRootPath = url.replace(adminRootPath, "");
urlWithoutAdminRootPath = urlWithoutAdminRootPath.replace(
adminRootPath,
""
);
if (!urlWithoutAdminRootPath.startsWith("/")) {
urlWithoutAdminRootPath = `/${urlWithoutAdminRootPath}`;
}
}

const isAdminRootUrl = url === adminRootPath;
const isAdminRootUrl = originalUrl === adminRootPath;
const isUrlUnderRootPath = originalUrl.startsWith(adminRootPath);

return (
isAdminRootUrl ||
adminRoutes.some((route) =>
(adminRoutes.some((route) =>
pathToRegexp(route).test(urlWithoutAdminRootPath)
)
) &&
isUrlUnderRootPath)
);
};

Expand Down
13 changes: 11 additions & 2 deletions test/protected-routes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,22 @@ describe("Protected routes", () => {
});

it("should detect admin routes when query params are included", () => {
const route = "/resources/list?filters.someFilter=123";
const route =
"/resources/someResource/actions/list?filters.someFilter=123";

expect(isAdminRoute(route, "/")).toBeTruthy();
});

it("should detect admin routes when query params are included and root path is not /", () => {
const route =
"/admin/resources/someResource/actions/list?filters.someFilter=123";

expect(isAdminRoute(route, "/admin")).toBeTruthy();
});

it("should not detect admin routes when query params are included but root is different", () => {
const route = "/resources/list?filters.someFilter=123";
const route =
"/resources/someResource/actions/list?filters.someFilter=123";

expect(isAdminRoute(route, "/admin")).toBeFalsy();
});
Expand Down

0 comments on commit 9daf9e9

Please sign in to comment.