Ejemplo n.º 1
0
        public async Task AddHardwareVaultAsync(string employeeId, string vaultId)
        {
            if (employeeId == null)
            {
                throw new ArgumentNullException(nameof(employeeId));
            }

            if (vaultId == null)
            {
                throw new ArgumentNullException(nameof(vaultId));
            }

            _dataProtectionService.Validate();

            var employee = await GetEmployeeByIdAsync(employeeId);

            if (employee == null)
            {
                throw new Exception("Employee not found");
            }

            if (employee.HardwareVaults.Count > 0)
            {
                throw new Exception("Cannot add more than one hardware vault.");
            }

            var vault = await _hardwareVaultService.GetVaultByIdAsync(vaultId);

            if (vault == null)
            {
                throw new Exception($"Vault {vault} not found");
            }

            if (vault.Status != VaultStatus.Ready)
            {
                throw new Exception($"Vault {vaultId} in a status that does not allow to reserve.");
            }

            vault.EmployeeId      = employeeId;
            vault.Status          = VaultStatus.Reserved;
            vault.IsStatusApplied = false;
            vault.MasterPassword  = _dataProtectionService.Encrypt(GenerateMasterPassword());

            var accounts = await GetAccountsByEmployeeIdAsync(employeeId);

            var tasks = new List <HardwareVaultTask>();

            // Create a task for accounts that were created without a vault
            foreach (var account in accounts.Where(x => x.Password != null))
            {
                tasks.Add(_hardwareVaultTaskService.GetAccountCreateTask(vault.Id, account.Id, account.Password, account.OtpSecret));
            }

            if (tasks.Count > 0)
            {
                vault.NeedSync = true;
            }

            using (TransactionScope transactionScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                await _hardwareVaultService.UpdateVaultAsync(vault);

                await _hardwareVaultService.CreateVaultActivationAsync(vaultId);

                if (tasks.Count > 0)
                {
                    await _hardwareVaultTaskService.AddRangeTasksAsync(tasks);
                }

                transactionScope.Complete();
            }
        }