Scaffolded project
This commit is contained in:
commit
17a561094a
123 changed files with 64313 additions and 0 deletions
61
Services/Auth/SingleUserSeedService.cs
Normal file
61
Services/Auth/SingleUserSeedService.cs
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
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;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue