authorize method

void authorize({
  1. dynamic onAuth(
    1. AuthData authData
    ) = _defaultOnAuth,
  2. dynamic onAuthCode(
    1. AuthCodeData authCodeData,
    2. bool isCompletion
    ) = _defaultOnAuthCode,
  3. dynamic onError(
    1. AuthError error
    ) = _defaultOnError,
  4. AuthParams params = const AuthParams(),
})

Initiates the authorization process with optional params.

Authorization process launches ui which can be either WebView with auth flow or auth provider (another app from VK ecosystem).

In case AuthParams.authFlowData as set to PublicFlowData in the end of successful auth process calls onAuth. In case it was set to ConfidentialFlowData calls onAuthCode. The second parameter of onAuthCode, isCompletion is always true for now. In case of any error during auth, always calls onError.

Usage example:

final vkid = await VKID.getInstance();
vkid.authorize(
    onAuth: (data) => print(data.token),
    onError: (error) => print(error),
    params: AuthParamsBuilder().withLocale(AuthLocale.en).build()
);

Implementation

void authorize({
  Function(AuthData authData) onAuth = _defaultOnAuth,
  Function(AuthCodeData authCodeData, bool isCompletion) onAuthCode =
      _defaultOnAuthCode,
  Function(AuthError error) onError = _defaultOnError,
  AuthParams params = const AuthParams(),
}) async {
  try {
    String? state;
    String? codeChallenge;
    switch (params._authFlowData) {
      case PublicFlowData(state: var actualState):
        state = actualState;
        codeChallenge = null;
        break;
      case ConfidentialFlowData(
          state: var actualState,
          codeChallenge: var actualCodeChallange
        ):
        state = actualState;
        codeChallenge = actualCodeChallange;
        break;
    }
    final List<Object?> result = await _platform.invokeMethod("authorize", [
      // ignore: sdk_version_since
      params._locale?.name,
      // ignore: sdk_version_since
      params._theme?.name,
      params._useOAuthProviderIfPossible,
      // ignore: sdk_version_since
      params._oAuth?.name,
      state,
      codeChallenge,
      params._scopes.toList(),
    ]);
    if (result[0] == "onAuth") {
      onAuth(_parseAuthData(result));
    } else if (result[0] == "onAuthCode") {
      onAuthCode(_parseAuthCodeData(result), true);
    }
  } on PlatformException catch (e) {
    onError(e.code == "cancelled"
        ? const AuthCancelledError._()
        : AuthOtherError._(e.message ?? ""));
  } catch (e) {
    onError(const AuthOtherError._("unknown error"));
  }
}