@@ -3,38 +3,33 @@ import { Router } from "express";
33import { convertToExpressRoute } from "../convertRoutes" ;
44import { pathToRegexp } from "path-to-regexp" ;
55
6+ const doesNotRequireAuthentication = (
7+ url : string ,
8+ { loginPath, logoutPath }
9+ ) => {
10+ return (
11+ isAdminAsset ( url ) || url . startsWith ( loginPath ) || url . startsWith ( logoutPath )
12+ ) ;
13+ } ;
14+
615export const withProtectedRoutesHandler = (
716 router : Router ,
817 admin : AdminJS
918) : void => {
1019 const { rootPath, loginPath, logoutPath } = admin . options ;
1120
1221 router . use ( ( req , res , next ) => {
13- if ( isAdminAsset ( req . originalUrl ) ) {
14- next ( ) ;
15- } else if (
16- req . session . adminUser ||
17- // these routes doesn't need authentication
18- req . originalUrl . startsWith ( loginPath ) ||
19- req . originalUrl . startsWith ( logoutPath )
22+ if (
23+ doesNotRequireAuthentication ( req . originalUrl , { loginPath, logoutPath } )
2024 ) {
21- next ( ) ;
22- } else if ( isAdminRoute ( req . originalUrl , rootPath ) ) {
23- // If the redirection is caused by API call to some action just redirect to resource
24- const [ redirectTo ] = req . originalUrl . split ( "/actions" ) ;
25- req . session . redirectTo = redirectTo . includes ( `${ rootPath } /api` )
26- ? rootPath
27- : redirectTo ;
25+ return next ( ) ;
26+ }
2827
29- req . session . save ( ( err ) => {
30- if ( err ) {
31- next ( err ) ;
32- }
33- res . redirect ( loginPath ) ;
34- } ) ;
35- } else {
36- next ( ) ;
28+ if ( isAdminRoute ( req . originalUrl , rootPath ) && ! ! req . session . adminUser ) {
29+ return next ( ) ;
3730 }
31+
32+ return res . redirect ( loginPath ) ;
3833 } ) ;
3934} ;
4035
@@ -43,7 +38,7 @@ export const isAdminRoute = (url: string, adminRootPath: string): boolean => {
4338 . map ( ( route ) => convertToExpressRoute ( route . path ) )
4439 . filter ( ( route ) => route !== "" ) ;
4540
46- let urlWithoutAdminRootPath = url ;
41+ let urlWithoutAdminRootPath = url . split ( "?" ) [ 0 ] ;
4742 if ( adminRootPath !== "/" ) {
4843 urlWithoutAdminRootPath = url . replace ( adminRootPath , "" ) ;
4944 if ( ! urlWithoutAdminRootPath . startsWith ( "/" ) ) {
@@ -55,7 +50,7 @@ export const isAdminRoute = (url: string, adminRootPath: string): boolean => {
5550
5651 return (
5752 isAdminRootUrl ||
58- ! ! adminRoutes . find ( ( route ) =>
53+ adminRoutes . some ( ( route ) =>
5954 pathToRegexp ( route ) . test ( urlWithoutAdminRootPath )
6055 )
6156 ) ;
0 commit comments