rehydrateSessionIfNeeded method

Future<void> rehydrateSessionIfNeeded()

Rehydrates AuthUser.session from sessionManager.activeSession when the user is authenticated but session was lost (warm restore).

Implementation

Future<void> rehydrateSessionIfNeeded() async {
  if (!sessionTokensEnabled) return;

  final currentUser = authService.user;
  if (currentUser == null) return;
  if (currentUser.session != null) return;

  await _ensureSessionManagerReady();

  final activeSession = sessionManager.activeSession;
  if (activeSession == null) return;

  final status = sessionManager.getSessionStatus(activeSession);

  if (status == AuthSessionStatus.valid ||
      status == AuthSessionStatus.expiringSoon) {
    _assignSession(currentUser, activeSession);
    _captureBaseSession(activeSession);
    logger.info(
      this,
      'Rehydrated session for ${currentUser.userId} from persisted storage',
    );
  }

  if (status == AuthSessionStatus.expiringSoon ||
      status == AuthSessionStatus.expired) {
    try {
      final refreshed = await sessionManager.refreshSession(
        currentUser.userId,
      );
      _assignSession(currentUser, refreshed);
      _captureBaseSession(refreshed);
      logger.info(
        this,
        'Refreshed expiring session for ${currentUser.userId}',
      );
    } catch (e, st) {
      logger.error(
        this,
        'Failed to refresh session for ${currentUser.userId}',
        error: e,
        stackTrace: st,
      );
    }
  }
}