111 lines
3.2 KiB
TypeScript
111 lines
3.2 KiB
TypeScript
import { defineStore } from 'pinia'
|
||
import { login, getInfo, logout as logoutApi } from '@/api/auth'
|
||
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 {
|
||
const error: any = new Error(response.data.msg || '登录失败')
|
||
error.code = response.data.code
|
||
error.response = response
|
||
throw error
|
||
}
|
||
} catch (error: any) {
|
||
console.error('登录接口调用失败:', error)
|
||
throw error
|
||
}
|
||
},
|
||
|
||
/**
|
||
* 获取用户信息
|
||
*/
|
||
async getInfo() {
|
||
if (this.userInfo) return; // 如果已有用户信息,则不再获取
|
||
try {
|
||
const response = await getInfo();
|
||
if (response.data.code === 0) {
|
||
const user = response.data.data.user;
|
||
this.userInfo = user;
|
||
} else {
|
||
throw new Error(response.data.msg || '获取用户信息失败');
|
||
}
|
||
} catch (error) {
|
||
console.error('获取用户信息失败:', error);
|
||
// 这里可以选择是否要登出
|
||
// await this.logout();
|
||
}
|
||
},
|
||
|
||
/**
|
||
* 用户登出
|
||
*/
|
||
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')
|
||
|
||
// 注意:这里不清除保存的用户名和密码,以便下次自动填充
|
||
}
|
||
},
|
||
|
||
/**
|
||
* 检查登录状态
|
||
*/
|
||
checkAuthStatus() {
|
||
// 从localStorage检查认证状态
|
||
const isAuthenticated = localStorage.getItem('isAuthenticated')
|
||
if (isAuthenticated === 'true') {
|
||
this.isAuthenticated = true
|
||
}
|
||
}
|
||
}
|
||
}) |