import { createRouter, createWebHistory } from 'vue-router' import axios from "axios" import Register from '../views/Register.vue' import LogIn from '../views/LogIn.vue' import HomeView from '../views/HomeView.vue' import AllBrands from '../views/AllBrands.vue' import AllCustomers from '../views/AllCustomers.vue' import NewCustomer from '../views/NewCustomer.vue' import AllItems from '../views/AllItems.vue' import NewItem from '../views/NewItem.vue' import NewInvoice from '../views/NewInvoice.vue' import EditInvoice from '../views/EditInvoice.vue' import ViewInvoice from '../views/ViewInvoice.vue' const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), routes: [ { path: '/register', name: 'register', component: Register, meta: { requiresAuth: false } }, { path: '/login', name: 'log in', component: LogIn, meta: { requiresAuth: false } }, { path: '/', name: 'home', component: HomeView, meta: { requiresAuth: true } }, { path: '/brand', name: 'brand', component: AllBrands, meta: { requiresAuth: true } }, { path: '/customer', name: 'customer', component: AllCustomers, meta: { requiresAuth: true } }, { path: '/customer/new', name: 'new-customer', component: NewCustomer, meta: { requiresAuth: true } }, { path: '/item', name: 'item', component: AllItems, meta: { requiresAuth: true } }, { path: '/item/new', name: 'new-item', component: NewItem, meta: { requiresAuth: true } }, { path: '/invoice/new', name: 'new-invoice', component: NewInvoice, meta: { requiresAuth: true } }, { path: '/invoice/edit/:id', name: 'edit-invoice', component: EditInvoice, meta: { requiresAuth: true } }, { path: '/invoice/view/:id', name: 'view-invoice', component: ViewInvoice, meta: { requiresAuth: true } }, ] }) router.beforeEach((to, _, next) => { if (to.meta.requiresAuth) { if (!localStorage.getItem('authToken')) { next(`/login?redirect=${to.fullPath}&reason=not_logged_in`) } else { // refresh the token on every route change // this makes sure token isn't expired axios.post( '/auth/refresh', { RefreshToken: localStorage.getItem('refToken') } ).then(res => { localStorage.setItem('authToken', res.data.auth_token) next() }).catch(_ => { // if error is 401 then axios interceptor will automatically handle it next(`/login?redirect=${to.fullPath}&reason=err`) }) } } else { next() } }) export default router