initDelegations method

Future<DecryptedPatientDto> initDelegations(
  1. UserDto user,
  2. CryptoConfig<DecryptedPatientDto, PatientDto> config, {
  3. Set<String>? delegates = null,
})

Implementation

Future<DecryptedPatientDto> initDelegations(UserDto user, CryptoConfig<DecryptedPatientDto, PatientDto> config, { Set<String>? delegates = null }) async {
  final Uuid uuid = Uuid();

  Set<String> allDelegates = Set.from(delegates ?? <String>{})
    ..addAll(user.autoDelegations["all"] ?? <String>{})
    ..addAll(user.autoDelegations["medicalInformation"] ?? <String>{});

  if (!this.encryptionKeys.isEmpty || !this.delegations.isEmpty) {
    throw FormatException("Patient is already initialised");
  }

  this.responsible = this.responsible ?? user.dataOwnerId()!;
  this.author = user.id;

  DataOwnerDto? dataOwner = null;

  final sfk = uuid.v4(options: {'rng': UuidUtil.cryptoRNG});
  this.delegations = await (allDelegates..add(user.dataOwnerId()!)).fold(
      Future.value({...delegations}),
          (m, d) async {
        final acc = await m;

        final keyAndOwner = await config.crypto.encryptAESKeyForHcp(user.dataOwnerId()!, d, id, sfk);
        dataOwner = keyAndOwner.item2 ?? dataOwner;

        return acc..addEntries([
          MapEntry(d, {
            DelegationDto(
                owner: user.dataOwnerId(),
                delegatedTo: d,
                key: keyAndOwner.item1
            )
          })
        ]);
      });

  final ek = uuid.v4(options: {'rng': UuidUtil.cryptoRNG});
  this.encryptionKeys = await (allDelegates..add(user.dataOwnerId()!)).fold(
      Future.value({...this.encryptionKeys}),
          (m, d) async {
        final acc = await m;

        final keyAndOwner = await config.crypto.encryptAESKeyForHcp(user.dataOwnerId()!, d, id, ek);
        dataOwner = keyAndOwner.item2 ?? dataOwner;

        return acc..addEntries([
          MapEntry(d, {
            DelegationDto(
                owner: user.dataOwnerId(),
                delegatedTo: d,
                key: keyAndOwner.item1
            )
          })
        ]);
      });

  if (dataOwner != null && this.id == dataOwner!.dataOwnerId) {
    this.hcPartyKeys = dataOwner!.hcPartyKeys;
    this.aesExchangeKeys = dataOwner!.aesExchangeKeys;
    this.rev = dataOwner!.rev;
  }

  return this;
}