using System.Net; using Galaeth.Core.Constants; using Galaeth.Core.RepositoryInterfaces; using Galaeth.Services.Configuration; using Galaeth.Services.Dtos; using Galaeth.Services.Interfaces; using Injectio.Attributes; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace Galaeth.Services.Services; /// [RegisterScoped] public class InitialUserService : IInitialUserService { private readonly InitialUserConfiguration _configuration; private readonly IUserService _userService; private readonly IUserRepository _userRepository; private readonly ILogger _logger; /// /// Initializes a new instance of the class. /// /// Instance of . /// Instance of . /// Instance of . /// Instance of . public InitialUserService( IOptions initialUserConfiguration, IUserService userService, IUserRepository userRepository, ILogger logger) { _configuration = initialUserConfiguration.Value; _userService = userService; _userRepository = userRepository; _logger = logger; } /// public async Task CreateFirstUserIfRequiredAsync() { // Check if any users exist. var userCount = await _userRepository.CountUsersAsync(); if (userCount > 0) { return; } _logger.LogInformation("Creating initial user. Username: {username}", _configuration.Username); _logger.LogWarning("*************************************************************"); _logger.LogWarning("* CHANGE INITIAL USER PASSWORD IMMEDIATELY AFTER LOGGING IN *"); _logger.LogWarning("*************************************************************"); var newUser = await _userService.CreateNewUser(new CreateUserDto() { Username = _configuration.Username, Email = _configuration.Email, Password = _configuration.Password, ActivateImmediately = true, IpAddress = IPAddress.Any, }); // Promote user to root. var userEntity = await _userRepository.FindByIdAsync(newUser.Id); userEntity.Role = UserRole.Root; await _userRepository.UpdateAsync(userEntity); _logger.LogInformation("Initial user {username} created", newUser.Id); } }