using Microsoft.AspNetCore.DataProtection; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using OTSSignsOrchestrator.Core.Models.Entities; namespace OTSSignsOrchestrator.Core.Data; public class XiboContext : DbContext { private readonly IDataProtectionProvider? _dataProtection; public XiboContext(DbContextOptions options, IDataProtectionProvider? dataProtection = null) : base(options) { _dataProtection = dataProtection; } public DbSet CmsInstances => Set(); public DbSet SshHosts => Set(); public DbSet SecretMetadata => Set(); public DbSet OperationLogs => Set(); public DbSet AppSettings => Set(); protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); // --- CmsInstance --- modelBuilder.Entity(entity => { entity.HasIndex(e => e.StackName).IsUnique(); entity.HasIndex(e => e.CustomerName); entity.HasQueryFilter(e => e.DeletedAt == null); entity.HasOne(e => e.SshHost) .WithMany(h => h.Instances) .HasForeignKey(e => e.SshHostId) .OnDelete(DeleteBehavior.SetNull); if (_dataProtection != null) { var protector = _dataProtection.CreateProtector("OTSSignsOrchestrator.CmsInstance"); var pwdConverter = new ValueConverter( v => v != null ? protector.Protect(v) : null, v => v != null ? protector.Unprotect(v) : null); entity.Property(e => e.XiboPassword).HasConversion(pwdConverter); entity.Property(e => e.XiboUsername).HasConversion(pwdConverter); entity.Property(e => e.TemplateRepoPat).HasConversion(pwdConverter); entity.Property(e => e.CifsPassword).HasConversion(pwdConverter); } }); // --- SshHost --- modelBuilder.Entity(entity => { entity.HasIndex(e => e.Label).IsUnique(); if (_dataProtection != null) { var protector = _dataProtection.CreateProtector("OTSSignsOrchestrator.SshHost"); var passphraseConverter = new ValueConverter( v => v != null ? protector.Protect(v) : null, v => v != null ? protector.Unprotect(v) : null); var passwordConverter = new ValueConverter( v => v != null ? protector.Protect(v) : null, v => v != null ? protector.Unprotect(v) : null); entity.Property(e => e.KeyPassphrase).HasConversion(passphraseConverter); entity.Property(e => e.Password).HasConversion(passwordConverter); } }); // --- SecretMetadata --- modelBuilder.Entity(entity => { entity.HasIndex(e => e.Name).IsUnique(); }); // --- OperationLog --- modelBuilder.Entity(entity => { entity.HasIndex(e => e.Timestamp); entity.HasIndex(e => e.InstanceId); entity.HasIndex(e => e.Operation); }); // --- AppSetting --- modelBuilder.Entity(entity => { entity.HasKey(e => e.Key); entity.HasIndex(e => e.Category); }); } }