Home > OS >  Vue 3 composition API Router Params with Navigation Auth Guard
Vue 3 composition API Router Params with Navigation Auth Guard

Time:12-28

I am having a small problem where I don't know what to do. I tried so many diffrent solutions but nothing worked.

My Problem:

I got a navigation Guard:

import { createRouter, createWebHistory, useRoute } from "vue-router";
import { isAuthenticated } from "../service/axios-auth";
import ChangePasswordView from "../views/ChangePasswordView.vue";
import LoginView from "../views/LoginView.vue";
import HomeView from "../views/HomeView.vue";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      name: "home",
      component: HomeView,
      meta: {
        requiresAuth: true,
      }
    },
    {
      path: "/password-reset/Token/:Token",
      name: "password-reset",
      component: ChangePasswordView,
      meta: {
        requiresAuth: false,
      }
    },
    {
      path: "/login",
      name: "login",
      component: LoginView,
      meta: {
        requiresAuth: false,
      }
    }
  ],
});

router.beforeEach(async (to, from, next) => {
  if (to.params.Token != null) {
    next({ name:"password-reset", params: { Token: to.fullPath }})
  } else if (to.matched.some((record) => record.meta.requiresAuth)) {
    if (!(await isAuthenticated())) {
      next('/login');
    } else {
      next();
    }
  } else {
     next();
  }
})

export default router;

and I want to call an external Link (http://localhost:5173/password-reset/Token/A1EB34589AD1CCEE77C79BDDC5A3187DF51D3368F08B49DA833AB902CBC812A513A11C111455DB8FB2C0824E5401096F31CFB6D1CEDABCCB549BF5C5D3B1747F) but as soon as I open this link nothing happens and the website is loading infinitely.

Does anyone knows what I am doing wrong here?

CodePudding user response:

What does this block mean?

if (to.params.Token != null) {
    next({ name:"password-reset", params: { Token: to.fullPath }})
}

if the route has a Token param then redirect it to password-reset. It's a loop. because the password-reset route has the Token param, it will get back to it over & over. I don't know precisely what you want to do with this check. It does nothing, other than looping around. I would like to understand more about your implementation, so I can assist you.

Also, you can access the meta field of the route directly from the to parameter. documentation

router.beforeEach(async (to, from, next) => {
  if (to.meta.requiresAuth === true && !(await isAuthenticated())) {
      next('/login');
      return;
  }
  next();
})

CodePudding user response:

I am basicly stupid... Inside my password-reset View I have a onMount function that checks if I am logged in. This function pushes the router to the home View. That's why I can't access the password-reset site :)

  • Related