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.

144 lines
4.5 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 type { User, LoginResponse } from '~/types/User';
// import redis from '~/utils/redis';
import { CookieManager } from '~/utils/cookieManager'
import { $fetch } from 'ofetch'
// 认证状态接口
export interface AuthState {
// user: User | null,
token: string | null,
isAuthenticated: boolean,
loading: boolean
}
export const useAuthStore = defineStore('auth', {
state: (): AuthState => ({
// user: null,
token: null,
isAuthenticated: false,
loading: false,
}),
getters: {
isLoggedIn: (state) => state.isAuthenticated,
// currentUser: (state) => state.user,
// userRoles: (state) => state.user?.Roles || [],
// hasRole: (state) => (role: string) => {
// return state.user?.Roles?.includes(role) || false
// },
// hasPermission: (state) => (permission: string) => {
// return state.user?.permissions?.includes(permission) || false
// },
},
actions: {
// 初始化认证状态
initializeAuth() {
// 客户端从Cookie恢复状态
if (CookieManager.isClient) {
this.restoreFromCookies()
}
// 服务端:需要通过插件或中间件处理
},
// 从Cookie恢复状态
restoreFromCookies() {
try {
this.token = AuthService.getAuthToken();
// const user = AuthService.getUserInfo()
if (this.token) {
// this.user = user
this.isAuthenticated = AuthService.isAuthenticated()
}
// this.token = AuthService.getAuthToken();
} catch (error) {
console.error('Failed to restore auth from cookies:', error)
this.clearAuth()
}
},
// 登录
async login(credentials: { UserName: string; PassWord: string }): Promise<LoginResponse> {
this.loading = true
try {
// 使用封装的API客户端
const response = await $fetch<LoginResponse>('/api/auth/login', { method: 'POST', body: credentials });
if (response.Code == 1) {
// this.user = response.Data.user;
this.isAuthenticated = true;
this.token = response.Data.token;
}
return response;
} catch (error) {
this.clearAuth()
return {
Code: -1,
Msg: error as string || '登录失败',
Data: null
}
} finally {
this.loading = false
}
},
// 登出
async logout() {
try {
await $fetch('/api/auth/logout');
} catch (error) {
console.error('Logout API error:', error)
} finally {
// 清除本地状态
this.clearAuth()
// 客户端重定向
if (CookieManager.isClient) {
window.location.href = '/login'
}
}
},
// // 更新用户信息
// updateUser(user: Partial<User>) {
// if (this.user) {
// this.user = { ...this.user, ...user }
// // 更新Cookie中的用户信息
// AuthService.saveUserInfo(this.user)
// }
// },
// 检查认证状态
async checkAuth() {
try {
const isAuthenticated = await AuthService.checkAuth()
if (isAuthenticated) {
// const user = AuthService.getUserInfo()
// if (user) {
// this.user = user
// this.isAuthenticated = true
// }
const token = AuthService.getAuthToken();
if (token) {
this.isAuthenticated = true;
}
} else {
this.clearAuth()
}
return isAuthenticated
} catch (error) {
this.clearAuth()
return false
}
},
// 清除认证状态
clearAuth() {
// this.user = null
this.token = null;
this.isAuthenticated = false
AuthService.clearAuthData()
},
},
})