2025-08-28 07:37:34 +00:00
|
|
|
|
import { defineStore } from 'pinia'
|
2025-12-01 08:25:32 +00:00
|
|
|
|
import { login, logout as logoutApi } from '@/api/auth'
|
2025-08-28 07:37:34 +00:00
|
|
|
|
import type { LoginParams } from '@/types'
|
|
|
|
|
|
|
|
|
|
|
|
interface AuthState {
|
|
|
|
|
|
token: string | null
|
|
|
|
|
|
userInfo: any | null
|
|
|
|
|
|
isAuthenticated: boolean
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
export const useAuthStore = defineStore('auth', {
|
|
|
|
|
|
state: (): AuthState => ({
|
|
|
|
|
|
token: null,
|
|
|
|
|
|
userInfo: null,
|
|
|
|
|
|
isAuthenticated: localStorage.getItem('isAuthenticated') === 'true'
|
|
|
|
|
|
}),
|
|
|
|
|
|
|
|
|
|
|
|
actions: {
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 用户登录
|
|
|
|
|
|
*/
|
|
|
|
|
|
async login(params: LoginParams) {
|
|
|
|
|
|
try {
|
|
|
|
|
|
// 调用登录接口
|
|
|
|
|
|
const response = await login(params)
|
|
|
|
|
|
|
|
|
|
|
|
// 检查响应状态
|
|
|
|
|
|
if (response.status === 200 && response.data.code === 0) {
|
|
|
|
|
|
// 由于服务器使用session判断登录状态,我们只需要设置认证状态为true
|
|
|
|
|
|
this.isAuthenticated = true
|
|
|
|
|
|
|
|
|
|
|
|
// 保存到localStorage,用于页面刷新后保持登录状态
|
|
|
|
|
|
localStorage.setItem('isAuthenticated', 'true')
|
|
|
|
|
|
|
|
|
|
|
|
// 如果选择了记住密码,则保存用户名和密码
|
|
|
|
|
|
if (params.rememberMe) {
|
|
|
|
|
|
localStorage.setItem('savedUsername', params.username)
|
|
|
|
|
|
localStorage.setItem('savedPassword', params.password)
|
|
|
|
|
|
} else {
|
|
|
|
|
|
// 清除保存的用户名和密码
|
|
|
|
|
|
localStorage.removeItem('savedUsername')
|
|
|
|
|
|
localStorage.removeItem('savedPassword')
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
return response.data
|
|
|
|
|
|
} else {
|
|
|
|
|
|
throw new Error(response.data.msg || '登录失败')
|
|
|
|
|
|
}
|
|
|
|
|
|
} catch (error: any) {
|
|
|
|
|
|
console.error('登录接口调用失败:', error)
|
|
|
|
|
|
throw error
|
|
|
|
|
|
}
|
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 用户登出
|
|
|
|
|
|
*/
|
2025-12-01 08:25:32 +00:00
|
|
|
|
async logout() {
|
|
|
|
|
|
try {
|
|
|
|
|
|
// 调用后端logout接口清除session
|
|
|
|
|
|
await logoutApi()
|
|
|
|
|
|
} catch (error) {
|
|
|
|
|
|
console.warn('服务器退出登录失败,仅清除本地状态:', error)
|
|
|
|
|
|
} finally {
|
|
|
|
|
|
// 清除本地状态
|
|
|
|
|
|
this.token = null
|
|
|
|
|
|
this.userInfo = null
|
|
|
|
|
|
this.isAuthenticated = false
|
|
|
|
|
|
|
|
|
|
|
|
// 清除localStorage中的认证状态
|
|
|
|
|
|
localStorage.removeItem('isAuthenticated')
|
|
|
|
|
|
|
|
|
|
|
|
// 注意:这里不清除保存的用户名和密码,以便下次自动填充
|
|
|
|
|
|
}
|
2025-08-28 07:37:34 +00:00
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 检查登录状态
|
|
|
|
|
|
*/
|
|
|
|
|
|
checkAuthStatus() {
|
|
|
|
|
|
// 从localStorage检查认证状态
|
|
|
|
|
|
const isAuthenticated = localStorage.getItem('isAuthenticated')
|
|
|
|
|
|
if (isAuthenticated === 'true') {
|
|
|
|
|
|
this.isAuthenticated = true
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
})
|