auth.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import UserApi, { LoginResult, UserInfo } from "@/api/auth/UserApi";
  2. import { defineStore } from "pinia"
  3. const STORAGE_KEY = 'authInfo';
  4. export const useAuthStore = defineStore('auth', {
  5. state: () => ({
  6. token: '',
  7. expireAt: 0,
  8. userId: 0,
  9. userInfo: null as null|UserInfo,
  10. }),
  11. actions: {
  12. async loadLoginState() {
  13. try {
  14. const res = localStorage.getItem(STORAGE_KEY);
  15. if (!res)
  16. throw 'no storage';
  17. const authInfo = JSON.parse(res);
  18. this.token = authInfo.token;
  19. this.userId = authInfo.userId;
  20. this.expireAt = authInfo.expireAt;
  21. // 检查token是否过期,如果快要过期,则刷新token
  22. if (Date.now() > this.expireAt + 1000 * 3600 * 5) {
  23. const refreshResult = await UserApi.refresh();
  24. this.loginResultHandle(refreshResult);
  25. this.userInfo = refreshResult.userInfo;
  26. } else {
  27. this.userInfo = await UserApi.getUserInfo(this.userId);
  28. }
  29. } catch (error) {
  30. this.token = '';
  31. this.userId = 0;
  32. this.userInfo = null;
  33. console.log('loadLoginState', error);
  34. }
  35. },
  36. async loginAdmin(account: string, password: string) {
  37. const loginResult = await UserApi.loginAdmin({
  38. account,
  39. password,
  40. })
  41. this.loginResultHandle(loginResult);
  42. },
  43. async loginResultHandle(loginResult: LoginResult) {
  44. this.token = loginResult.userInfo.token;
  45. this.userId = loginResult.userInfo.id;
  46. this.userInfo = loginResult.userInfo;
  47. this.expireAt = loginResult.userInfo.expiresIn + Date.now();
  48. localStorage.setItem(STORAGE_KEY,
  49. JSON.stringify({
  50. token: this.token,
  51. userId: this.userId ,
  52. expireAt: this.expireAt,
  53. })
  54. );
  55. },
  56. async logout() {
  57. this.token = '';
  58. this.userId = 0;
  59. this.userInfo = null;
  60. localStorage.removeItem(STORAGE_KEY);
  61. }
  62. },
  63. getters: {
  64. isLogged(state) {
  65. return state.token != '' && state.userId != 0
  66. },
  67. },
  68. })