61 lines
1.9 KiB
C#
61 lines
1.9 KiB
C#
using Microsoft.AspNetCore.Identity;
|
|
using Microsoft.Extensions.Options;
|
|
using WorkTracker.Configuration;
|
|
using WorkTracker.Data;
|
|
|
|
namespace WorkTracker.Services.Auth;
|
|
|
|
public sealed class SingleUserSeedService : IHostedService
|
|
{
|
|
private readonly IServiceProvider serviceProvider;
|
|
private readonly IOptions<SingleUserOptions> options;
|
|
private readonly ILogger<SingleUserSeedService> logger;
|
|
|
|
public SingleUserSeedService(
|
|
IServiceProvider serviceProvider,
|
|
IOptions<SingleUserOptions> options,
|
|
ILogger<SingleUserSeedService> logger)
|
|
{
|
|
this.serviceProvider = serviceProvider;
|
|
this.options = options;
|
|
this.logger = logger;
|
|
}
|
|
|
|
public async Task StartAsync(CancellationToken cancellationToken)
|
|
{
|
|
if (!options.Value.SeedOnStartup)
|
|
{
|
|
return;
|
|
}
|
|
|
|
using var scope = serviceProvider.CreateScope();
|
|
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
|
|
|
|
var configuredEmail = options.Value.Email;
|
|
var existingUser = await userManager.FindByEmailAsync(configuredEmail);
|
|
|
|
if (existingUser is not null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
var user = new ApplicationUser
|
|
{
|
|
UserName = configuredEmail,
|
|
Email = configuredEmail,
|
|
EmailConfirmed = true
|
|
};
|
|
|
|
var result = await userManager.CreateAsync(user, options.Value.Password);
|
|
if (!result.Succeeded)
|
|
{
|
|
var errors = string.Join("; ", result.Errors.Select(x => x.Description));
|
|
logger.LogError("Unable to seed single user account {Email}. Errors: {Errors}", configuredEmail, errors);
|
|
return;
|
|
}
|
|
|
|
logger.LogInformation("Seeded single user account {Email}", configuredEmail);
|
|
}
|
|
|
|
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
|
|
}
|