user.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. const { wsCache } = useCache()
  6. interface UserVO {
  7. id: number
  8. avatar: string
  9. nickname: string
  10. }
  11. interface UserInfoVO {
  12. permissions: string[]
  13. roles: string[]
  14. isSetUser: boolean
  15. user: UserVO
  16. }
  17. export const useUserStore = defineStore('admin-user', {
  18. state: (): UserInfoVO => ({
  19. permissions: [],
  20. roles: [],
  21. isSetUser: false,
  22. user: {
  23. id: 0,
  24. avatar: '',
  25. nickname: ''
  26. }
  27. }),
  28. getters: {
  29. getPermissions(): string[] {
  30. return this.permissions
  31. },
  32. getRoles(): string[] {
  33. return this.roles
  34. },
  35. getIsSetUser(): boolean {
  36. return this.isSetUser
  37. },
  38. getUser(): UserVO {
  39. return this.user
  40. }
  41. },
  42. actions: {
  43. async setUserInfoAction(userInfo: UserInfoVO) {
  44. if (!getAccessToken()) {
  45. this.resetState()
  46. return null
  47. }
  48. this.permissions = userInfo.permissions
  49. this.roles = userInfo.roles
  50. this.user = userInfo.user
  51. this.isSetUser = true
  52. wsCache.set(CACHE_KEY.USER, userInfo)
  53. },
  54. loginOut() {
  55. removeToken()
  56. wsCache.clear()
  57. this.resetState()
  58. },
  59. resetState() {
  60. this.permissions = []
  61. this.roles = []
  62. this.isSetUser = false
  63. this.user = {
  64. id: 0,
  65. avatar: '',
  66. nickname: ''
  67. }
  68. }
  69. }
  70. })
  71. export const useUserStoreWithOut = () => {
  72. return useUserStore(store)
  73. }