Forbid authenticated users from visiting login page in nuxt js

Viewed 158

I have the following code snipped from my middleware/auth.js that redirects users to login page if the users are unauthenticated.

export default function ({ store, redirect }) {
  if (!store.state.admin.isAdmin) {
    redirect('/auth/login')
  }
}

Now I want to forbid authenticated users visiting login page and redirect to ('/manage/dashboard') when they hit the login url.

I have used the following approach in my login view:

  mounted () {
    if (localStorage.getItem('token') && localStorage.getItem('userId')) {
      this.$router.replace({ path: '/admin/dashboard' })
    }
  }

This works but the execution is too slow and user can see login page for few seconds.

What is the efficient way to achieve the redirect ?

1 Answers

I wouldn't access localStorage from the login view, I would prefer to set it in your store and then access the store. I have not run this code but I think you want to do something like this.

You can create another check-auth.js middleware and add that to your login view.

check-auth.js

export default function (context) {
    context.store.dispatch('initAuth', context.req);
}

store/index.js

state:{
     authenticated:false;
}
mutations: {
    setAuthentication(state, auth) {
            state.authenticated = auth;
        },
}
actions: {
    initAuth(vuexContext, req) {
        if (localStorage.getItem('token') && localStorage.getItem('userId')){
            vuexContext.commit('setAuthentication', true);
        }else{
            vuexContext.commit('setAuthentication', false);
        }
    }
},
getters: {
        isAuthenticated(state) {
            return state.authenticated;
        },
    },

Then check if the user is authenticated auth.js

if (!context.store.getters.isAuthenticated) {
    context.redirect('/auth/login');
}

add middleware to your view

export default {
    middleware: ['check-auth', 'auth'],
    components: {},
    methods: {},
};
Related