getSession method

Future<CognitoUserSession?> getSession()

This is used to get a session, either from the session object or from the local storage, or by using a refresh token

Implementation

Future<CognitoUserSession?> getSession() async {
  if (username == null) {
    throw Exception('Username is null. Cannot retrieve a new session');
  }

  if (_signInUserSession != null && _signInUserSession!.isValid()) {
    return _signInUserSession;
  }

  final idTokenKey = '$keyPrefix.idToken';
  final accessTokenKey = '$keyPrefix.accessToken';
  final refreshTokenKey = '$keyPrefix.refreshToken';
  final clockDriftKey = '$keyPrefix.clockDrift';

  final refreshTokenValue = await storage.getItem(refreshTokenKey);
  final refreshToken = CognitoRefreshToken(refreshTokenValue);
  final canRefreshToken = refreshToken.getToken() != null;

  final clockDriftValue = await storage.getItem(clockDriftKey);
  final clockDrift = int.tryParse(clockDriftValue ?? '');

  final idTokenValue = await storage.getItem(idTokenKey);
  if (idTokenValue == null) {
    if (canRefreshToken) {
      return refreshSession(refreshToken);
    }
    throw Exception(
        'Local storage is missing an ID Token, Please authenticate');
  }
  final idToken = CognitoIdToken(idTokenValue);

  final accessTokenValue = await storage.getItem(accessTokenKey);
  if (accessTokenValue == null) {
    if (canRefreshToken) {
      return refreshSession(refreshToken);
    }
    throw Exception(
        'Local storage is missing an Access Token, Please authenticate');
  }
  final accessToken = CognitoAccessToken(accessTokenValue);

  final cachedSession = CognitoUserSession(
    idToken,
    accessToken,
    refreshToken: refreshToken,
    clockDrift: clockDrift,
  );

  if (cachedSession.isValid()) {
    _signInUserSession = cachedSession;
    return _signInUserSession;
  }

  if (canRefreshToken) {
    return refreshSession(refreshToken);
  }

  throw Exception('Cannot retrieve a new session. Please authenticate.');
}