Created
November 9, 2020 06:31
-
-
Save blogcacanid/117ecc308a79762d17d0bd93f9beea5c to your computer and use it in GitHub Desktop.
router.js Authentication JWT Vue Lumen 7
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Vue from 'vue'; | |
import Router from 'vue-router'; | |
import Home from './views/Home.vue'; | |
import Login from './views/Login.vue'; | |
import Register from './views/Register.vue'; | |
Vue.use(Router); | |
export const router = new Router({ | |
mode: 'history', | |
routes: [ | |
{ | |
path: '/', | |
name: 'home', | |
component: Home | |
}, | |
{ | |
path: '/home', | |
component: Home | |
}, | |
{ | |
path: '/login', | |
component: Login | |
}, | |
{ | |
path: '/register', | |
component: Register | |
}, | |
{ | |
path: '/profile', | |
name: 'profile', | |
// lazy-loaded | |
component: () => import('./views/Profile.vue') | |
} | |
] | |
}); | |
router.beforeEach((to, from, next) => { | |
const publicPages = ['/login', '/register', '/home']; | |
const authRequired = !publicPages.includes(to.path); | |
const loggedIn = localStorage.getItem('user'); | |
// trying to access a restricted page + not logged in | |
// redirect to login page | |
if (authRequired && !loggedIn) { | |
next('/login'); | |
} else { | |
next(); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment