isLoggedInAsync method
Implementation
@override
Future<bool> isLoggedInAsync() async {
// Check if another check is in progress
if (_loginCheckCompleter != null && !_loginCheckCompleter!.isCompleted) {
logd('isLoggedInAsync: Already checking login state, waiting for completion...');
try {
// Wait for the existing check to complete and return its result
return await _loginCheckCompleter!.future;
} catch (e) {
logd('isLoggedInAsync: Error waiting for existing check: $e');
// If the existing check failed, fall through to perform our own check
}
}
// Create a new completer for this check
_loginCheckCompleter = Completer<bool>();
try {
// Use cached state for very frequent calls (within 30 seconds)
if (_shouldUseQuickCache()) {
logd('isLoggedInAsync: Using quick cached auth state');
_safeCompleteLoginCheck(_lastKnownAuthState!);
return _lastKnownAuthState!;
}
await waitForCanCheckLoginState();
// Quick check if no user
if (_fbAuth.currentUser == null) {
final result = await _handleUnauthenticatedState();
_updateCachedState(result);
_safeCompleteLoginCheck(result);
return result;
}
// For less frequent calls, do a lightweight check
if (_shouldUseLightweightCheck()) {
logd('isLoggedInAsync: Performing lightweight token check');
bool isValid = await _performLightweightTokenCheck();
if (isValid) {
_updateCachedState(true);
_safeCompleteLoginCheck(true);
return true;
}
}
// Full validation with network check
bool isTokenValid = await _performFullTokenValidation();
if (isTokenValid) {
_updateCachedState(true);
_safeCompleteLoginCheck(true);
return true;
} else {
// Token is invalid, try alternative auth methods
final result = await _handleInvalidToken();
_updateCachedState(result);
_safeCompleteLoginCheck(result);
return result;
}
} catch (e) {
logd('isLoggedInAsync: Unexpected error: $e');
// On error, trust Firebase's auth state
bool fbAuthState = _fbAuth.currentUser != null;
if (fbAuthState && _lastKnownAuthState == true) {
// If Firebase says we're logged in and we were logged in before, trust it
_safeCompleteLoginCheck(true);
return true;
}
_safeCompleteLoginCheckWithError(e);
return fbAuthState;
} finally {
// Clean up the completer after a short delay
Future.delayed(const Duration(milliseconds: 100), () {
_loginCheckCompleter = null;
});
}
}