60 lines
2.1 KiB
C#
60 lines
2.1 KiB
C#
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 MCVIngenieros.Transactional.Abstractions.Interfaces;
|
|
using System.Text.Json;
|
|
|
|
namespace back.services.engine.SystemUser;
|
|
|
|
public class SystemUserGenerator(
|
|
ITransactionalService<DataContext> transactional,
|
|
JsonSerializerOptions jsonSerializerOptions,
|
|
IUserRepository userRepository,
|
|
IPersonRepository personRepository,
|
|
IRoleRepository roleRepository,
|
|
IPermissionRepository permissionRepository,
|
|
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 permissionRepository.SeedDefaultPermissions();
|
|
await roleRepository.SeedDefaultRoles();
|
|
await personRepository.Insert(Person.SystemPerson);
|
|
await userRepository.Insert(User.SystemUser);
|
|
});
|
|
}
|
|
else
|
|
{
|
|
await userRepository.Update(User.SystemUser);
|
|
await userRepository.SaveChanges();
|
|
}
|
|
}
|
|
} |