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 = localStorage.getItem(STORAGE_KEY); if (!res) throw 'no storage'; const authInfo = JSON.parse(res); this.token = authInfo.token; this.userId = authInfo.userId; this.expireAt = authInfo.expireAt; // 检查token是否过期,如果快要过期,则刷新token if (Date.now() > this.expireAt + 1000 * 3600 * 5) { const refreshResult = await UserApi.refresh(); this.loginResultHandle(refreshResult); this.userInfo = refreshResult.userInfo; } else { this.userInfo = await UserApi.getUserInfo(this.userId); } } catch (error) { this.token = ''; this.userId = 0; this.userInfo = null; console.log('loadLoginState', error); } }, async loginAdmin(account: string, password: string) { const loginResult = await UserApi.loginAdmin({ account, password, }) this.loginResultHandle(loginResult); }, async loginResultHandle(loginResult: LoginResult) { this.token = loginResult.userInfo.token; this.userId = loginResult.userInfo.id; this.userInfo = loginResult.userInfo; this.expireAt = loginResult.userInfo.expiresIn + Date.now(); localStorage.setItem(STORAGE_KEY, JSON.stringify({ token: this.token, userId: this.userId , expireAt: this.expireAt, }) ); }, async logout() { this.token = ''; this.userId = 0; this.userInfo = null; localStorage.removeItem(STORAGE_KEY); } }, getters: { isLogged(state) { return state.token != '' && state.userId != 0 }, }, })