user.ts 2.3 KB

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