You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

125 lines
4.4 KiB
TypeScript

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import { defineStore } from 'pinia';
import { login } from '~/services/authService';
import { useCookie } from '#app';
import { getCookie, removeCookie, setCookie } from '@/utils/cookie'
// import redis from '~/utils/redis';
export const useAuthStore = defineStore('auth', {
state: () => ({
token: null as string | null,
user: null as any | null,
refreshToken: null as string | null,
isAuthenticated: false,
isInitialized: false
}),
actions: {
// 初始化认证状态
async initializeAuth() {
// if (import.meta.client) {
// this.token = localStorage.getItem("token");
// this.user = localStorage.getItem("userInfo");
// console.log("meta.client", this.token, this.user);
// }
const tokenCookie = getCookie('token');
// const refreshTokenCookie = getCookie('refreshToken');
// const userCookie = getCookie('userInfo');
console.log("初始化认证状态 获取到的用户信息:", tokenCookie);
if (tokenCookie) {
this.token = tokenCookie;
// this.refreshToken = refreshTokenCookie;
// this.user = JSON.parse(userCookie);
this.isAuthenticated = true;
}
this.isInitialized = true;
return true;
},
// 验证权限
async checkAuth() {
// const nuxtApp = useNuxtApp();
// this.token = nuxtApp.$state.auth?.token;
},
// 登录操作
async login(credentials: { UserName: string, PassWord: string }) {
try {
this.clearUserInfo();
const response = await login(credentials);
// 生成唯一会话 ID推荐使用 uuid 或更安全的随机字符串)
const sessionId = crypto.randomUUID();
// 更新状态
this.token = response.Data.token;
this.refreshToken = response.Data.token;
this.user = response.Data.user;
this.isAuthenticated = true;
// 设置cookie
setCookie('token', response.Data.token);
// setCookie('refreshToken', response.Data.token); // 7天
// setCookie('userInfo', JSON.stringify(response.Data.user));
// 存储会话到 Redis设置过期时间如 1 小时)
// await redis.set(`session:${sessionId}`, JSON.stringify(response.Data.user), 'EX', 3600);
return response;
} catch (error) {
this.logout();
throw error;
}
},
setToken(token: string) {
this.token = token;
},
setUser(user: any) {
this.user = user
},
// 刷新令牌
// async refreshToken() {
// if (!this.refreshToken) {
// throw new Error('No refresh token available');
// }
// try {
// const response = await refreshToken(this.refreshToken);
// // 更新状态
// this.token = response.token;
// // 更新cookie
// const tokenCookie = useCookie('token', { maxAge: 60 * 60 * 24 });
// tokenCookie.value = response.token;
// return response.token;
// } catch (error) {
// this.logout();
// throw error;
// }
// },
logout() {
try {
if (this.token) {
// TODO 需要在 authService 中实现退出登录 api
// await logout();
}
} finally {
this.token = null;
this.refreshToken = null;
this.user = null;
this.isAuthenticated = false;
this.isInitialized = true;
// 清除cookie
removeCookie('token');
// removeCookie('refreshToken');
// removeCookie('userInfo');
}
},
clearUserInfo() {
this.token = null;
this.refreshToken = null;
this.user = null;
// 清除cookie
removeCookie('token');
// removeCookie('refreshToken');
// removeCookie('userInfo');
}
}
});