Answer the question
In order to leave comments, you need to log in
Vue middleware routing protection?
Colleagues, welcome!
I'm trying to figure out how to protect routing in vue through middleware.
./router.js
/**
* Vue Router
*
* @library
*
* https://router.vuejs.org/en/
*/
// Lib imports
import Vue from "vue"
import Router from "vue-router"
import Meta from "vue-meta"
// Routes
import paths from "./paths"
import {store} from "../store/index"
function route(path, view, name, meta) {
return {
name: name || view,
path,
meta,
component: (resovle) => import(`@/views/${view}.vue`).then(resovle)
}
}
Vue.use(Router);
Vue.use(Meta);
// Create a new router
const vueRouter = new Router({
mode: "history",
routes: paths.map(path => route(path.path, path.view, path.name, path.meta)).concat([{path: "*", redirect: "/"}]),
scrollBehavior(to, from, savedPosition) {
if (savedPosition) {
return savedPosition
}
if (to.hash) {
return {selector: to.hash}
}
return {x: 0, y: 0}
}
});
vueRouter.beforeEach( async (to, from, next) => {
const middleware = to.meta.middleware;
if (!middleware) return next();
const context = {to, from, next, store};
for (const name of middleware) {
let obj = await loadMiddleware(name)
await obj.default(context)
}
});
/**
* @param name
* @returns {Promise<*>}
*/
async function loadMiddleware(name) {
return await import(`@/middleware/${name}.js`)
}
export default vueRouter
import {Secure} from "../api/Secure";
import {ACCESS_TOKEN} from "../store/mutation-types";
export default async function ({store, next,}) {
if (!await checkToken(store.getters[ACCESS_TOKEN]))
return next("/login")
return next()
}
/**
*
* @param token
* @returns {Promise<boolean>}
*/
async function checkToken(token) {
let secure = new Secure()
try {
let response = await secure.checkToken({token})
return response.code === 0;
} finally {
secure = undefined
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question