You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Dotnet-WebAPI/AppContext/AppContext.cs

73 lines
1.9 KiB

using System.Security.Cryptography;
using AppContext.Entities;
using Microsoft.AspNetCore.Cryptography.KeyDerivation;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace AppContext;
public class AppContext : DbContext
{
public DbSet<UserEntity> Users { get; init; }
public DbSet<TacticEntity> Tactics { get; init; }
public DbSet<TeamEntity> Teams { get; init; }
public DbSet<MemberEntity> Members { get; init; }
public DbSet<TacticStepEntity> TacticSteps { get; set; }
public AppContext()
{
}
public AppContext(DbContextOptions<AppContext> options) : base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
if (optionsBuilder.IsConfigured)
{
return;
}
var pgsqliteDsn = Environment.GetEnvironmentVariable("PGSQL_DSN");
if (pgsqliteDsn != null)
{
optionsBuilder.UseNpgsql(pgsqliteDsn);
}
else
{
optionsBuilder.UseSqlite("Data Source=database.db");
}
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<UserEntity>()
.Property(e => e.Password)
.HasConversion(
v => HashString(v),
v => v
);
builder.Entity<MemberEntity>()
.HasKey("UserId", "TeamId");
}
private static string HashString(string str)
{
byte[] salt = RandomNumberGenerator.GetBytes(128 / 8);
return Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: str,
salt,
prf: KeyDerivationPrf.HMACSHA256,
iterationCount: 50000,
numBytesRequested: 256 / 8
));
}
}