Prevent auto-logout on page refresh

This commit is contained in:
jingrow 2025-11-20 20:11:22 +08:00
parent 19bd8ff104
commit d65b586831
3 changed files with 12 additions and 20 deletions

View File

@ -30,9 +30,7 @@ export function getSessionCookie(): string | null {
// 检查cookie是否过期通过检查session cookie是否存在
export function isCookieExpired(): boolean {
const sessionCookie = getSessionCookie()
const sessionUser = getSessionUser()
// 如果session cookie或user_id不存在认为cookie已过期
return !sessionCookie || !sessionUser
return !sessionCookie
}
export const loginApi = async (username: string, password: string): Promise<LoginResponse> => {

View File

@ -59,20 +59,9 @@ export const useAuthStore = defineStore('auth', () => {
}
const initAuth = async () => {
// 首先检查Cookie是否过期
if (isCookieExpired()) {
// Cookie已过期清除本地状态
if (isAuthenticated.value) {
await logout()
}
return
}
// 首先检查Cookie中的session
const sessionUser = getSessionUser()
if (sessionUser) {
// 首先检查session cookie是否存在
if (!isCookieExpired()) {
try {
// 从Cookie获取到用户验证用户信息
const userInfo = await getUserInfoApi()
user.value = userInfo
isAuthenticated.value = true
@ -83,14 +72,14 @@ export const useAuthStore = defineStore('auth', () => {
return
} catch (error: any) {
console.error('验证用户信息失败:', error)
// 如果是401/403错误说明cookie已过期
if (error.status === 401 || error.status === 403 || error.message?.includes('过期')) {
await logout()
}
return
}
}
// 如果Cookie中没有session检查localStorage
// session cookie不存在检查localStorage
const savedUser = localStorage.getItem('jingrow_user')
const savedAuth = localStorage.getItem('jingrow_authenticated')
@ -102,15 +91,19 @@ export const useAuthStore = defineStore('auth', () => {
// 验证用户信息是否仍然有效
const userInfo = await getUserInfoApi()
user.value = userInfo
localStorage.setItem('jingrow_user', JSON.stringify(userInfo))
} catch (error: any) {
console.error('验证用户信息失败:', error)
// 如果是401/403错误说明cookie已过期
if (error.status === 401 || error.status === 403 || error.message?.includes('过期')) {
await logout()
} else {
logout()
}
}
} else {
if (isAuthenticated.value) {
await logout()
}
}
}

View File

@ -33,7 +33,8 @@ COOKIE_CONFIG = {
"httponly": True,
"samesite": "lax",
"secure": False, # 开发环境可以设为False生产环境建议设为True
"path": "/"
"path": "/",
"max_age": 7 * 24 * 60 * 60 # 7天过期时间
}
# 需要清除的cookie列表