auth.ts
1.45 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
import { defineStore } from 'pinia'
export interface UserInfo {
id: string
name: string
roles: string[]
}
interface AuthState {
token: string | null
user: UserInfo | null
}
export const useAuthStore = defineStore('auth', {
state: (): AuthState => ({
token: null,
user: null,
}),
getters: {
isAuthenticated: (s) => !!s.token,
roleSet: (s) => new Set(s.user?.roles || []),
},
actions: {
async login(username: string, password: string) {
if (!username || !password) return false
// Mock: 基于用户名设定角色
const roles = username === 'admin' ? ['admin'] : ['user']
this.token = 'mock-token'
this.user = { id: 'u-' + username, name: username, roles }
// 同步到 qiankun 全局态(如存在)
const actions = (window as any).__QIANKUN_ACTIONS__
actions?.setGlobalState?.({ user: { name: username, roles }, token: this.token })
return true
},
logout() {
this.token = null
this.user = null
const actions = (window as any).__QIANKUN_ACTIONS__
actions?.setGlobalState?.({ user: null, token: null })
},
setFromGlobal(user?: any, token?: string | null) {
if (typeof token !== 'undefined') this.token = token || null
if (user) {
const roles = Array.isArray(user.roles) ? user.roles : []
this.user = { id: 'global', name: user.name || 'User', roles }
}
},
},
persist: {
paths: ['token', 'user'],
},
})