How to disable access to login and signup page when user is logged in?

Viewed 1837

i am confused why is this not working.

Routes

const router = new VueRouter({
  mode: 'history',
  routes: [
      { path: '/', component: Home,  name: 'Home', meta: { requiresAuth: true }},
      { path: '/adminarea', component: Admin, name:"Admin", meta: { requiresAuth: true }},
      { path: '/login', component: Login, name: 'Login'},
      { path: '/signup', component: Register,  name: 'Signup'},
  ]
});

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // this route requires auth, check if logged in
    // if not, redirect to login page.
    if (!store.getters.getAuth) {
      next({ name: 'Login' })
    } else {
       next();
    }
  } else {
    next()
  }

});

to.matched.some(record => record.meta.requiresAuth this line should allow only routes with meta requiresAuth but i don't know why is it allowing other routes as well.

I can manually access login and signup pages. I cannot figure out what is wrong here.

1 Answers

I included a disableIfLoggedIn value in the router meta section

{
    name: 'login',
    path: '/login',
    component: Login,
    meta: {
        disableIfLoggedIn: true
    }
},

which will check before every route navigation

import {store} from "./store"; // import the store to check if authenticated

router.beforeEach((to, from, next) => {
    // if the route is not public
    if (!to.meta.public) {
        // if the user authenticated
        if (store.getters.isAuthenticated) { // I declared a `getter` function in the store to check if the user is authenticated.
            // continue to the route
            next();
        } else {
            // redirect to login
            next({name: 'login'});
        }
    }
    next();
});

Inside the store declare a getter function to check if authenticated or not

const getters = {
    isAuthenticated: state => {
        return state.isAuth; // code to check if authenticated
    }
};

The meta value disableIfLoggedIn can be set to true in any of the router object. Then it won't be accessible after logged in.

Related