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