Adds in authentication system and overhauls the navigation bar to be built dynamically.

This commit is contained in:
Cameron Redmore 2025-04-24 21:35:52 +01:00
parent 7e98b5345d
commit 28c054de22
21 changed files with 1531 additions and 56 deletions

View file

@ -1,6 +1,7 @@
import { defineRouter } from '#q-app/wrappers'
import { createRouter, createMemoryHistory, createWebHistory, createWebHashHistory } from 'vue-router'
import routes from './routes'
import { useAuthStore } from 'stores/auth'; // Import the auth store
/*
* If not building with SSR mode, you can
@ -11,7 +12,7 @@ import routes from './routes'
* with the Router instance.
*/
export default defineRouter(function (/* { store, ssrContext } */) {
export default defineRouter(function ({ store /* { store, ssrContext } */ }) {
const createHistory = process.env.SERVER
? createMemoryHistory
: (process.env.VUE_ROUTER_MODE === 'history' ? createWebHistory : createWebHashHistory)
@ -26,5 +27,45 @@ export default defineRouter(function (/* { store, ssrContext } */) {
history: createHistory(process.env.VUE_ROUTER_BASE)
})
// Navigation Guard using Pinia store
Router.beforeEach(async (to, from, next) => {
const authStore = useAuthStore(store); // Get store instance
// Ensure auth status is checked, especially on first load or refresh
// This check might be better placed in App.vue or a boot file
if (!authStore.user && !authStore.loading) { // Check only if user is not loaded and not already loading
try {
await authStore.checkAuthStatus();
} catch (e) {
console.error("Initial auth check failed", e);
// Decide how to handle initial check failure (e.g., proceed, redirect to error page)
}
}
const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
const publicPages = ['/login', '/register'];
const isPublicPage = publicPages.includes(to.path);
const isAuthenticated = authStore.isAuthenticated; // Get status from store
console.log('Store Auth status:', isAuthenticated);
console.log('Navigating to:', to.path);
console.log('Requires auth:', requiresAuth);
console.log('Is public page:', isPublicPage);
if (requiresAuth && !isAuthenticated) {
// If route requires auth and user is not authenticated, redirect to login
console.log('Redirecting to login (requires auth, not authenticated)');
next('/login');
} else if (isPublicPage && isAuthenticated) {
// If user is authenticated and tries to access login/register, redirect to home
console.log('Redirecting to home (public page, authenticated)');
next('/');
} else {
// Otherwise, allow navigation
console.log('Allowing navigation');
next();
}
});
return Router
})