using back.DataModels; using back.persistance.blob; using back.persistance.data; using back.persistance.data.repositories.Abstracts; using back.services.engine.Crypto; using back.services.engine.PasswordGenerator; using System.Text.Json; using Transactional.Abstractions.Interfaces; namespace back.services.engine.SystemUser; public class SystemUserGenerator( ITransactionalService transactional, JsonSerializerOptions jsonSerializerOptions, IUserRepository userRepository, IPersonRepository personRepository, ICryptoService cryptoService, IBlobStorageService blobStorageService, IPasswordGenerator passwordGenerator) : ISystemUserGenerator { public async Task GenerateAsync() { var systemKey = new SystemKey() { Password = passwordGenerator.Generate(16), }; var systemKeyJson = JsonSerializer.Serialize(systemKey, options: jsonSerializerOptions); using Stream stream = new MemoryStream(new System.Text.UTF8Encoding(true).GetBytes(systemKeyJson)); await blobStorageService.Delete("systemkey.lock"); await blobStorageService.Save( stream, "systemkey.lock" ); User.SystemUser.Password = systemKey.Password; User.SystemUser.Salt = cryptoService.Salt(); User.SystemUser.Password = cryptoService.HashPassword(User.SystemUser.Password, User.SystemUser.Salt) ?? string.Empty; if (!await userRepository.Exists(User.SystemUser.Id!)) { await transactional.DoTransaction(async () => { await personRepository.Insert(Person.SystemPerson); await userRepository.Insert(User.SystemUser); }); } else { await userRepository.Update(User.SystemUser); await userRepository.SaveChanges(); } } }