| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116 |
- 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,
- loginType: 0,
- }),
- actions: {
- async loadLoginState() {
- try {
- const res = await uni.getStorage({ key: STORAGE_KEY });
- if (!res.data)
- return false;
- const authInfo = JSON.parse(res.data);
- this.token = authInfo.token;
- this.userId = authInfo.userId;
- this.userInfo = authInfo.userInfo;
- this.loginType = authInfo.loginType;
- setToken(this.token);
- return true;
- } catch (error) {
- this.token = '';
- this.userId = 0;
- this.userInfo = null;
- setToken('');
- console.log('loadLoginState', error);
- return false;
- }
- },
- 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, 0);
- },
- async loginMobile(account: string, password: string, loginType: number) {
- let loginResult;
- if (loginType == 0) {
- loginResult = await UserApi.login({
- account,
- password,
- })
- } else if (loginType == 1) {
- loginResult = await UserApi.loginAdmin({
- account,
- password,
- })
- } else
- throw 'login type error';
- this.loginResultHandle(loginResult, loginType);
- },
- async loginResultHandle(loginResult: LoginResult, loginType: number) {
- this.token = loginResult.token;
- this.userId = loginResult.userInfo.id;
- this.userInfo = loginResult.userInfo;
- this.loginType = loginType;
- setToken(this.token);
- this.saveLoginState();
- },
- async logout() {
- this.token = '';
- this.userId = 0;
- this.userInfo = null;
- setToken('');
- uni.removeStorage({ key: STORAGE_KEY });
- },
- saveLoginState() {
- uni.setStorage({
- key: STORAGE_KEY,
- data: JSON.stringify({
- token: this.token,
- userId: this.userId ,
- expireAt: this.expireAt,
- userInfo: this.userInfo,
- loginType: this.loginType,
- })
- });
- },
- getInternalAuth() {
- return {
- token: this.token,
- userId: this.userId ,
- expireAt: this.expireAt,
- userInfo: this.userInfo,
- loginType: this.loginType,
- }
- },
- },
- getters: {
- isAdmin(state) {
- return state.loginType === 1;
- },
- isLogged(state) {
- return state.token != '' && state.userId != 0
- },
- },
- })
- function setToken(token: string) {
- const app = getApp();
- if (!!app.globalData)
- app.globalData = {};
- return app.globalData!.token = token;
- }
|