auth.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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 = await uni.getStorage({ key: STORAGE_KEY });
  15. if (!res.data)
  16. throw 'no storage';
  17. const authInfo = JSON.parse(res.data);
  18. this.token = authInfo.token;
  19. this.userId = authInfo.userId;
  20. this.expireAt = authInfo.expireAt;
  21. this.userInfo = authInfo.userInfo;
  22. // 全局变量存储
  23. const app = getApp();
  24. if (!app.globalData)
  25. app.globalData = {};
  26. app.globalData.token = this.token;
  27. app.globalData.userId = this.userId;
  28. app.globalData.userInfo = this.userInfo;
  29. } catch (error) {
  30. this.token = '';
  31. this.userId = 0;
  32. this.userInfo = null;
  33. console.log('loadLoginState', error);
  34. }
  35. },
  36. async loginWechart(code: string, res: UniApp.GetUserProfileRes) {
  37. const loginResult = await UserApi.loginThird({
  38. code,
  39. encrypted_data: res.encryptedData,
  40. iv: res.iv,
  41. platform: 'wechat',
  42. raw_data: JSON.parse(res.rawData),
  43. signature: res.signature,
  44. })
  45. this.loginResultHandle(loginResult);
  46. },
  47. async loginMobile(mobile: string, password: string) {
  48. const loginResult = await UserApi.loginWithMobile({
  49. mobile,
  50. password,
  51. })
  52. this.loginResultHandle(loginResult);
  53. },
  54. async loginResultHandle(loginResult: LoginResult) {
  55. this.token = loginResult.auth.token;
  56. this.userId = loginResult.mainBodyUserInfo.id;
  57. this.userInfo = loginResult.mainBodyUserInfo;
  58. this.expireAt = loginResult.auth.expiresIn + Date.now();
  59. this.saveLoginState();
  60. },
  61. saveLoginState() {
  62. uni.setStorage({
  63. key: STORAGE_KEY,
  64. data: JSON.stringify({
  65. token: this.token,
  66. userId: this.userId ,
  67. expireAt: this.expireAt,
  68. userInfo: this.userInfo,
  69. })
  70. });
  71. },
  72. async logout() {
  73. this.token = '';
  74. this.userId = 0;
  75. this.userInfo = null;
  76. uni.removeStorage({ key: STORAGE_KEY });
  77. }
  78. },
  79. getters: {
  80. isLogged(state) {
  81. return state.token != '' && state.userId != 0
  82. },
  83. },
  84. })