diff --git a/src/authentication/protected-routes.handler.ts b/src/authentication/protected-routes.handler.ts index a7d917b..98dbb95 100644 --- a/src/authentication/protected-routes.handler.ts +++ b/src/authentication/protected-routes.handler.ts @@ -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) ); }; diff --git a/test/protected-routes.test.ts b/test/protected-routes.test.ts index 3f0aabc..9fdb998 100644 --- a/test/protected-routes.test.ts +++ b/test/protected-routes.test.ts @@ -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(); });