11import AdminJS , { Router as AdminRouter } from "adminjs" ;
22import { Router } from "express" ;
3+ import { convertToExpressRoute } from "../convertRoutes" ;
4+ import { pathToRegexp } from "path-to-regexp" ;
35
46export const withProtectedRoutesHandler = (
57 router : Router ,
@@ -8,7 +10,7 @@ export const withProtectedRoutesHandler = (
810 const { rootPath } = admin . options ;
911
1012 router . use ( ( req , res , next ) => {
11- if ( AdminRouter . assets . find ( ( asset ) => req . originalUrl . match ( asset . path ) ) ) {
13+ if ( isAdminAsset ( req . originalUrl ) ) {
1214 next ( ) ;
1315 } else if (
1416 req . session . adminUser ||
@@ -17,18 +19,36 @@ export const withProtectedRoutesHandler = (
1719 req . originalUrl . startsWith ( admin . options . logoutPath )
1820 ) {
1921 next ( ) ;
20- } else {
22+ } else if ( isAdminRoute ( req . originalUrl , rootPath ) ) {
2123 // If the redirection is caused by API call to some action just redirect to resource
2224 const [ redirectTo ] = req . originalUrl . split ( "/actions" ) ;
2325 req . session . redirectTo = redirectTo . includes ( `${ rootPath } /api` )
2426 ? rootPath
2527 : redirectTo ;
28+
2629 req . session . save ( ( err ) => {
2730 if ( err ) {
2831 next ( err ) ;
2932 }
3033 res . redirect ( admin . options . loginPath ) ;
3134 } ) ;
35+ } else {
36+ next ( ) ;
3237 }
3338 } ) ;
3439} ;
40+
41+ export const isAdminRoute = ( url : string , adminRootUrl : string ) : boolean => {
42+ const adminRoutes = AdminRouter . routes
43+ . map ( ( route ) => convertToExpressRoute ( route . path ) )
44+ . filter ( ( route ) => route !== "" ) ;
45+ const isAdminRootUrl = url === adminRootUrl ;
46+
47+ return (
48+ isAdminRootUrl ||
49+ ! ! adminRoutes . find ( ( route ) => pathToRegexp ( route ) . test ( url ) )
50+ ) ;
51+ } ;
52+
53+ const isAdminAsset = ( url : string ) =>
54+ AdminRouter . assets . find ( ( asset ) => url . match ( asset . path ) ) ;
0 commit comments