user.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import { store } from '../index'
  2. import { defineStore } from 'pinia'
  3. import { getAccessToken, removeToken } from '@/utils/auth'
  4. import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
  5. import { getInfoApi, loginOutApi } from '@/api/login'
  6. const { wsCache } = useCache()
  7. interface UserVO {
  8. id: number
  9. avatar: string
  10. nickname: string
  11. }
  12. interface UserInfoVO {
  13. permissions: string[]
  14. roles: string[]
  15. isSetUser: boolean
  16. user: UserVO
  17. }
  18. export const useUserStore = defineStore('admin-user', {
  19. state: (): UserInfoVO => ({
  20. permissions: [],
  21. roles: [],
  22. isSetUser: false,
  23. user: {
  24. id: 0,
  25. avatar: '',
  26. nickname: ''
  27. }
  28. }),
  29. getters: {
  30. getPermissions(): string[] {
  31. return this.permissions
  32. },
  33. getRoles(): string[] {
  34. return this.roles
  35. },
  36. getIsSetUser(): boolean {
  37. return this.isSetUser
  38. },
  39. getUser(): UserVO {
  40. return this.user
  41. }
  42. },
  43. actions: {
  44. async setUserInfoAction() {
  45. if (!getAccessToken()) {
  46. this.resetState()
  47. return null
  48. }
  49. let userInfo = wsCache.get(CACHE_KEY.USER)
  50. if (!userInfo) {
  51. userInfo = await getInfoApi()
  52. }
  53. this.permissions = userInfo.permissions
  54. this.roles = userInfo.roles
  55. this.user = userInfo.user
  56. this.isSetUser = true
  57. wsCache.set(CACHE_KEY.USER, userInfo)
  58. },
  59. async loginOut() {
  60. await loginOutApi()
  61. removeToken()
  62. wsCache.clear()
  63. this.resetState()
  64. },
  65. resetState() {
  66. this.permissions = []
  67. this.roles = []
  68. this.isSetUser = false
  69. this.user = {
  70. id: 0,
  71. avatar: '',
  72. nickname: ''
  73. }
  74. }
  75. }
  76. })
  77. export const useUserStoreWithOut = () => {
  78. return useUserStore(store)
  79. }