I am currently in the process of developing a dashboard using Vue, Vuex, and Quasar. However, I have encountered an authentication error that is preventing me from progressing. Additionally, I need assistance in ensuring that when a user is already logged in, they are redirected directly to the dashboard.
The login functionality appears to be working perfectly fine. Upon entering credentials and logging in, the token is received and stored correctly in the status. However, the issue arises when trying to redirect to the dashboard after login. Instead, I receive the following error message (screenshot attached): https://i.stack.imgur.com/IhLbw.png Router Index
import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'
import routes from './routes'
Vue.use(VueRouter)
// Router setup
const Router = new VueRouter({
scrollBehavior: () => ({ x: 0, y: 0 }),
routes,
mode: process.env.VUE_ROUTER_MODE,
base: process.env.VUE_ROUTER_BASE
})
// Navigation Guard
Router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
if (store.getters['auth/isLoggedIn']) {
next({ name: 'Dashboard' })
return
}
next('/login')
} else {
next()
}
})
export default Router
Routes
const routes = [
{ path: '/login', name: 'Login', component: () => import('pages/Login.vue') },
{
path: '/app',
component: () => import('layouts/MainLayout.vue'),
meta: { requiresAuth: true },
name: 'App',
children: [
{ path: 'dashboard', name: 'Dashboard', component: () => import('pages/Index.vue') },
{ path: 'user', name: 'User', component: () => import('pages/User.vue') }
]
},
{
path: '*',
component: () => import('pages/Error404.vue')
}
]
export default routes
Vuex Auth
import Api from '../api'
// Vuex module for auth
export default {
namespaced: true,
state: {
token: localStorage.getItem('token') || '',
user: null
},
getters: {
isLoggedIn: state => !!state.token,
user (state) {
return state.user
}
},
mutations: {
SET_TOKEN (state, token) {
state.token = token
},
SET_USER (state, user) {
state.user = user
}
},
actions: {
async signIn ({ commit }, credentials) {
const response = await Api().post('/token', credentials)
const token = response.data.token
const loginuser = {
username: response.data.user_display_name,
email: response.data.user_email
}
commit('SET_TOKEN', token)
commit('SET_USER', loginuser)
},
signOut ({ commit }) {
return Api().post('/logout').then(() => {
commit('SET_TOKEN', null)
commit('SET_USER', null)
})
}
}
}