2025-12-25 13:27:23 +08:00
|
|
|
|
import { defineStore } from 'pinia'
|
|
|
|
|
|
import { ref, computed } from 'vue'
|
|
|
|
|
|
import request from '@/api/request'
|
|
|
|
|
|
|
|
|
|
|
|
export const useAuthStore = defineStore('auth', () => {
|
|
|
|
|
|
const token = ref(localStorage.getItem('token') || '')
|
|
|
|
|
|
const expiresAt = ref(localStorage.getItem('expiresAt') || '')
|
|
|
|
|
|
|
|
|
|
|
|
const isAuthenticated = computed(() => {
|
2026-01-16 11:15:44 +08:00
|
|
|
|
if (!token.value || !expiresAt.value) {
|
|
|
|
|
|
return false
|
|
|
|
|
|
}
|
2025-12-25 13:27:23 +08:00
|
|
|
|
// 检查token是否过期
|
|
|
|
|
|
return new Date(expiresAt.value) > new Date()
|
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
|
|
const login = async (password) => {
|
|
|
|
|
|
try {
|
|
|
|
|
|
const response = await request.post('/Auth/Login', { password })
|
|
|
|
|
|
const { token: newToken, expiresAt: newExpiresAt } = response.data
|
2026-01-16 11:15:44 +08:00
|
|
|
|
|
2025-12-25 13:27:23 +08:00
|
|
|
|
token.value = newToken
|
|
|
|
|
|
expiresAt.value = newExpiresAt
|
2026-01-16 11:15:44 +08:00
|
|
|
|
|
2025-12-25 13:27:23 +08:00
|
|
|
|
localStorage.setItem('token', newToken)
|
|
|
|
|
|
localStorage.setItem('expiresAt', newExpiresAt)
|
2026-01-16 11:15:44 +08:00
|
|
|
|
|
2025-12-25 13:27:23 +08:00
|
|
|
|
return true
|
|
|
|
|
|
} catch (error) {
|
|
|
|
|
|
if (error.response?.status === 401) {
|
|
|
|
|
|
throw new Error('密码错误')
|
|
|
|
|
|
}
|
|
|
|
|
|
throw new Error('登录失败,请稍后重试')
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
const logout = () => {
|
|
|
|
|
|
token.value = ''
|
|
|
|
|
|
expiresAt.value = ''
|
|
|
|
|
|
localStorage.removeItem('token')
|
|
|
|
|
|
localStorage.removeItem('expiresAt')
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
|
token,
|
|
|
|
|
|
expiresAt,
|
|
|
|
|
|
isAuthenticated,
|
|
|
|
|
|
login,
|
2026-01-16 11:15:44 +08:00
|
|
|
|
logout
|
2025-12-25 13:27:23 +08:00
|
|
|
|
}
|
|
|
|
|
|
})
|