|
|
|
import { defineStore } from 'pinia'
|
|
|
|
import type { ChatInfoType, UserInfoType, UserStateType } from './index.d'
|
|
|
|
import { router } from '@/router'
|
|
|
|
import { PageEnum } from '@/enums/pageEnum'
|
|
|
|
import { ACCESS_TOKEN_KEY, CHAT_INFO_KEY, USER_INFO_KEY } from '@/enums/cacheEnum'
|
|
|
|
import { token } from '@/api/base/login'
|
|
|
|
import { chatInfo } from '@/api/base/message'
|
|
|
|
import type { TokenParams } from '@/api/base/login'
|
|
|
|
import crypto from '@/utils/crypto'
|
|
|
|
|
|
|
|
export const useUserStore = defineStore('useUserStore', {
|
|
|
|
state: (): UserStateType => {
|
|
|
|
return {
|
|
|
|
token: null,
|
|
|
|
userInfo: null,
|
|
|
|
chatInfo: null,
|
|
|
|
}
|
|
|
|
},
|
|
|
|
getters: {
|
|
|
|
getToken(): string | null {
|
|
|
|
return this.token ? crypto.decryptAES(this.token, crypto.localKey) : null
|
|
|
|
},
|
|
|
|
getUserInfo(): UserInfoType | null {
|
|
|
|
return this.userInfo ? JSON.parse(crypto.decryptAES(this.userInfo, crypto.localKey)) : null
|
|
|
|
},
|
|
|
|
getChatInfo(): ChatInfoType | null {
|
|
|
|
return this.chatInfo ? JSON.parse(crypto.decryptAES(this.chatInfo, crypto.localKey)) : null
|
|
|
|
},
|
|
|
|
},
|
|
|
|
actions: {
|
|
|
|
setToken(token: string) {
|
|
|
|
this.token = token
|
|
|
|
},
|
|
|
|
|
|
|
|
setUserInfo(userInfo: string) {
|
|
|
|
this.userInfo = userInfo
|
|
|
|
},
|
|
|
|
|
|
|
|
setChatInfo(chatInfo: string) {
|
|
|
|
this.chatInfo = chatInfo
|
|
|
|
},
|
|
|
|
|
|
|
|
async login(params: TokenParams) {
|
|
|
|
return new Promise<any>((resolve, reject) => {
|
|
|
|
token(params).then((res) => {
|
|
|
|
this.setToken(crypto.encryptAES(res.access_token, crypto.localKey))
|
|
|
|
this.setUserInfo(crypto.encryptAES(JSON.stringify(res), crypto.localKey))
|
|
|
|
this.getChatInfoFun()
|
|
|
|
resolve(res)
|
|
|
|
}).catch((err) => {
|
|
|
|
reject(err)
|
|
|
|
})
|
|
|
|
})
|
|
|
|
},
|
|
|
|
|
|
|
|
getChatInfoFun() {
|
|
|
|
chatInfo().then((res) => {
|
|
|
|
this.setChatInfo(crypto.encryptAES(JSON.stringify(res), crypto.localKey))
|
|
|
|
})
|
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @description: logout
|
|
|
|
*/
|
|
|
|
async logout(goLogin = false) {
|
|
|
|
this.$reset()
|
|
|
|
localStorage.clear()
|
|
|
|
// 清空数据
|
|
|
|
goLogin && router.push(PageEnum.BASE_LOGIN)
|
|
|
|
},
|
|
|
|
},
|
|
|
|
persist: [
|
|
|
|
{
|
|
|
|
paths: ['token'],
|
|
|
|
key: ACCESS_TOKEN_KEY,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
paths: ['userInfo'],
|
|
|
|
key: USER_INFO_KEY,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
paths: ['chatInfo'],
|
|
|
|
key: CHAT_INFO_KEY,
|
|
|
|
},
|
|
|
|
],
|
|
|
|
})
|