auth.ts 1.45 KB
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'],
  },
})