78 lines
2.8 KiB
C#
78 lines
2.8 KiB
C#
// <copyright file="InitialUserService.cs" company="alveus.dev">
|
|
// Copyright (c) alveus.dev. All rights reserved. Licensed under the MIT License.
|
|
// </copyright>
|
|
|
|
using System.Net;
|
|
using Astral.Core.Constants;
|
|
using Astral.Core.RepositoryInterfaces;
|
|
using Astral.Services.Dtos;
|
|
using Astral.Services.Interfaces;
|
|
using Astral.Services.Options;
|
|
using Injectio.Attributes;
|
|
using Microsoft.Extensions.Logging;
|
|
using Microsoft.Extensions.Options;
|
|
|
|
namespace Astral.Services.Services;
|
|
|
|
/// <inheritdoc />
|
|
[RegisterScoped]
|
|
public class InitialUserService : IInitialUserService
|
|
{
|
|
private readonly InitialUserOptions _configuration;
|
|
private readonly ILogger<InitialUserService> _logger;
|
|
private readonly IUserRepository _userRepository;
|
|
private readonly IUserService _userService;
|
|
|
|
/// <summary>
|
|
/// Initializes a new instance of the <see cref="InitialUserService" /> class.
|
|
/// </summary>
|
|
/// <param name="initialUserConfiguration">Instance of <see cref="IOptions{InitialUserOptions}" />.</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<InitialUserOptions> 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 admin.
|
|
var userEntity = await _userRepository.FindByIdAsync(newUser.Id);
|
|
userEntity.UserRole = UserRole.Admin;
|
|
|
|
await _userRepository.UpdateAsync(userEntity);
|
|
|
|
_logger.LogInformation("Initial user {username} created", newUser.Id);
|
|
}
|
|
}
|