switchAccount method

Future<bool> switchAccount(
  1. UserId userId
)

Switches to the account with the provided UserId using the persisted Credentials.

Returns true if the account was successfully switched, otherwise returns false.

Implementation

Future<bool> switchAccount(UserId userId) async {
  Log.debug('switchAccount($userId)', '$runtimeType');

  Credentials? creds = accounts[userId]?.value;
  if (creds == null) {
    return false;
  }

  final bool hadAuthorization = _hasAuthorization;

  status.value = RxStatus.loading();

  try {
    if (_shouldRefresh(creds)) {
      await refreshSession(userId: creds.userId);
    }

    creds = accounts[userId]?.value;
    if (creds == null) {
      status.value = hadAuthorization ? RxStatus.success() : RxStatus.empty();
      return false;
    }

    // TODO: Remove, when remote subscription to each [MyUser] events is up.
    //
    // This workarounds the situation when the password of another account was
    // changed or the account was deleted.
    final bool areValid = await validateToken(creds);
    if (areValid) {
      await WebUtils.protect(() async {
        await _authorized(creds!);
        status.value = RxStatus.success();
      });

      return true;
    } else {
      status.value = hadAuthorization ? RxStatus.success() : RxStatus.empty();
      _credentialsProvider.delete(userId);
      accounts.remove(userId);
    }
  } catch (_) {
    status.value = hadAuthorization ? RxStatus.success() : RxStatus.empty();
    rethrow;
  }

  return false;
}