getToken method

Future<AccessTokenResponse?> getToken(
  1. List<String> scopes
)

Looks for a token in the storage that matches the required scopes. If a token in the storage has been generated for a superset of the requested scopes, it is considered valid.

Implementation

Future<AccessTokenResponse?> getToken(List<String> scopes) async {
  AccessTokenResponse? tknResp;

  final serializedStoredTokens = await storage.read(key);

  if (serializedStoredTokens != null) {
    final Map<String, dynamic> storedTokens =
        jsonDecode(serializedStoredTokens);

    final cleanScopes = clearScopes(scopes);

    var tknMap = storedTokens.values.firstWhere((tkn) {
      var found = false;

      if (cleanScopes.isEmpty) {
        //If the scopes are empty, only tokens granted to empty scopes are considered valid...
        found = (tkn['scope'] == null || tkn['scope'].isEmpty);
      } else {
        //...Otherwise look for a token granted to a superset of the requested scopes
        if (tkn.containsKey('scope') && tkn['scope'] != null) {
          final tknCleanScopes = clearScopes(tkn['scope'].cast<String>());

          if (tknCleanScopes.isNotEmpty) {
            var s1 = Set.from(tknCleanScopes);
            var s2 = Set.from(cleanScopes);
            found = s1.intersection(s2).length == cleanScopes.length;
          }
        }
      }

      return found;
    }, orElse: () => null);

    if (tknMap != null) tknResp = AccessTokenResponse.fromMap(tknMap);
  }

  return tknResp;
}