restoreSession method

Future<RestoreResult> restoreSession()

Restore a previously saved session on app launch.

The flow is offline-aware and optimistic:

  1. Read the persisted session from secure storage.
  2. If none exists → return RestoreResult.noSession.
  3. Populate the in-memory state immediately (accessToken, currentUser, expiry) and fire authStateChanges so apps render their authenticated UI without waiting for the network.
  4. If the access token is still valid → return RestoreResult.restored.
  5. Otherwise refresh against the server:

Implementation

Future<RestoreResult> restoreSession() async {
  final persisted = await _storage.readSession();
  if (persisted == null) return RestoreResult.noSession;

  // Optimistic restoration — populate state from disk before any network.
  _accessToken = persisted.accessToken;
  _accessTokenExpiresAt = persisted.expiresAt;
  _currentUser = persisted.user;
  _authStateController.add(persisted.user);

  // If the access token is still valid, we're done — no network needed.
  if (!persisted.isAccessTokenExpired) {
    return RestoreResult.restored;
  }

  // Access token expired — attempt to refresh.
  try {
    final session = await _api.refresh(persisted.refreshToken);
    await _setSession(session);
    return RestoreResult.restored;
  } on KoolbaseAuthException {
    // Server rejected the refresh token — clear and require fresh login.
    await _clearSession();
    return RestoreResult.expired;
  } catch (_) {
    // Network error (timeout, DNS, connection refused). Keep the optimistic
    // state — the app UI stays authenticated, API calls will fail until
    // network returns. App can call [refreshSession] when connectivity is
    // restored.
    return RestoreResult.offline;
  }
}