| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- import UserApi, { LoginResult, UserInfo } from "@/api/auth/UserApi";
- import { defineStore } from "pinia"
- const STORAGE_KEY = 'authInfo';
- export const useAuthStore = defineStore('auth', {
- state: () => ({
- token: '',
- expireAt: 0,
- userId: 0,
- userInfo: null as null|UserInfo,
- }),
- actions: {
- async loadLoginState() {
- try {
- const res = await uni.getStorage({ key: STORAGE_KEY });
- if (!res.data)
- throw 'no storage';
- const authInfo = JSON.parse(res.data);
- this.token = authInfo.token;
- this.userId = authInfo.userId;
- this.expireAt = authInfo.expireAt;
- this.userInfo = authInfo.userInfo;
- // 全局变量存储
- const app = getApp();
- if (!app.globalData)
- app.globalData = {};
- app.globalData.token = this.token;
- app.globalData.userId = this.userId;
- app.globalData.userInfo = this.userInfo;
- } catch (error) {
- this.token = '';
- this.userId = 0;
- this.userInfo = null;
- console.log('loadLoginState', error);
- }
- },
- async loginWechart(code: string, res: UniApp.GetUserProfileRes) {
- const loginResult = await UserApi.loginThird({
- code,
- encrypted_data: res.encryptedData,
- iv: res.iv,
- platform: 'wechat',
- raw_data: JSON.parse(res.rawData),
- signature: res.signature,
- })
- this.loginResultHandle(loginResult);
- },
- async loginMobile(mobile: string, password: string) {
- const loginResult = await UserApi.loginWithMobile({
- mobile,
- password,
- })
- this.loginResultHandle(loginResult);
- },
- async loginResultHandle(loginResult: LoginResult) {
- this.token = loginResult.auth.token;
- this.userId = loginResult.mainBodyUserInfo.id;
- this.userInfo = loginResult.mainBodyUserInfo;
- this.expireAt = loginResult.auth.expiresIn + Date.now();
- this.saveLoginState();
- },
- saveLoginState() {
- uni.setStorage({
- key: STORAGE_KEY,
- data: JSON.stringify({
- token: this.token,
- userId: this.userId ,
- expireAt: this.expireAt,
- userInfo: this.userInfo,
- })
- });
- },
- async logout() {
- this.token = '';
- this.userId = 0;
- this.userInfo = null;
- uni.removeStorage({ key: STORAGE_KEY });
- }
- },
- getters: {
- isLogged(state) {
- return state.token != '' && state.userId != 0
- },
- },
- })
|