validateSession method

Future<void> validateSession(
  1. AuthUserSession? session, {
  2. bool refreshOnExpiring = true,
})

Validates that the session is valid.

Implementation

Future<void> validateSession(
  AuthUserSession? session, {
  bool refreshOnExpiring = true,
}) async {
  try {
    logger.info(
      this,
      'Validating session for user ${session?.userId ?? 'unknown'}.',
    );
    var userId = session?.userId ?? 'unknown';
    if (session == null) {
      logger.error(
        this,
        'Server did not provide a session for user $userId.',
      );
      throw AuthException(AuthenticationErrorCodes.sessionNotFound);
    }

    var sessionTokenUnavailable = session.sessionToken.isEmpty;
    if (sessionTokenUnavailable) {
      logger.error(
        this,
        'Server did not provide a valid session token for user $userId.',
      );
      throw AuthException(AuthenticationErrorCodes.sessionInvalid);
    }

    if (isSessionExpired(session)) {
      logger.error(
        this,
        'Received session token for user $userId is already expired.',
      );
      throw AuthException(AuthenticationErrorCodes.sessionExpired);
    }
  } catch (e) {
    logger.error(this, 'Error validating session, removing it.', error: e);
    if (session != null) {
      await deleteSession(session.userId);
    }
    rethrow;
  }
}