auth.ts
1.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { computed, ref } from 'vue'
import { defineStore } from 'pinia'
import type { AuthUser, LoginResponse, MenuNode } from '@/types/auth'
import { findFirstMenuPath, flattenMenuPaths } from '@/utils/menu'
export const useAuthStore = defineStore('auth', () => {
const token = ref(localStorage.getItem('token') || '')
const user = ref<AuthUser | null>(JSON.parse(localStorage.getItem('user') || 'null'))
const menus = ref<MenuNode[]>(JSON.parse(localStorage.getItem('menus') || '[]'))
const homePath = ref(localStorage.getItem('homePath') || '')
const isAdmin = computed(() => user.value?.role === 'admin')
const flatMenuPaths = computed(() => flattenMenuPaths(menus.value))
const fallbackHomePath = computed(() => homePath.value || findFirstMenuPath(menus.value) || '/dashboard')
function setToken(t: string) {
token.value = t
localStorage.setItem('token', t)
}
function setSession(payload: LoginResponse) {
token.value = payload.token
user.value = payload.user
menus.value = payload.menus || []
homePath.value = payload.homePath || findFirstMenuPath(menus.value) || '/dashboard'
localStorage.setItem('token', token.value)
localStorage.setItem('user', JSON.stringify(user.value))
localStorage.setItem('menus', JSON.stringify(menus.value))
localStorage.setItem('homePath', homePath.value)
}
function hasPath(path: string) {
return flatMenuPaths.value.includes(path)
}
function logout() {
token.value = ''
user.value = null
menus.value = []
homePath.value = ''
localStorage.removeItem('token')
localStorage.removeItem('user')
localStorage.removeItem('menus')
localStorage.removeItem('homePath')
}
return {
token,
user,
menus,
homePath,
isAdmin,
flatMenuPaths,
fallbackHomePath,
setToken,
setSession,
hasPath,
logout,
}
})