diff --git a/lib/templates/auth.middleware.js b/lib/templates/auth.middleware.js index 4d61d0bc9..268d3ab8e 100644 --- a/lib/templates/auth.middleware.js +++ b/lib/templates/auth.middleware.js @@ -1,29 +1,31 @@ import middleware from './middleware' -middleware.auth = function authMiddleware ({ route, redirect, store }) { - route.matched.some((currentRoute) => { - // Retriving Auth Guard status through route's component options. - const options = currentRoute.components.default.options - const guarded = options.guarded +const isRouteGuarded = ({ route: { matched: m } }) => + m.some(({ components: c }) => process.server + ? Object.values(c).some(({ _Ctor: _c }) => + Object.values(_c).some(({ options: o }) => o && o.guarded) + ) + : Object.values(c).some(o => o.options.guarded) + ) - // Only apply the middleware to guarded routes - if (guarded) { - // Checking if guest redirection middleware is enabled - <% if (options.redirect.guest) { %> - // Guest is redirected back to login page - // and excluding redirected paths from hitting the middleware again. - if (!store.getters['auth/loggedIn'] && route.path !== '<%= options.redirect.notLoggedIn %>') { - return redirect('<%= options.redirect.notLoggedIn %>') - } - // Checking if user redirection middleware is enabled - <% } if (options.redirect.user) { %> - // Guest is redirected back to login page - // and excluding redirected paths from hitting the middleware again. - if (store.getters['auth/loggedIn'] && route.path !== '<%= options.redirect.loggedIn %>') { - return redirect('<%= options.redirect.loggedIn %>') - } - <% } %> +middleware.auth = function(context) { + const { route: {path: p}, redirect: r, store: s } = context + + // Registering guest and auth routes. + let guestRoute = '<%= options.redirect.notLoggedIn %>' + let authRoute = '<%= options.redirect.loggedIn %>' + + // Retriving Auth Guard status through route's component options. + let g = isRouteGuarded(context) + // Apply the middleware to guarded routes + if (g) { + if (<%= options.redirect.guest %> && !s.getters['auth/loggedIn'] && guestRoute !== p) { + return r(guestRoute) + } + + if (<% options.redirect.user %> && s.getters['auth/loggedIn'] && authRoute !== p) { + return r(authRoute) } - }); + } }