Fix: Prevent automatic logout when starting app offline

Problem:
The application would inadvertently log you out if it was started while offline.
This occurred because the `fetchCurrentUser` action in the `authStore` would attempt to fetch your profile, and if this network request failed (as it does when offline), the catch block would unconditionally call `clearTokens()`. This removed the authentication token, effectively logging you out and preventing access to any cached data or offline functionality.

Solution:
I modified the `fetchCurrentUser` action in `fe/src/stores/auth.ts`:
- The `catch` block now inspects the error.
- `clearTokens()` is only called if the error is a specific HTTP authentication error from the server (401 Unauthorized or 403 Forbidden) when online.
- For network errors (indicating offline status) or other non-auth HTTP errors, tokens are preserved. The user object (`user.value`) might remain null if no cached profile is available, but the authentication token itself is kept.

This change allows the application to remain in a logged-in state when started offline. The service worker can then serve cached API responses, and you can view previously accessed data. Navigation guards rely on `isAuthenticated` (which now remains true offline as long as a token exists), so you are not incorrectly redirected to the login page.
This commit is contained in:
google-labs-jules[bot] 2025-06-07 20:30:52 +00:00
parent 550fac1c0c
commit 6e56e164df

View File

@ -57,6 +57,7 @@ export const useAuthStore = defineStore('auth', () => {
const fetchCurrentUser = async () => {
if (!accessToken.value) {
// No token, so definitely clear any residual state and return.
clearTokens()
return null
}
@ -65,7 +66,28 @@ export const useAuthStore = defineStore('auth', () => {
setUser(response.data)
return response.data
} catch (error: any) {
clearTokens()
// Check if the error is from an Axios request and has a response status
if (error.isAxiosError && error.response) {
const status = error.response.status
if (status === 401 || status === 403) {
// Authentication error from the server, clear tokens.
console.error('Authentication error fetching user, clearing tokens:', error)
clearTokens()
} else {
// Other HTTP error, log it but don't clear tokens.
// The user might be null, but the token remains for other cached calls.
console.error('HTTP error fetching user, token preserved:', error)
}
} else {
// Network error (offline) or other non-HTTP error.
// Log the error but preserve tokens.
// This allows the app to function with cached data if available.
console.error('Network or other error fetching user, token preserved:', error)
}
// In all error cases where tokens are not cleared, return null for the user object.
// The existing user object (if any) will remain until explicitly cleared or overwritten.
// If the intention is to clear the user object on any fetch error, uncomment the next line:
// setUser(null);
return null
}
}