user.ts 1.8 KB

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