| | | 1 | | using System.ComponentModel; |
| | | 2 | | using System.Reflection; |
| | | 3 | | using ArturRios.Heimdall.Data.Configuration; |
| | | 4 | | using ArturRios.Heimdall.Domain.Entities; |
| | | 5 | | using ArturRios.Heimdall.Domain.Enums; |
| | | 6 | | using ArturRios.Util.Hashing; |
| | | 7 | | using Microsoft.EntityFrameworkCore; |
| | | 8 | | using Microsoft.Extensions.Logging; |
| | | 9 | | |
| | | 10 | | namespace ArturRios.Heimdall.Data.Seeding; |
| | | 11 | | |
| | | 12 | | /// <summary> |
| | | 13 | | /// Brings a migrated database to the state the application assumes: every <see cref="Roles" /> |
| | | 14 | | /// member present as a row, and at least one system administrator to sign in as. Idempotent, so |
| | | 15 | | /// it runs on every startup. It never applies migrations — that is <c>scripts/migrations.py</c>'s |
| | | 16 | | /// job — and refuses to seed a schema that is behind. |
| | | 17 | | /// </summary> |
| | 901 | 18 | | public class DatabaseSeeder( |
| | 901 | 19 | | AppDbContext context, |
| | 901 | 20 | | MasterUserOptions masterUser, |
| | 901 | 21 | | ILogger<DatabaseSeeder> logger) |
| | | 22 | | { |
| | | 23 | | public async Task SeedAsync(CancellationToken cancellationToken = default) |
| | | 24 | | { |
| | 901 | 25 | | await EnsureSchemaIsUpToDateAsync(cancellationToken); |
| | 901 | 26 | | await EnsureRolesAsync(cancellationToken); |
| | 901 | 27 | | await EnsureSystemAdminAsync(cancellationToken); |
| | 901 | 28 | | } |
| | | 29 | | |
| | | 30 | | private async Task EnsureSchemaIsUpToDateAsync(CancellationToken cancellationToken) |
| | | 31 | | { |
| | 901 | 32 | | var pending = (await context.Database.GetPendingMigrationsAsync(cancellationToken)).ToList(); |
| | | 33 | | |
| | 901 | 34 | | if (pending.Count == 0) |
| | | 35 | | { |
| | 901 | 36 | | return; |
| | | 37 | | } |
| | | 38 | | |
| | 0 | 39 | | var names = string.Join(", ", pending); |
| | | 40 | | |
| | 0 | 41 | | logger.LogCritical("Database is behind by {Count} migration(s): {Migrations}", pending.Count, names); |
| | | 42 | | |
| | 0 | 43 | | throw new InvalidOperationException( |
| | 0 | 44 | | $"The database is missing {pending.Count} migration(s): {names}. Apply them with " + |
| | 0 | 45 | | "scripts/migrations.py before starting the API."); |
| | 901 | 46 | | } |
| | | 47 | | |
| | | 48 | | private async Task EnsureRolesAsync(CancellationToken cancellationToken) |
| | | 49 | | { |
| | 3601 | 50 | | var stored = await context.Roles.ToDictionaryAsync(x => x.Id, cancellationToken); |
| | | 51 | | |
| | 7208 | 52 | | foreach (var role in Enum.GetValues<Roles>()) |
| | | 53 | | { |
| | 2703 | 54 | | var id = (long)role; |
| | 2703 | 55 | | var name = role.ToString(); |
| | 2703 | 56 | | var description = DescriptionOf(role); |
| | | 57 | | |
| | 2703 | 58 | | if (!stored.TryGetValue(id, out var existing)) |
| | | 59 | | { |
| | 3 | 60 | | context.Roles.Add(new Role { Id = id, Name = name, Description = description }); |
| | | 61 | | |
| | 3 | 62 | | logger.LogInformation("Seeding role {RoleName} with id {RoleId}", name, id); |
| | | 63 | | |
| | 3 | 64 | | continue; |
| | | 65 | | } |
| | | 66 | | |
| | 2700 | 67 | | if (existing.Name == name && existing.Description == description) |
| | | 68 | | { |
| | | 69 | | continue; |
| | | 70 | | } |
| | | 71 | | |
| | 0 | 72 | | existing.Name = name; |
| | 0 | 73 | | existing.Description = description; |
| | | 74 | | |
| | 0 | 75 | | logger.LogInformation("Realigning role {RoleId} with the Roles enum", id); |
| | | 76 | | } |
| | | 77 | | |
| | 901 | 78 | | await context.SaveChangesAsync(cancellationToken); |
| | 901 | 79 | | } |
| | | 80 | | |
| | | 81 | | private async Task EnsureSystemAdminAsync(CancellationToken cancellationToken) |
| | | 82 | | { |
| | | 83 | | const long systemAdminRoleId = (long)Roles.SystemAdmin; |
| | | 84 | | |
| | 901 | 85 | | var exists = await context.Persons |
| | 901 | 86 | | .AnyAsync(x => x.RoleId == systemAdminRoleId && !x.IsDeleted, cancellationToken); |
| | | 87 | | |
| | 901 | 88 | | if (exists) |
| | | 89 | | { |
| | 900 | 90 | | return; |
| | | 91 | | } |
| | | 92 | | |
| | 1 | 93 | | if (!masterUser.IsComplete) |
| | | 94 | | { |
| | 0 | 95 | | throw new InvalidOperationException( |
| | 0 | 96 | | "The database has no system administrator and the master user is not configured. Set " + |
| | 0 | 97 | | $"{MasterUserOptions.NameVariable}, {MasterUserOptions.EmailVariable} and " + |
| | 0 | 98 | | $"{MasterUserOptions.PasswordVariable} before starting the API."); |
| | | 99 | | } |
| | | 100 | | |
| | 1 | 101 | | var passwordHash = Hash.EncodeWithRandomSalt(masterUser.Password, out var salt); |
| | | 102 | | |
| | 1 | 103 | | context.Persons.Add(new Person |
| | 1 | 104 | | { |
| | 1 | 105 | | Name = masterUser.Name, |
| | 1 | 106 | | Email = masterUser.Email, |
| | 1 | 107 | | PasswordHash = passwordHash, |
| | 1 | 108 | | Salt = salt, |
| | 1 | 109 | | EmailVerified = true, |
| | 1 | 110 | | RoleId = systemAdminRoleId |
| | 1 | 111 | | }); |
| | | 112 | | |
| | 1 | 113 | | await context.SaveChangesAsync(cancellationToken); |
| | | 114 | | |
| | | 115 | | // The address is deliberately not logged (NFR-22). It came from the environment the |
| | | 116 | | // operator set, so the line tells them nothing they do not already know, and it would |
| | | 117 | | // otherwise be written on every start-up for the life of the deployment. |
| | 1 | 118 | | logger.LogInformation("Seeded the master system administrator"); |
| | 901 | 119 | | } |
| | | 120 | | |
| | | 121 | | private static string DescriptionOf(Roles role) => |
| | 2703 | 122 | | typeof(Roles).GetField(role.ToString())?.GetCustomAttribute<DescriptionAttribute>()?.Description |
| | 2703 | 123 | | ?? role.ToString(); |
| | | 124 | | } |