//-----------------------------------------------------------------------
//
// Copyright (c) lanedirt. All rights reserved.
// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.
//
//-----------------------------------------------------------------------
namespace AliasClientDb;
using System.Globalization;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Microsoft.Extensions.Configuration;
///
/// The AliasClientDbContext class.
///
public class AliasClientDbContext : DbContext
{
///
/// Initializes a new instance of the class.
///
public AliasClientDbContext()
{
}
///
/// Initializes a new instance of the class.
///
/// The SQLite connection to use to connect to the SQLite database.
/// The action to perform for logging.
public AliasClientDbContext(SqliteConnection sqliteConnection, Action logAction)
: base(GetOptions(sqliteConnection, logAction))
{
}
///
/// Initializes a new instance of the class.
///
/// DbContextOptions to use.
public AliasClientDbContext(DbContextOptions options)
: base(options)
{
}
///
/// Gets or sets the Alias DbSet.
///
public DbSet Aliases { get; set; }
///
/// Gets or sets the Attachment DbSet.
///
public DbSet Attachments { get; set; }
///
/// Gets or sets the Credential DbSet.
///
public DbSet Credentials { get; set; }
///
/// Gets or sets the Password DbSet.
///
public DbSet Passwords { get; set; }
///
/// Gets or sets the Service DbSet.
///
public DbSet Services { get; set; }
///
/// Gets or sets the EncryptionKey DbSet.
///
public DbSet EncryptionKeys { get; set; }
///
/// Gets or sets the Settings DbSet.
///
public DbSet Settings { get; set; }
///
/// Gets or sets the TotpCodes DbSet.
///
public DbSet TotpCodes { get; set; }
///
/// The OnModelCreating method.
///
/// ModelBuilder instance.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
foreach (var entity in modelBuilder.Model.GetEntityTypes())
{
foreach (var property in entity.GetProperties())
{
// SQLite does not support varchar(max) so we use TEXT.
if (property.ClrType == typeof(string) && property.GetMaxLength() == null)
{
property.SetColumnType("TEXT");
}
}
}
// Create a value converter that maps DateTime.MinValue to an empty string and vice versa.
// This prevents an empty string in the client DB from causing a fatal exception while loading
// Alias objects. TODO: when the birthdate field is made optional in data model, this can probably
// be removed. But test the usecase where the birthdate field is empty string (because of browser extension error).
var emptyDateTimeConverter = new ValueConverter(
v => v == DateTime.MinValue ? string.Empty : v.ToString("yyyy-MM-dd HH:mm:ss"),
v => string.IsNullOrEmpty(v) ? DateTime.MinValue : DateTime.Parse(v, CultureInfo.InvariantCulture));
modelBuilder.Entity()
.Property(e => e.BirthDate)
.HasConversion(emptyDateTimeConverter);
// Configure Credential - Alias relationship
modelBuilder.Entity()
.HasOne(l => l.Alias)
.WithMany(c => c.Credentials)
.HasForeignKey(l => l.AliasId)
.OnDelete(DeleteBehavior.Cascade);
// Configure Credential - Service relationship
modelBuilder.Entity()
.HasOne(l => l.Service)
.WithMany(c => c.Credentials)
.HasForeignKey(l => l.ServiceId)
.OnDelete(DeleteBehavior.Cascade);
// Configure Attachment - Credential relationship
modelBuilder.Entity()
.HasOne(l => l.Credential)
.WithMany(c => c.Attachments)
.HasForeignKey(l => l.CredentialId)
.OnDelete(DeleteBehavior.Cascade);
// Configure Password - Credential relationship
modelBuilder.Entity()
.HasOne(l => l.Credential)
.WithMany(c => c.Passwords)
.HasForeignKey(l => l.CredentialId)
.OnDelete(DeleteBehavior.Cascade);
// Configure TotpCode - Credential relationship
modelBuilder.Entity()
.HasOne(l => l.Credential)
.WithMany(c => c.TotpCodes)
.HasForeignKey(l => l.CredentialId)
.OnDelete(DeleteBehavior.Cascade);
}
///
/// Sets up the connection string if it is not already configured.
///
/// DbContextOptionsBuilder instance.
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// If the options are not already configured, use the appsettings.json file.
if (!optionsBuilder.IsConfigured)
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
optionsBuilder
.UseSqlite(configuration.GetConnectionString("AliasClientDbContext"))
.UseLazyLoadingProxies();
// Log queries made as debug output.
optionsBuilder.LogTo(Console.WriteLine);
}
base.OnConfiguring(optionsBuilder);
}
private static DbContextOptions GetOptions(SqliteConnection connection, Action logAction)
{
var optionsBuilder = new DbContextOptionsBuilder();
optionsBuilder.UseSqlite(connection);
optionsBuilder.LogTo(logAction, new[] { DbLoggerCategory.Database.Command.Name });
return optionsBuilder.Options;
}
}