diff --git a/src/main.js b/src/main.js index 95e6577..3bcc429 100644 --- a/src/main.js +++ b/src/main.js @@ -1,6 +1,25 @@ import Vue from 'vue'; import router from './router'; import store from './store'; +import { isAuthenticated } from './lib/authentication'; + +// pre-route auth checking +router.beforeEach((to, from, next) => { + // check if any of the matched routes require authentication + if (to.matched.some(record => record.meta.requiresAuthentication)) { + return isAuthenticated().then((user) => { + // if user is authenticated, continue + if (user) return next(); + + // otherwise, redirect to login, preserving the requested route + const { name, fullPath } = to; + const query = (name !== undefined) ? { redirect: name } : { prev: fullPath }; + return next({ name: 'login', query }); + }); + } + + return next(); +}); const app = new Vue({ router, diff --git a/src/router.js b/src/router.js index ab5cd39..ceb8f79 100644 --- a/src/router.js +++ b/src/router.js @@ -8,8 +8,6 @@ import Customers from './pages/Customers.vue'; import Orders from './pages/Orders.vue'; import About from './pages/About.vue'; -import { isAuthenticated } from './lib/authentication'; - Vue.use(VueRouter); const routes = [{ @@ -48,21 +46,4 @@ const router = new VueRouter({ routes, }); -router.beforeEach((to, from, next) => { - // check if any of the matched routes require authentication - if (to.matched.some(record => record.meta.requiresAuthentication)) { - return isAuthenticated().then((user) => { - // if user is authenticated, continue - if (user) return next(); - - // otherwise, redirect to login, preserving the requested route - const { name, fullPath } = to; - const query = (name !== undefined) ? { redirect: name } : { prev: fullPath }; - return next({ name: 'login', query }); - }); - } - - return next(); -}); - export default router;