I
I
Igor2019-08-24 02:18:23
Vue.js
Igor, 2019-08-24 02:18:23

Vue middleware routing protection?

Colleagues, welcome!

I'm trying to figure out how to protect routing in vue through middleware.

./router.js

spoiler

/**
 * 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


./middleware/auth.js
spoiler

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
  }
}



During the time while the token is being verified, information that needs to be protected is displayed for a few seconds.
Where am I wrong?

How to wait for verification and not go to the requested route?

Thank you.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question