loginWithApple method

  1. @override
dynamic loginWithApple()
override

Implementation

@override
loginWithApple() async {
  update(state: LoginViewState.Loading);
  bool isAvailable = await SignInWithApple.isAvailable();
  if (!isAvailable) {
    this.authError = AuthError(
        title: AppStrings.loginError,
        code: AppStrings.codeAppleLoginError,
        message: AppStrings.invalidVersionAppleLogin);
    update(state: LoginViewState.Error);
    return;
  }

  try {
    final credential = await SignInWithApple.getAppleIDCredential(
      scopes: [
        AppleIDAuthorizationScopes.email,
        AppleIDAuthorizationScopes.fullName,
      ],
    );

    AppleCredential appleCredential = AppleCredential(
        userIdentifier: credential.userIdentifier,
        identityToken: credential.identityToken,
        authorizationCode: credential.authorizationCode,
        email: credential.email);

    var appCredential = await repository.loginWithApple(appleCredential);

    if (appCredential is ICredential) {
      if (appCredential.isError) {
        this.authError = appCredential.error;
        update(state: LoginViewState.Error);
        return;
      }

      await Future.wait([
        AuthRepository.instance().writeUserId(appCredential.userId),
        AuthRepository.instance().writeUserCode(appCredential.userCode),
        AuthRepository.instance().writeAccessToken(appCredential.accessToken),
        AuthRepository.instance()
            .writeRefreshToken(appCredential.refreshToken ?? "")
      ]);

      update(state: LoginViewState.Success);
      return;
    } else {
      throw AuthError(
          title: AppStrings.loginError, code: AppStrings.codeAppleLoginError);
    }
  } catch (e) {
    String title = AppStrings.loginError;
    String code = AppStrings.codeAppleLoginError;
    String message = AppStrings.messageAuthError;

    if (e is SignInWithAppleAuthorizationException) {
      title = e.code.toString();
      code = e.message;
      message = e.message;
      if (e.code == AuthorizationErrorCode.canceled ||
          e.code == AuthorizationErrorCode.unknown) {
        update(state: LoginViewState.Idle);
        return;
      }
    }

    this.authError =
        AuthError(title: title, code: code, message: message, error: e);
    update(state: LoginViewState.Error);
  }
}