75 lines
2.7 KiB
C#
75 lines
2.7 KiB
C#
|
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;
|
||
|
|
||
|
/// <inheritdoc />
|
||
|
[RegisterScoped]
|
||
|
public class InitialUserService : IInitialUserService
|
||
|
{
|
||
|
private readonly InitialUserConfiguration _configuration;
|
||
|
private readonly IUserService _userService;
|
||
|
private readonly IUserRepository _userRepository;
|
||
|
private readonly ILogger<InitialUserService> _logger;
|
||
|
|
||
|
/// <summary>
|
||
|
/// Initializes a new instance of the <see cref="InitialUserService"/> class.
|
||
|
/// </summary>
|
||
|
/// <param name="initialUserConfiguration">Instance of <see cref="IOptions{InitialUserConfiguration}"/>.</param>
|
||
|
/// <param name="userService">Instance of <see cref="IUserService"/>.</param>
|
||
|
/// <param name="userRepository">Instance of <see cref="IUserRepository"/>.</param>
|
||
|
/// <param name="logger">Instance of <see cref="ILogger"/>.</param>
|
||
|
public InitialUserService(
|
||
|
IOptions<InitialUserConfiguration> initialUserConfiguration,
|
||
|
IUserService userService,
|
||
|
IUserRepository userRepository,
|
||
|
ILogger<InitialUserService> logger)
|
||
|
{
|
||
|
_configuration = initialUserConfiguration.Value;
|
||
|
_userService = userService;
|
||
|
_userRepository = userRepository;
|
||
|
_logger = logger;
|
||
|
}
|
||
|
|
||
|
/// <inheritdoc />
|
||
|
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);
|
||
|
}
|
||
|
}
|