fix(auth): Improve auth error handling without token clearing
This commit is contained in:
@@ -1,3 +1,5 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:dio/dio.dart';
|
||||
import '../utils/debug_logger.dart';
|
||||
|
||||
@@ -136,6 +138,7 @@ class ApiAuthInterceptor extends Interceptor {
|
||||
final path = err.requestOptions.path;
|
||||
|
||||
// Handle authentication errors consistently
|
||||
// IMPORTANT: Never auto-logout. Instead, notify the app to show connection issue page
|
||||
if (statusCode == 401) {
|
||||
// Do not clear the token for public or optional-auth endpoints.
|
||||
// A 401 here may indicate endpoint-level permission or server config,
|
||||
@@ -143,8 +146,9 @@ class ApiAuthInterceptor extends Interceptor {
|
||||
final requiresAuth = _requiresAuth(path);
|
||||
final optionalAuth = _hasOptionalAuth(path);
|
||||
if (requiresAuth && !optionalAuth) {
|
||||
DebugLogger.auth('401 Unauthorized on $path - clearing auth token');
|
||||
_clearAuthToken();
|
||||
_notifyAuthFailure(
|
||||
'401 Unauthorized on $path - notifying app without clearing token',
|
||||
);
|
||||
} else {
|
||||
DebugLogger.auth(
|
||||
'401 on public/optional endpoint $path - keeping auth token',
|
||||
@@ -155,10 +159,9 @@ class ApiAuthInterceptor extends Interceptor {
|
||||
final requiresAuth = _requiresAuth(path);
|
||||
final optionalAuth = _hasOptionalAuth(path);
|
||||
if (requiresAuth && !optionalAuth) {
|
||||
DebugLogger.auth(
|
||||
'403 Forbidden on protected endpoint $path - clearing auth token',
|
||||
_notifyAuthFailure(
|
||||
'403 Forbidden on protected endpoint $path - notifying app without clearing token',
|
||||
);
|
||||
_clearAuthToken();
|
||||
} else {
|
||||
DebugLogger.auth(
|
||||
'403 Forbidden on public/optional endpoint $path - keeping auth token',
|
||||
@@ -169,9 +172,24 @@ class ApiAuthInterceptor extends Interceptor {
|
||||
handler.next(err);
|
||||
}
|
||||
|
||||
/// Clear auth token and notify callbacks
|
||||
/// Note: This should only be called for explicit logout, not for connection errors
|
||||
|
||||
void _clearAuthToken() {
|
||||
_authToken = null;
|
||||
final future = onTokenInvalidated?.call();
|
||||
if (future != null) {
|
||||
unawaited(future);
|
||||
}
|
||||
}
|
||||
|
||||
void _notifyAuthFailure(String message) {
|
||||
DebugLogger.auth(message);
|
||||
onAuthTokenInvalid?.call();
|
||||
onTokenInvalidated?.call();
|
||||
}
|
||||
|
||||
/// Explicitly clear auth token for logout scenarios
|
||||
void clearAuthTokenForLogout() {
|
||||
_clearAuthToken();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,6 +79,7 @@ enum AuthStatus {
|
||||
unauthenticated,
|
||||
tokenExpired,
|
||||
error,
|
||||
credentialError, // Invalid credentials - need re-login
|
||||
}
|
||||
|
||||
/// Unified auth state manager - single source of truth for all auth operations
|
||||
@@ -87,6 +88,11 @@ class AuthStateManager extends _$AuthStateManager {
|
||||
final AuthCacheManager _cacheManager = AuthCacheManager();
|
||||
Future<bool>? _silentLoginFuture;
|
||||
|
||||
// Prevent infinite retry loops
|
||||
int _retryCount = 0;
|
||||
static const int _maxRetries = 3;
|
||||
DateTime? _lastRetryTime;
|
||||
|
||||
AuthState get _current =>
|
||||
state.asData?.value ?? const AuthState(status: AuthStatus.initial);
|
||||
|
||||
@@ -496,13 +502,23 @@ class AuthStateManager extends _$AuthStateManager {
|
||||
|
||||
String errorMessage = e.toString();
|
||||
|
||||
// Clear invalid credentials on auth errors
|
||||
if (e.toString().contains('401') ||
|
||||
e.toString().contains('403') ||
|
||||
e.toString().contains('authentication') ||
|
||||
e.toString().contains('unauthorized')) {
|
||||
// Don't clear credentials on connection errors - only clear on actual auth failures
|
||||
// Check if this is a genuine auth failure vs network issue
|
||||
final isNetworkError =
|
||||
e.toString().contains('SocketException') ||
|
||||
e.toString().contains('Connection') ||
|
||||
e.toString().contains('timeout') ||
|
||||
e.toString().contains('NetworkImage');
|
||||
|
||||
if (!isNetworkError &&
|
||||
(e.toString().contains('401') ||
|
||||
e.toString().contains('403') ||
|
||||
e.toString().contains('authentication') ||
|
||||
e.toString().contains('unauthorized'))) {
|
||||
// Only clear credentials if this is a real auth failure, not a network issue
|
||||
final storage = ref.read(optimizedStorageServiceProvider);
|
||||
try {
|
||||
DebugLogger.auth('Clearing invalid credentials after auth failure');
|
||||
await storage.deleteSavedCredentials();
|
||||
} catch (deleteError, deleteStack) {
|
||||
DebugLogger.error(
|
||||
@@ -516,72 +532,148 @@ class AuthStateManager extends _$AuthStateManager {
|
||||
'credentials; please clear Conduit credentials from '
|
||||
'system settings.';
|
||||
}
|
||||
|
||||
// Set credential error status to trigger login page
|
||||
_update(
|
||||
(current) => current.copyWith(
|
||||
status: AuthStatus.credentialError,
|
||||
error: errorMessage,
|
||||
isLoading: false,
|
||||
clearToken: true,
|
||||
),
|
||||
);
|
||||
return false;
|
||||
} else if (isNetworkError) {
|
||||
DebugLogger.auth(
|
||||
'Silent login failed due to network error - keeping credentials',
|
||||
);
|
||||
errorMessage = 'Connection issue - please check your network';
|
||||
|
||||
// Set general error status to trigger connection issue page
|
||||
_update(
|
||||
(current) => current.copyWith(
|
||||
status: AuthStatus.error,
|
||||
error: errorMessage,
|
||||
isLoading: false,
|
||||
),
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Unknown error type - treat as connection issue but keep credentials
|
||||
if (errorMessage.trim().isEmpty) {
|
||||
errorMessage = 'Connection issue - please try again shortly';
|
||||
}
|
||||
DebugLogger.auth(
|
||||
'Silent login failed with unknown error - keeping credentials',
|
||||
);
|
||||
_update(
|
||||
(current) => current.copyWith(
|
||||
status: AuthStatus.unauthenticated,
|
||||
status: AuthStatus.error,
|
||||
error: errorMessage,
|
||||
isLoading: false,
|
||||
clearToken: true,
|
||||
),
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle token invalidation (called by API service)
|
||||
/// Reset retry counter (called when user manually retries)
|
||||
void resetRetryCounter() {
|
||||
_retryCount = 0;
|
||||
_lastRetryTime = null;
|
||||
DebugLogger.auth('Retry counter reset for manual retry');
|
||||
}
|
||||
|
||||
/// Handle auth issues (called by API service)
|
||||
/// This shows connection issue page instead of logging out
|
||||
void onAuthIssue() {
|
||||
DebugLogger.auth('Auth issue detected - showing connection issue page');
|
||||
// Don't clear token or user data - just set error state
|
||||
// The router will show connection issue page
|
||||
_update(
|
||||
(current) => current.copyWith(
|
||||
status: AuthStatus.error,
|
||||
error: 'Connection issue - please check your connection',
|
||||
clearError: false,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Handle token invalidation (called by API service for explicit token expiry)
|
||||
/// This is only used when we need to clear the token for re-login attempts
|
||||
Future<void> onTokenInvalidated() async {
|
||||
// Prevent infinite retry loops
|
||||
final now = DateTime.now();
|
||||
if (_lastRetryTime != null &&
|
||||
now.difference(_lastRetryTime!).inSeconds < 5) {
|
||||
_retryCount++;
|
||||
if (_retryCount >= _maxRetries) {
|
||||
DebugLogger.auth(
|
||||
'Max retry attempts reached - stopping silent re-login',
|
||||
);
|
||||
_update(
|
||||
(current) => current.copyWith(
|
||||
status: AuthStatus.error,
|
||||
error: 'Connection issue - please retry manually',
|
||||
clearError: false,
|
||||
),
|
||||
);
|
||||
// Reset after 30 seconds to allow manual retry
|
||||
Future.delayed(const Duration(seconds: 30), () {
|
||||
_retryCount = 0;
|
||||
_lastRetryTime = null;
|
||||
});
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
// Reset counter if enough time has passed
|
||||
_retryCount = 0;
|
||||
}
|
||||
_lastRetryTime = now;
|
||||
|
||||
// Avoid spamming logs if multiple requests invalidate at once
|
||||
final reloginInProgress = _silentLoginFuture != null;
|
||||
if (!reloginInProgress) {
|
||||
DebugLogger.auth('Auth token invalidated');
|
||||
DebugLogger.auth(
|
||||
'Auth token invalidated - attempting silent re-login (attempt ${_retryCount + 1}/$_maxRetries)',
|
||||
);
|
||||
}
|
||||
|
||||
// Clear token from storage
|
||||
final storage = ref.read(optimizedStorageServiceProvider);
|
||||
try {
|
||||
await storage.deleteAuthToken();
|
||||
_updateApiServiceToken(null);
|
||||
} catch (error, stack) {
|
||||
DebugLogger.auth('Cleared invalidated token from secure storage');
|
||||
} catch (e, stack) {
|
||||
DebugLogger.error(
|
||||
'token-delete-failed',
|
||||
scope: 'auth/state',
|
||||
error: error,
|
||||
error: e,
|
||||
stackTrace: stack,
|
||||
);
|
||||
_updateApiServiceToken(null);
|
||||
_update(
|
||||
(current) => current.copyWith(
|
||||
status: AuthStatus.error,
|
||||
error:
|
||||
'Failed to clear secure token. Please clear Conduit '
|
||||
'credentials from your device keychain and sign in again.',
|
||||
clearToken: true,
|
||||
clearUser: true,
|
||||
clearError: false,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
_updateApiServiceToken(null);
|
||||
|
||||
// Update state
|
||||
_update(
|
||||
(current) => current.copyWith(
|
||||
status: AuthStatus.tokenExpired,
|
||||
error: 'Session expired - please sign in again',
|
||||
clearToken: true,
|
||||
clearUser: true,
|
||||
clearError: true,
|
||||
isLoading: false,
|
||||
),
|
||||
);
|
||||
|
||||
// Attempt silent re-login if credentials are available
|
||||
final hasCredentials = await storage.getSavedCredentials() != null;
|
||||
if (hasCredentials) {
|
||||
if (!reloginInProgress) {
|
||||
DebugLogger.auth('Attempting silent re-login after token invalidation');
|
||||
if (hasCredentials && !reloginInProgress) {
|
||||
DebugLogger.auth('Attempting silent re-login after token invalidation');
|
||||
final success = await silentLogin();
|
||||
if (success) {
|
||||
// Reset retry counter on success
|
||||
_retryCount = 0;
|
||||
_lastRetryTime = null;
|
||||
}
|
||||
await silentLogin();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -275,8 +275,14 @@ final apiServiceProvider = Provider<ApiService?>((ref) {
|
||||
|
||||
// Keep callbacks in sync so interceptor can notify auth manager
|
||||
apiService.setAuthCallbacks(
|
||||
onAuthTokenInvalid: () {},
|
||||
onAuthTokenInvalid: () {
|
||||
// Called when auth errors occur (401/403)
|
||||
// Show connection issue page instead of logging out
|
||||
final authManager = ref.read(authStateManagerProvider.notifier);
|
||||
authManager.onAuthIssue();
|
||||
},
|
||||
onTokenInvalidated: () async {
|
||||
// Called for token expiry - attempt silent re-login
|
||||
final authManager = ref.read(authStateManagerProvider.notifier);
|
||||
await authManager.onTokenInvalidated();
|
||||
},
|
||||
@@ -291,8 +297,9 @@ final apiServiceProvider = Provider<ApiService?>((ref) {
|
||||
|
||||
// Keep legacy callback for backward compatibility during transition
|
||||
apiService.onAuthTokenInvalid = () {
|
||||
// This will be removed once migration is complete
|
||||
DebugLogger.auth('legacy-token-callback', scope: 'auth/api');
|
||||
// Show connection issue page instead of logging out
|
||||
final authManager = ref.read(authStateManagerProvider.notifier);
|
||||
authManager.onAuthIssue();
|
||||
};
|
||||
|
||||
return apiService;
|
||||
|
||||
@@ -3,6 +3,7 @@ import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
import '../auth/auth_state_manager.dart';
|
||||
import '../providers/app_providers.dart';
|
||||
import '../services/connectivity_service.dart';
|
||||
import '../services/navigation_service.dart';
|
||||
@@ -129,8 +130,20 @@ class RouterNotifier extends ChangeNotifier {
|
||||
if (location == Routes.connectionIssue) return null;
|
||||
return null;
|
||||
case AuthNavigationState.error:
|
||||
if (location == Routes.connectionIssue) return null;
|
||||
return null;
|
||||
final authSnapshot = ref
|
||||
.read(authStateManagerProvider)
|
||||
.maybeWhen(data: (state) => state, orElse: () => null);
|
||||
final hasValidToken = authSnapshot?.hasValidToken ?? false;
|
||||
final isAuthFormRoute =
|
||||
location == Routes.login || location == Routes.authentication;
|
||||
if (!hasValidToken && isAuthFormRoute) {
|
||||
// Keep user on the login/authentication flow to show inline errors
|
||||
return null;
|
||||
}
|
||||
// Otherwise show connection issue page for recoverable auth errors
|
||||
return location == Routes.connectionIssue
|
||||
? null
|
||||
: Routes.connectionIssue;
|
||||
case AuthNavigationState.authenticated:
|
||||
// Avoid unnecessary redirects if already on a non-auth route
|
||||
if (_isAuthLocation(location) ||
|
||||
|
||||
@@ -1170,9 +1170,7 @@ class ApiService {
|
||||
data,
|
||||
debugLabel: 'parse_file_search',
|
||||
);
|
||||
return normalized
|
||||
.map(FileInfo.fromJson)
|
||||
.toList(growable: false);
|
||||
return normalized.map(FileInfo.fromJson).toList(growable: false);
|
||||
}
|
||||
return const [];
|
||||
}
|
||||
@@ -1186,9 +1184,7 @@ class ApiService {
|
||||
data,
|
||||
debugLabel: 'parse_file_all',
|
||||
);
|
||||
return normalized
|
||||
.map(FileInfo.fromJson)
|
||||
.toList(growable: false);
|
||||
return normalized.map(FileInfo.fromJson).toList(growable: false);
|
||||
}
|
||||
return const [];
|
||||
}
|
||||
@@ -1599,10 +1595,7 @@ class ApiService {
|
||||
if (data is Map<String, dynamic>) {
|
||||
final voices = data['voices'];
|
||||
if (voices is List) {
|
||||
return _normalizeList(
|
||||
voices,
|
||||
debugLabel: 'parse_voice_list',
|
||||
);
|
||||
return _normalizeList(voices, debugLabel: 'parse_voice_list');
|
||||
}
|
||||
}
|
||||
if (data is List) {
|
||||
@@ -1795,10 +1788,7 @@ class ApiService {
|
||||
final response = await _dio.get('/api/v1/images/models');
|
||||
final data = response.data;
|
||||
if (data is List) {
|
||||
return _normalizeList(
|
||||
data,
|
||||
debugLabel: 'parse_image_models',
|
||||
);
|
||||
return _normalizeList(data, debugLabel: 'parse_image_models');
|
||||
}
|
||||
return [];
|
||||
}
|
||||
@@ -3213,10 +3203,7 @@ class ApiService {
|
||||
|
||||
final data = response.data;
|
||||
if (data is List) {
|
||||
return _normalizeList(
|
||||
data,
|
||||
debugLabel: 'parse_message_search',
|
||||
);
|
||||
return _normalizeList(data, debugLabel: 'parse_message_search');
|
||||
}
|
||||
if (data is Map<String, dynamic>) {
|
||||
final list = (data['items'] ?? data['results'] ?? data['messages']);
|
||||
|
||||
@@ -161,7 +161,10 @@ class SettingsService {
|
||||
box.get(PreferenceKeys.voiceSttPreference) as String?,
|
||||
),
|
||||
voiceSilenceDuration:
|
||||
(box.get(_voiceSilenceDurationKey) as int? ?? 2000).clamp(300, 3000),
|
||||
(box.get(_voiceSilenceDurationKey) as int? ?? 2000).clamp(
|
||||
300,
|
||||
3000,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user