user.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import { store } from '../index'
  2. import { defineStore } from 'pinia'
  3. import { getAccessToken, removeToken } from '@/utils/auth'
  4. import { 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. user: UserVO
  15. }
  16. export const useUserStore = defineStore({
  17. id: 'admin-user',
  18. state: (): UserInfoVO => ({
  19. permissions: [],
  20. roles: [],
  21. user: {
  22. id: 0,
  23. avatar: '',
  24. nickname: ''
  25. }
  26. }),
  27. getters: {
  28. getPermissions(): string[] {
  29. return this.permissions
  30. },
  31. getRoles(): string[] {
  32. return this.roles
  33. },
  34. getUser(): UserVO {
  35. return this.user
  36. }
  37. },
  38. actions: {
  39. async setUserInfoAction(userInfo: UserInfoVO) {
  40. if (!getAccessToken()) {
  41. this.resetState()
  42. return null
  43. }
  44. this.permissions = userInfo.permissions
  45. this.roles = userInfo.roles
  46. this.user = userInfo.user
  47. wsCache.set('user', userInfo)
  48. },
  49. loginOut() {
  50. removeToken()
  51. wsCache.clear()
  52. this.resetState()
  53. },
  54. resetState() {
  55. this.permissions = []
  56. this.roles = []
  57. this.user = {
  58. id: 0,
  59. avatar: '',
  60. nickname: ''
  61. }
  62. }
  63. }
  64. })
  65. export const useUserStoreWithOut = () => {
  66. return useUserStore(store)
  67. }