diff --git a/apps/jingrow/frontend/src/shared/api/auth.ts b/apps/jingrow/frontend/src/shared/api/auth.ts index a7aa533..d17405f 100644 --- a/apps/jingrow/frontend/src/shared/api/auth.ts +++ b/apps/jingrow/frontend/src/shared/api/auth.ts @@ -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 => { diff --git a/apps/jingrow/frontend/src/shared/stores/auth.ts b/apps/jingrow/frontend/src/shared/stores/auth.ts index 1b5b4af..c14703a 100644 --- a/apps/jingrow/frontend/src/shared/stores/auth.ts +++ b/apps/jingrow/frontend/src/shared/stores/auth.ts @@ -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() + } } } diff --git a/apps/jingrow/jingrow/api/auth_api.py b/apps/jingrow/jingrow/api/auth_api.py index 2bded68..a077559 100644 --- a/apps/jingrow/jingrow/api/auth_api.py +++ b/apps/jingrow/jingrow/api/auth_api.py @@ -33,7 +33,8 @@ COOKIE_CONFIG = { "httponly": True, "samesite": "lax", "secure": False, # 开发环境可以设为False,生产环境建议设为True - "path": "/" + "path": "/", + "max_age": 7 * 24 * 60 * 60 # 7天过期时间(秒) } # 需要清除的cookie列表