diff --git a/src/Core/KeyManagement/Commands/Interfaces/ISetAccountKeysForUserCommand.cs b/src/Core/KeyManagement/Commands/Interfaces/ISetAccountKeysForUserCommand.cs new file mode 100644 index 0000000000..ffce03f916 --- /dev/null +++ b/src/Core/KeyManagement/Commands/Interfaces/ISetAccountKeysForUserCommand.cs @@ -0,0 +1,14 @@ +#nullable enable +using Bit.Core.KeyManagement.Models.Api.Request; +using Bit.Core.KeyManagement.Repositories; +using Bit.Core.Repositories; + +namespace Bit.Core.KeyManagement.Commands.Interfaces; + +public interface ISetAccountKeysForUserCommand +{ + Task SetAccountKeysForUserAsync(Guid userId, + AccountKeysRequestModel accountKeys, + IUserRepository userRepository, + IUserSignatureKeyPairRepository userSignatureKeyPairRepository); +} diff --git a/src/Core/KeyManagement/Commands/SetAccountKeysForUserCommand.cs b/src/Core/KeyManagement/Commands/SetAccountKeysForUserCommand.cs new file mode 100644 index 0000000000..78d60fe1c1 --- /dev/null +++ b/src/Core/KeyManagement/Commands/SetAccountKeysForUserCommand.cs @@ -0,0 +1,42 @@ +using Bit.Core.KeyManagement.Commands.Interfaces; +using Bit.Core.KeyManagement.Entities; +using Bit.Core.KeyManagement.Models.Api.Request; +using Bit.Core.KeyManagement.Repositories; +using Bit.Core.Repositories; +using Bit.Core.Utilities; + +namespace Bit.Core.KeyManagement.Commands; + +public class SetAccountKeysForUserCommand : ISetAccountKeysForUserCommand +{ + public async Task SetAccountKeysForUserAsync(Guid userId, AccountKeysRequestModel accountKeys, IUserRepository userRepository, IUserSignatureKeyPairRepository userSignatureKeyPairRepository) + { + var user = await userRepository.GetByIdAsync(userId); + if (user == null) + { + throw new ArgumentException("User not found", nameof(userId)); + } + + var accountKeysData = accountKeys.ToAccountKeysData(); + + // Update the public key encryption key pair data + user.PrivateKey = accountKeysData.PublicKeyEncryptionKeyPairData.WrappedPrivateKey; + user.PublicKey = accountKeysData.PublicKeyEncryptionKeyPairData.PublicKey; + user.RevisionDate = user.AccountRevisionDate = DateTime.UtcNow; + await userRepository.ReplaceAsync(user); + // Update the signature key pair data + if (accountKeysData.SignatureKeyPairData != null) + { + await userSignatureKeyPairRepository.UpsertAsync(new UserSignatureKeyPair + { + Id = CoreHelpers.GenerateComb(), + UserId = userId, + SignatureAlgorithm = accountKeysData.SignatureKeyPairData.SignatureAlgorithm, + SigningKey = accountKeysData.SignatureKeyPairData.WrappedSigningKey, + VerifyingKey = accountKeysData.SignatureKeyPairData.VerifyingKey, + CreationDate = DateTime.UtcNow, + RevisionDate = DateTime.UtcNow, + }); + } + } +}