I have set up a new vue3 router and configured different routes:
const routes = [
{
path: "/",
name: "home",
component: HomeView,
},
{
path: "/about",
name: "about",
component: () =>
import(/* webpackChunkName: "about" */ "../views/AboutView.vue"),
},
{
path: "/gallery",
name: "gallery",
component: () =>
import(/* webpackChunkName: "gallery" */ "../views/GalleryView.vue"),
},
{
path: "/cms",
name: "cms",
component: () =>
import(/* webpackChunkName: "cms" */ "../views/CmsView.vue"),
},
{
path: "/login",
name: "login",
component: () =>
import(/* webpackChunkName: "cms" */ "../components/Login/LoginPage.vue"),
},
];
I am working on implementing a feature for Google Auth Login, where access to the /cms
route is restricted to a specific logged-in account. I am using a boolean value called loggedIn in the store which will be set to true when the correct user logs in, like this:
<script setup>
import { decodeCredential, googleLogout } from "vue3-google-login";
import store from "@/store/index";
import router from "@/router/index";
const callback = (response) => {
const userData = decodeCredential(response.credential);
if (userData.email === "my_email") {
store.state.loggedIn = true;
router.push({ path: "/cms" });
} else {
store.state.loggedIn = false;
googleLogout();
}
};
</script>
In the router configuration, I have added a beforeEach guard to handle routing based on the user's authorization status and previous page navigation:
router.beforeEach(async (to, from, next) => {
// Redirect to login page if user tries to access cms without logging in
if (!store.state.loggedIn && to.name === "cms") {
return next({ name: "login" });
}
// Redirect to cms page if user is already logged in and tries to go back to /cms
else if (store.state.loggedIn && to.name === "cms" && from.name === "login") {
console.log("test");
return next({ name: "cms" });
}
// Otherwise proceed to next page
else {
return next();
}
});
However, after successful login by the authorized user, an error occurs with message "Uncaught (in promise) Error: Infinite redirect in navigation guard" and the page remains on the /login
route instead of redirecting to /cms
.