import { defineStore } from 'pinia' import { store } from '@/stores' interface UserState { access_token: string tokenExpiresAt: number tenant_id: string pushRecordId: string needFaceId: boolean } export const useUserStore = defineStore('user', { state: (): UserState => ({ access_token: '', tokenExpiresAt: 0, tenant_id: '1', pushRecordId: '', needFaceId: false, }), actions: { setAccessToken(token: string, expiresIn?: number | string) { // expires_in 的单位为秒;未返回时使用后端约定的 12 小时。 const seconds = expiresIn == null || expiresIn === '' ? NaN : Number(expiresIn) this.access_token = token this.tokenExpiresAt = Date.now() + (Number.isFinite(seconds) && seconds >= 0 ? seconds : 12 * 60 * 60) * 1000 this.$persist() }, hasValidSession() { if (!this.access_token) return false if (!Number.isFinite(this.tokenExpiresAt) || Date.now() >= this.tokenExpiresAt) { this.LogOut() return false } return true }, setPushRecordId(id: string) { // 当前链接没有可核对的用户 ID,不能把旧业务的 token 用到另一条链接。 if (id !== this.pushRecordId) this.LogOut() this.pushRecordId = id this.$persist() }, setNeedFaceId(flag: boolean) { this.needFaceId = flag }, LogOut() { this.access_token = '' this.tokenExpiresAt = 0 this.needFaceId = false this.$persist() }, }, persist: { key: 'user-store', storage: localStorage, pick: ['access_token', 'tokenExpiresAt', 'needFaceId', 'tenant_id', 'pushRecordId'], }, }) export function useUserStoreWithOut() { return useUserStore(store) }