send method

Future<Token> send()

Sends the request to the server.

Implementation

Future<Token> send() async {
  Ensure(_resources).isNotEmpty('resources');

  var userSpaceEntities = [ResourceType.user, ResourceType.space];
  var hasUserSpaceResourceType =
      _resources.any((resource) => userSpaceEntities.contains(resource.type));
  var hasLegacyResourceType = _resources
      .any((resource) => !userSpaceEntities.contains(resource.type));

  if (hasUserSpaceResourceType && hasLegacyResourceType) {
    Ensure.fail(
        'not-together', 'user/space', ['channel', 'uuid', 'channelGroup']);
  }
  if (authorizedUUID != null && hasUserSpaceResourceType) {
    Ensure.fail('not-together', 'authorizedUUID', ['user', 'space']);
  }
  if (authorizedUserId != null && hasLegacyResourceType) {
    Ensure.fail('not-together', 'authorizedUserId',
        ['channel', 'uuid', 'channelGroup']);
  }

  Map<String, dynamic> combine<T extends Pattern>(
      Map<String, dynamic> accumulator, Resource resource) {
    var type = resource.type.value;
    var name = resource.name ?? resource.pattern;

    return {
      ...accumulator,
      type: {...(accumulator[type] ?? {}), name: resource.bit}
    };
  }

  var resources = _resources
      .where((resource) => resource.name is String)
      .fold({'channels': {}, 'groups': {}, 'uuids': {}}, combine);

  var patterns = _resources
      .where((resource) => resource.pattern is String)
      .fold({'channels': {}, 'groups': {}, 'uuids': {}}, combine);

  var data = {
    'ttl': ttl,
    'permissions': {
      'resources': resources,
      'patterns': patterns,
      if (authorizedUUID != null || authorizedUserId != null)
        'uuid': authorizedUUID ?? authorizedUserId,
      if (meta != null) 'meta': meta
    }
  };

  var payload = json.encode(data);

  return defaultFlow<PamGrantTokenParams, Token>(
      keyset: _keyset,
      core: _core,
      params: PamGrantTokenParams(
        _keyset,
        payload,
      ),
      serialize: (object, [_]) {
        var result = PamGrantTokenResult.fromJson(object);

        return Token(result.token);
      });
}