Skip to content

Commit

Permalink
feat: implement auth guard on route change
Browse files Browse the repository at this point in the history
  • Loading branch information
doroudi committed Jan 2, 2024
1 parent aea4373 commit 3bf6ce1
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/components.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ declare module 'vue' {
NConfigProvider: typeof import('naive-ui')['NConfigProvider']
NDataTable: typeof import('naive-ui')['NDataTable']
NDialogProvider: typeof import('naive-ui')['NDialogProvider']
NDrawer: typeof import('naive-ui')['NDrawer']
NDrawerContent: typeof import('naive-ui')['NDrawerContent']
NDynamicTags: typeof import('naive-ui')['NDynamicTags']
NForm: typeof import('naive-ui')['NForm']
NFormItem: typeof import('naive-ui')['NFormItem']
Expand Down
6 changes: 6 additions & 0 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,12 @@ router.beforeEach((to, from, next) => {
title = `${to.meta.title} - ${title}`

document.title = title

const isAuthenticated = useAccountStore().isAuthenticated()
const isAuthRequired = to.meta.authRequired ?? true
if (isAuthRequired && !isAuthenticated)
next({ path: '/account/login' })

next()
})
enableMocking().then(() => app.mount('#app'))
1 change: 1 addition & 0 deletions src/pages/Account/login.vue
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ const rules: FormRules = {
meta:
title: Login
layout: auth
authRequired: false
</route>

<template>
Expand Down
6 changes: 6 additions & 0 deletions src/store/account.store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export const useAccountStore = defineStore('account', () => {
const user = ref<Account | null>(null)
const isLoading = ref(false)
const loginFailed = ref(false)

async function login(loginInfo: LoginViewModel): Promise<boolean> {
isLoading.value = true
try {
Expand All @@ -32,11 +33,16 @@ export const useAccountStore = defineStore('account', () => {
user.value = null
}

function isAuthenticated() {
return (user.value?.token && user.value.token !== null) ?? false
}

return {
isLoading,
loginFailed,
login,
logout,
isAuthenticated,
}
})

Expand Down

0 comments on commit 3bf6ce1

Please sign in to comment.