| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 |
- import { defineStore } from 'pinia'
- import { TOKEN_KEY } from '~/constants'
- import type { PlaymateInfoVO, UserProfileVO, WalletUserVO } from '~/types/api'
- export const useAuthStore = defineStore('auth', {
- state: () => ({
- token: null as string | null,
- userProfile: null as UserProfileVO | null,
- wallet: null as WalletUserVO | null,
- playmateInfo: null as PlaymateInfoVO | null,
- isInitialized: false,
- }),
- getters: {
- isAuthenticated: state => !!state.token,
- isPlaymate: state => state.userProfile?.playmate ?? false,
- },
- actions: {
- // 初始化时从 localStorage 恢复登录状态(仅在客户端调用)
- restoreAuth() {
- if (import.meta.client) {
- this.token = localStorage.getItem(TOKEN_KEY)
- this.isInitialized = true
- }
- },
- // 设置 token 并持久化
- setAuth(token: string) {
- this.token = token
- if (import.meta.client) {
- localStorage.setItem(TOKEN_KEY, token)
- }
- },
- setUserProfile(userProfile: UserProfileVO) {
- this.userProfile = userProfile
- },
- setWallet(wallet: WalletUserVO) {
- this.wallet = wallet
- },
- setPlaymateInfo(playmateInfo: PlaymateInfoVO) {
- this.playmateInfo = playmateInfo
- },
- // 退出登录
- logout() {
- this.token = null
- if (import.meta.client) {
- localStorage.removeItem(TOKEN_KEY)
- }
- },
- },
- })
|