generate method

  1. @override
Future<Token> generate()
override

generate and persist the OAuth2 refresh token from a single use auth code

Implementation

@override
Future<Token> generate() async {
  final OAuthClient oAuthClient = new OAuthClient(dio);

  final tokenFile = File('.refreshToken.json');

  final tokenFileExits = tokenFile.existsSync();

  if (tokenFileExits && refresh) tokenFile.deleteSync();

  final tokenStore = <String, dynamic>{};

  String? refreshToken;

  if (tokenFileExits) {
    tokenStore.addAll(json.decode(tokenFile.readAsStringSync()));
  }

  if (tokenStore.containsKey(oauthCredentials.clientId)) {
    refreshToken = tokenStore[oauthCredentials.clientId];
  } else {
    try {
      final token = await oAuthClient.getToken({
        'client_id': oauthCredentials.clientId,
        'client_secret': oauthCredentials.clientSecret,
        'code': oauthCredentials.code,
        'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob',
        'grant_type': 'authorization_code'
      });

      if (token.refreshToken == null)
        throw Exception('Could not retrieve the refresh token');

      refreshToken = token.refreshToken!;
    } on DioError catch (err) {
      throw AuthorizationException(err.response.toString(), err);
    }

    tokenStore[oauthCredentials.clientId] = refreshToken;

    tokenFile.writeAsStringSync(json.encode(tokenStore));
  }

  return await oAuthClient.getToken({
    'client_id': oauthCredentials.clientId,
    'client_secret': oauthCredentials.clientSecret,
    'refresh_token': refreshToken,
    'grant_type': 'refresh_token'
  });
}