Search code examples
vue.jsvue-routerauth0

Vue-Router beforeEnter not function as expected?


I am trying to protect a route using beforeEnter. my route looks like such;

      path: '/account',
      name: 'account',
      component: Account,
      beforeEnter:

            (to, from, next) => {

            const authService = getInstance();

            const fn = () => {
              // If the user is authenticated, continue
              if (authService.isAuthenticated) {
                console.log('no')
                return next();
              }

              // Otherwise, log in
              console.log('should login')
              authService.loginWithRedirect({ appState: { targetUrl: to.fullPath } });
            };


            if (!authService.loading) {
              return fn();
            }


            authService.$watch("loading", loading => {
              if (loading === false) {
                return fn();
              }
            })
          }

    },

THIS functions as I expect, but I don't believe the logic should into the routes file, so simply enough I store it in a different file under my auth folder. Like so;

    import { getInstance } from "./index";

    export const authGuard = (to, from, next) => {
    console.log('test')
    const authService = getInstance();

    const fn = () => {
        // If the user is authenticated, continue with the route
        if (authService.isAuthenticated) {
            console.log('no')
            return next();
        }

        // Otherwise, log in
        console.log('should login')
        authService.loginWithRedirect({ appState: { targetUrl: to.fullPath } });
    };

    // If loading has already finished, check our auth state using `fn()`
    if (!authService.loading) {
        return fn();
    }

    // Watch for the loading property to change before we check isAuthenticated
    authService.$watch("loading", loading => {
        if (loading === false) {
            return fn();
        }
    });
    };

However when I import this to my routes and do;

    import { authGaurd } from './auth/authGaurd'

      Vue.use(Router)

      export default new Router({
      mode: 'history',
      base: process.env.BASE_URL,
      routes: [
        {
          path: '/account',
          name: 'account',
          component: Account,
          beforeEnter: authGaurd
        },

this no long works? I'm sure I must be missing something simple? Any help would be much appreciated.


Solution

  • Try:

    - beforeEnter: authGaurd
    + beforeEnter(to, from, next) {
        authGaurd(to, from, next)
      }