user.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import { VuexModule, Module, Action, Mutation, getModule } from 'vuex-module-decorators'
  2. import { login, logout, getUserInfo } from '@/api/users'
  3. import { getToken, setToken, removeToken } from '@/utils/cookies'
  4. import store from '@/store'
  5. export interface IUserState {
  6. token: string
  7. name: string
  8. avatar: string
  9. introduction: string
  10. roles: string[]
  11. }
  12. @Module({ dynamic: true, store, name: 'user' })
  13. class User extends VuexModule implements IUserState {
  14. public token = getToken() || ''
  15. public name = ''
  16. public avatar = ''
  17. public introduction = ''
  18. public roles: string[] = []
  19. @Mutation
  20. private SET_TOKEN(token: string) {
  21. this.token = token
  22. }
  23. @Mutation
  24. private SET_NAME(name: string) {
  25. this.name = name
  26. }
  27. @Mutation
  28. private SET_AVATAR(avatar: string) {
  29. this.avatar = avatar
  30. }
  31. @Mutation
  32. private SET_INTRODUCTION(introduction: string) {
  33. this.introduction = introduction
  34. }
  35. @Mutation
  36. private SET_ROLES(roles: string[]) {
  37. this.roles = roles
  38. }
  39. @Action
  40. public async Login(userInfo: { username: string, password: string }) {
  41. let { username, password } = userInfo
  42. username = username.trim()
  43. const { data } = await login({ username, password })
  44. setToken(data.accessToken)
  45. this.SET_TOKEN(data.accessToken)
  46. }
  47. @Action
  48. public ResetToken() {
  49. removeToken()
  50. this.SET_TOKEN('')
  51. this.SET_ROLES([])
  52. }
  53. @Action
  54. public async GetUserInfo() {
  55. if (this.token === '') {
  56. throw Error('GetUserInfo: token is undefined!')
  57. }
  58. const { data } = await getUserInfo({ /* Your params here */ })
  59. if (!data) {
  60. throw Error('Verification failed, please Login again.')
  61. }
  62. const { roles, name, avatar, introduction } = data.user
  63. // roles must be a non-empty array
  64. if (!roles || roles.length <= 0) {
  65. throw Error('GetUserInfo: roles must be a non-null array!')
  66. }
  67. this.SET_ROLES(roles)
  68. this.SET_NAME(name)
  69. this.SET_AVATAR(avatar)
  70. this.SET_INTRODUCTION(introduction)
  71. }
  72. @Action
  73. public async LogOut() {
  74. if (this.token === '') {
  75. throw Error('LogOut: token is undefined!')
  76. }
  77. await logout()
  78. removeToken()
  79. this.SET_TOKEN('')
  80. this.SET_ROLES([])
  81. }
  82. }
  83. export const UserModule = getModule(User)