| | | 1 | | using Anichron.API.Security; |
| | | 2 | | using Anichron.API.Settings; |
| | | 3 | | using Anichron.Core.Data; |
| | | 4 | | using Anichron.Core.Data.Repository; |
| | | 5 | | using Anichron.Core.Domain; |
| | | 6 | | using Microsoft.EntityFrameworkCore; |
| | | 7 | | using Npgsql; |
| | | 8 | | |
| | | 9 | | namespace Anichron.API.Services; |
| | | 10 | | |
| | | 11 | | public interface IBootstrapSeeder |
| | | 12 | | { |
| | | 13 | | Task SeedAsync(CancellationToken ct); |
| | | 14 | | } |
| | | 15 | | |
| | 10 | 16 | | public sealed partial class BootstrapSeeder( |
| | 10 | 17 | | IUserRepository users, |
| | 10 | 18 | | IUnitOfWork unitOfWork, |
| | 10 | 19 | | IGuidFactory guidFactory, |
| | 10 | 20 | | IPasswordHasher passwordHasher, |
| | 10 | 21 | | IConfiguration configuration, |
| | 10 | 22 | | ILogger<BootstrapSeeder> logger) : IBootstrapSeeder |
| | | 23 | | { |
| | | 24 | | public async Task SeedAsync(CancellationToken ct) |
| | 10 | 25 | | { |
| | 10 | 26 | | if (await users.AnyAsync(ct)) |
| | 1 | 27 | | return; |
| | | 28 | | |
| | 9 | 29 | | var rawUsername = configuration["BOOTSTRAP_ADMIN_USERNAME"]; |
| | 9 | 30 | | var username = string.IsNullOrWhiteSpace(rawUsername) ? AppDefaults.Startup.AdminDefaultUsername : rawUsername; |
| | 9 | 31 | | var rawPassword = configuration["BOOTSTRAP_ADMIN_PASSWORD"]; |
| | 9 | 32 | | var password = string.IsNullOrWhiteSpace(rawPassword) ? AppDefaults.Startup.AdminDefaultPassword : rawPassword; |
| | | 33 | | |
| | 9 | 34 | | Log.CreatingBootstrapAdmin(logger); |
| | | 35 | | |
| | 9 | 36 | | var user = new User |
| | 9 | 37 | | { |
| | 9 | 38 | | Id = guidFactory.NewGuid(), |
| | 9 | 39 | | Username = username.Trim().ToLowerInvariant(), |
| | 9 | 40 | | Email = AppDefaults.Startup.AdminDefaultMail, |
| | 9 | 41 | | PasswordHash = passwordHasher.Hash(password), |
| | 9 | 42 | | IsAdmin = true, |
| | 9 | 43 | | MustChangePassword = true, |
| | 9 | 44 | | }; |
| | | 45 | | |
| | 9 | 46 | | users.Add(user); |
| | | 47 | | try |
| | 9 | 48 | | { |
| | 9 | 49 | | await unitOfWork.SaveChangesAsync(ct); |
| | 7 | 50 | | } |
| | 2 | 51 | | catch (DbUpdateException ex) when (ex.InnerException is PostgresException { SqlState: "23505" }) |
| | 1 | 52 | | { |
| | 1 | 53 | | Log.BootstrapAdminAlreadyExists(logger, ex); |
| | 1 | 54 | | } |
| | 9 | 55 | | } |
| | | 56 | | |
| | | 57 | | private static partial class Log |
| | | 58 | | { |
| | | 59 | | [LoggerMessage(Level = LogLevel.Warning, Message = "No users exist. Creating bootstrap admin.")] |
| | | 60 | | public static partial void CreatingBootstrapAdmin(ILogger logger); |
| | | 61 | | |
| | | 62 | | [LoggerMessage(Level = LogLevel.Information, Message = "Bootstrap admin already exists (concurrent seed). Skippi |
| | | 63 | | public static partial void BootstrapAdminAlreadyExists(ILogger logger, Exception ex); |
| | | 64 | | } |
| | | 65 | | } |