restore method

  1. @override
Future<void> restore()
override

Restore session from storage.

Called on app boot to restore user from stored token.

Implementation

@override
Future<void> restore() async {
  Log.debug(
    'Auth: Restoring session (tokenKey=$tokenKey, hasFactory=${userFactory != null})',
  );
  await loadTokenToCache();

  if (cachedToken == null) {
    Log.debug('Auth: No token found in storage');
    return;
  }

  Log.debug('Auth: Token loaded from storage');

  // 1. Load from cache first (instant)
  final cachedUser = await loadCachedUser();
  if (cachedUser != null) {
    setUser(cachedUser);
    Log.debug('Auth: Cached user restored');
  } else {
    Log.debug('Auth: No cached user found');
  }

  // 2. Sync from API (fresh data).
  //
  // Awaited only when the cache had nothing to show. `AuthServiceProvider`
  // awaits `restore()`, which holds `Magic.init()`, which holds `runApp`, so
  // anything awaited here is time the user spends looking at a blank window.
  // Against a backend that accepts the connection and then says nothing (a
  // captive portal, a dead mobile link) that is the whole client timeout: on
  // an app configured for 120s it measured as roughly two minutes of white
  // screen on a cold start, with the console stopping dead on the line above.
  //
  // With a cached user already set the screen can render now and correct
  // itself when the sync lands, which is what this class has documented as
  // its cache strategy from the start ("2. Sync from API in background").
  // Without one there is nothing to render and no honest way to route, so the
  // API is the only answer and waiting for it is the point.
  if (cachedUser != null) {
    unawaited(_syncUserFromApi());

    return;
  }

  await _syncUserFromApi();
}