aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorVidhu Kant Sharma <vidhukant@vidhukant.com>2024-07-13 18:06:14 +0530
committerVidhu Kant Sharma <vidhukant@vidhukant.com>2024-07-13 18:06:14 +0530
commitacd2e2e0ec72a383d705c2fd62f62d4b0ee5335e (patch)
treed0b5dadac1f9a43fb94b90b63978bd27b8df695d
parent5120a20c995dc5f90d22890b58b29e37136b761a (diff)
refreshing the token on every page change; also makes sure that user is logged in with a valid session everytime
-rw-r--r--src/router/index.ts42
1 files changed, 29 insertions, 13 deletions
diff --git a/src/router/index.ts b/src/router/index.ts
index d498728..73d7499 100644
--- a/src/router/index.ts
+++ b/src/router/index.ts
@@ -1,4 +1,5 @@
import { createRouter, createWebHistory } from 'vue-router'
+import axios from "axios"
import Register from '../views/Register.vue'
import LogIn from '../views/LogIn.vue'
@@ -19,74 +20,89 @@ const router = createRouter({
path: '/register',
name: 'register',
component: Register,
- meta: { isAuth: false }
+ meta: { requiresAuth: false }
},
{
path: '/login',
name: 'log in',
component: LogIn,
- meta: { isAuth: false }
+ meta: { requiresAuth: false }
},
{
path: '/',
name: 'home',
component: HomeView,
- meta: { isAuth: true }
+ meta: { requiresAuth: true }
},
{
path: '/brand',
name: 'brand',
component: AllBrands,
- meta: { isAuth: true }
+ meta: { requiresAuth: true }
},
{
path: '/customer',
name: 'customer',
component: AllCustomers,
- meta: { isAuth: true }
+ meta: { requiresAuth: true }
},
{
path: '/customer/new',
name: 'new-customer',
component: NewCustomer,
- meta: { isAuth: true }
+ meta: { requiresAuth: true }
},
{
path: '/item',
name: 'item',
component: AllItems,
- meta: { isAuth: true }
+ meta: { requiresAuth: true }
},
{
path: '/item/new',
name: 'new-item',
component: NewItem,
- meta: { isAuth: true }
+ meta: { requiresAuth: true }
},
{
path: '/invoice/new',
name: 'new-invoice',
component: NewInvoice,
- meta: { isAuth: true }
+ meta: { requiresAuth: true }
},
{
path: '/invoice/edit/:id',
name: 'edit-invoice',
component: EditInvoice,
- meta: { isAuth: true }
+ meta: { requiresAuth: true }
},
{
path: '/invoice/view/:id',
name: 'view-invoice',
component: ViewInvoice,
- meta: { isAuth: true }
+ meta: { requiresAuth: true }
},
]
})
router.beforeEach((to, _, next) => {
- if (to.meta.isAuth && !localStorage.getItem('authToken')) {
- next(`/login?redirect=${to.fullPath}`)
+ 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()
}