Описание изменений
This commit is contained in:
@@ -1,43 +1,48 @@
|
||||
import { createRouter, createWebHistory } from 'vue-router';
|
||||
import { useAuthStore } from '../stores/auth';
|
||||
import HomeView from '../views/HomeView.vue';
|
||||
import { useAuthStore } from '../stores/auth';
|
||||
|
||||
console.log('router/index.js: Script loaded');
|
||||
|
||||
const routes = [
|
||||
{
|
||||
path: '/',
|
||||
name: 'home',
|
||||
component: HomeView,
|
||||
meta: { requiresAuth: false },
|
||||
},
|
||||
component: HomeView
|
||||
}
|
||||
// Другие маршруты можно добавить позже, когда будут созданы соответствующие компоненты
|
||||
];
|
||||
|
||||
const router = createRouter({
|
||||
history: createWebHistory(),
|
||||
routes,
|
||||
scrollBehavior(to, from, savedPosition) {
|
||||
return savedPosition || { top: 0 };
|
||||
},
|
||||
routes
|
||||
});
|
||||
|
||||
// Навигационный хук для проверки аутентификации
|
||||
console.log('router/index.js: Router created');
|
||||
|
||||
// Защита маршрутов
|
||||
router.beforeEach(async (to, from, next) => {
|
||||
const authStore = useAuthStore();
|
||||
|
||||
// Проверяем аутентификацию, если она еще не проверена
|
||||
if (!authStore.isAuthenticated) {
|
||||
try {
|
||||
await authStore.checkAuth();
|
||||
} catch (error) {
|
||||
console.error('Error checking auth:', error);
|
||||
// Если пытаемся перейти на несуществующий маршрут, перенаправляем на главную
|
||||
if (!to.matched.length) {
|
||||
return next({ name: 'home' });
|
||||
}
|
||||
|
||||
// Проверяем аутентификацию, если маршрут требует авторизации
|
||||
if (to.matched.some(record => record.meta.requiresAuth)) {
|
||||
if (!authStore.isAuthenticated) {
|
||||
// Если пользователь не авторизован, перенаправляем на главную
|
||||
return next({ name: 'home' });
|
||||
}
|
||||
|
||||
// Проверяем права администратора, если маршрут требует прав администратора
|
||||
if (to.matched.some(record => record.meta.requiresAdmin) && !authStore.isAdmin) {
|
||||
return next({ name: 'home' });
|
||||
}
|
||||
}
|
||||
|
||||
// Проверка прав доступа
|
||||
if (to.meta.requiresAuth && !authStore.isAuthenticated) {
|
||||
next({ name: 'home' });
|
||||
} else {
|
||||
next();
|
||||
}
|
||||
next();
|
||||
});
|
||||
|
||||
export default router;
|
||||
|
||||
Reference in New Issue
Block a user