Guys i don't know why im get this error when i try to login, console error after login is made:
Error: Redirected when going from "/pages/login" to "/dashboard" via a navigation guard.
Im trying when i hit login to redirect me to /dashboard page after the validation is made but when i hit login it does nothing no redirect, and if i hit again the login button the redirect is made on dashboard page. Any solutions? Thanks!
loginJWT ({ commit }, payload) {
return new Promise((resolve, reject) => {
jwt.login(payload.email, payload.password)
.then(response => {
console.log(response.data)
// If there's user data in response
if (response.data.userDetails) {
// Navigate User to homepage
router.push(router.currentRoute.query.to || '/') // <- Here is the redirect after login
// Set accessToken
localStorage.setItem('accessToken', response.data.accessToken)
// Update user details
commit('UPDATE_USER_INFO', response.data.userDetails, {root: true})
// Set bearer token in axios
commit('SET_BEARER', response.data.accessToken)
resolve(response)
} else {
reject({message: 'Wrong Email or Password'})
}
})
.catch(error => { reject(error) })
})
}
In router js:
{
path: '/dashboard',
name: 'dashboard',
component: () => import('./views/Dashboard.vue'),
meta: {
rule: 'editor',
authRequired: false
},
beforeEnter: (to, from, next) => {
guard(to, from, next)
}
}
And the guard code that validate the token after each route:
const guard = function (to, from, next) {
// check for valid auth token
const token = localStorage.getItem('accessToken')
axios.post('http://localhost:8081/api/users/checkAuthToken', {tokn: token})
.then(function (response) {
if (response.status === 200) {
next()
}
}).catch(function (error) {
if (error.response && error.response.status === 401) {
alert('access neautorizat')
next('/pages/login')
localStorage.removeItem('userInfo')
localStorage.removeItem('accessToken')
}
})
}
beforeEach code:
router.beforeEach((to, from, next) => {
const publicPages = [
'/pages/login',
'/pages/register',
'/pages/forgot-password',
'/pages/comingsoon',
'/pages/error-404',
'/pages/error-500',
'/pages/not-authorized',
'/pages/maintenance',
'/callback'
]
const authRequired = !publicPages.includes(to.path)
const loggedIn = localStorage.getItem('accessToken')
if (authRequired && !loggedIn) {
return next('/pages/login')
}
return next()
})
First Set accessToken and Last Navigate User to homepage