setSession method

  1. @override
  2. @visibleForTesting
Future<void> setSession(
  1. Session session
)

Updates the NhostAuthClient to begin identifying as the user described by session.

Implementation

@override
@visibleForTesting
Future<void> setSession(Session session) async {
  // It is CRITICAL that this function be awaited before returning to the
  // user. Failure to do so will result in very difficult to track down race
  // conditions.

  log.finest(
    'Setting session, accessToken.hashCode='
    '${identityHashCode(session.accessToken)}',
  );

  final previouslyAuthenticated = authenticationState;
  _session.session = session;
  _currentUser = session.user;

  if (session.refreshToken != null) {
    await _authStore.setString(
      refreshTokenClientStorageKey,
      session.refreshToken!,
    );
  }

  final accessTokenExpiresIn = session.accessTokenExpiresIn;
  final refreshTimerDuration = _tokenRefreshInterval ??
      (accessTokenExpiresIn != null
          ? accessTokenExpiresIn - Duration(seconds: 45)
          : Duration(seconds: 855)); // 45 sec before expiry

  // Ensure that the previous timer is cancelled.
  _tokenRefreshTimer?.cancel();

  // Start refresh token interval after logging in.
  log.finest('Creating token refresh timer, duration=$refreshTimerDuration');
  _tokenRefreshTimer = Timer(
    refreshTimerDuration,
    () {
      log.finest('Refresh timer elapsed');
      _refreshSession();
    },
  );

  // We're ready!
  _loading = false;

  _onTokenChanged();
  if (previouslyAuthenticated != AuthenticationState.signedIn) {
    _onAuthStateChanged(AuthenticationState.signedIn);
  }
}