auth.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { defineStore } from 'pinia'
  2. import { TOKEN_KEY } from '~/constants'
  3. import type { PlaymateInfoVO, UserProfileVO, WalletUserVO } from '~/types/api'
  4. export const useAuthStore = defineStore('auth', {
  5. state: () => ({
  6. token: null as string | null,
  7. userProfile: null as UserProfileVO | null,
  8. wallet: null as WalletUserVO | null,
  9. playmateInfo: null as PlaymateInfoVO | null,
  10. isInitialized: false,
  11. }),
  12. getters: {
  13. isAuthenticated: state => !!state.token,
  14. isPlaymate: state => state.userProfile?.playmate ?? false,
  15. },
  16. actions: {
  17. // 初始化时从 localStorage 恢复登录状态(仅在客户端调用)
  18. restoreAuth() {
  19. if (import.meta.client) {
  20. this.token = localStorage.getItem(TOKEN_KEY)
  21. this.isInitialized = true
  22. }
  23. },
  24. // 设置 token 并持久化
  25. setAuth(token: string) {
  26. this.token = token
  27. if (import.meta.client) {
  28. localStorage.setItem(TOKEN_KEY, token)
  29. }
  30. },
  31. setUserProfile(userProfile: UserProfileVO) {
  32. this.userProfile = userProfile
  33. },
  34. setWallet(wallet: WalletUserVO) {
  35. this.wallet = wallet
  36. },
  37. setPlaymateInfo(playmateInfo: PlaymateInfoVO) {
  38. this.playmateInfo = playmateInfo
  39. },
  40. // 退出登录
  41. logout() {
  42. this.token = null
  43. if (import.meta.client) {
  44. localStorage.removeItem(TOKEN_KEY)
  45. }
  46. },
  47. },
  48. })