move routing guard to main entry
This commit is contained in:
19
src/main.js
19
src/main.js
@@ -1,6 +1,25 @@
|
|||||||
import Vue from 'vue';
|
import Vue from 'vue';
|
||||||
import router from './router';
|
import router from './router';
|
||||||
import store from './store';
|
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({
|
const app = new Vue({
|
||||||
router,
|
router,
|
||||||
|
|||||||
@@ -8,8 +8,6 @@ import Customers from './pages/Customers.vue';
|
|||||||
import Orders from './pages/Orders.vue';
|
import Orders from './pages/Orders.vue';
|
||||||
import About from './pages/About.vue';
|
import About from './pages/About.vue';
|
||||||
|
|
||||||
import { isAuthenticated } from './lib/authentication';
|
|
||||||
|
|
||||||
Vue.use(VueRouter);
|
Vue.use(VueRouter);
|
||||||
|
|
||||||
const routes = [{
|
const routes = [{
|
||||||
@@ -48,21 +46,4 @@ const router = new VueRouter({
|
|||||||
routes,
|
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;
|
export default router;
|
||||||
|
|||||||
Reference in New Issue
Block a user