signIn method

Future<void> signIn()

Signs in and redirects to the Routes.home page.

Username is login's text and the password is password's text.

Implementation

Future<void> signIn() async {
  final String input = login.text.toLowerCase();

  final UserLogin? userLogin = UserLogin.tryParse(input);
  final UserNum? userNum = UserNum.tryParse(input);
  final UserEmail? userEmail = UserEmail.tryParse(input);
  final UserPhone? userPhone = UserPhone.tryParse(input);
  final UserPassword? userPassword = UserPassword.tryParse(password.text);

  login.error.value = null;
  password.error.value = null;

  final bool noCredentials =
      userLogin == null &&
      userNum == null &&
      userEmail == null &&
      userPhone == null;

  if (noCredentials || userPassword == null) {
    password.error.value = 'err_incorrect_login_or_password'.l10n;
    password.unsubmit();
    return;
  }

  try {
    login.status.value = RxStatus.loading();
    password.status.value = RxStatus.loading();

    final bool authorized = _authService.isAuthorized();

    await _authService.signIn(
      password: userPassword,
      login: userLogin,
      num: userNum,
      email: userEmail,
      phone: userPhone,
      force: authorized,
    );

    if (onSuccess != null) {
      onSuccess?.call();
    } else {
      // TODO: This is a hack that should be removed, as whenever the account
      //       is changed, the [HomeView] and its dependencies must be
      //       rebuilt, which may take some unidentifiable amount of time as
      //       of now.
      if (authorized) {
        router.nowhere();
        await Future.delayed(const Duration(milliseconds: 500));
      }

      router.home();
    }
  } on CreateSessionException catch (e) {
    ++signInAttempts;

    if (signInAttempts >= 3) {
      // Wrong password was entered three times. Login is possible in N
      // seconds.
      signInAttempts = 0;
      _setSignInTimer();
    }

    password.error.value = e.toMessage();
  } on ConnectionException {
    password.unsubmit();
    password.resubmitOnError.value = true;
    password.error.value = 'err_data_transfer'.l10n;
  } catch (e) {
    password.unsubmit();
    password.resubmitOnError.value = true;
    password.error.value = 'err_data_transfer'.l10n;
    rethrow;
  } finally {
    login.status.value = RxStatus.empty();
    password.status.value = RxStatus.empty();
  }
}