Authentication
Manage JWT Token based Authentication.
How does it work?
Main.ts
// Main.ts
import { fakeBackend } from '@/utils/helpers/fake-backend';
fakeBackend();router.ts
// router.ts
router.beforeEach(async (to, from, next) => {
// redirect to login page if not logged in and trying to access a restricted page
const publicPages = ['/'];
const auth: AuthStore = useAuthStore();
const isPublicPage = publicPages.includes(to.path);
const authRequired = !isPublicPage && to.matched.some((record) => record.meta.requiresAuth);
// User not logged in and trying to access a restricted page
if (authRequired && !auth.user) {
auth.returnUrl = to.fullPath; // Save the intended page
next('/login');
} else if (auth.user && to.path === '/login') {
// User logged in and trying to access the login page
next({
query: {
...to.query,
redirect: auth.returnUrl !== '/' ? to.fullPath : undefined
}
});
} else {
// All other scenarios, either public page or authorized access
next();
}
});Last updated