83 lines
2.7 KiB
C#
83 lines
2.7 KiB
C#
using Microsoft.EntityFrameworkCore.Migrations;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using System;
|
|
using System.IO;
|
|
using System.Security.Cryptography;
|
|
using System.Text;
|
|
using Application.Services.Encryption;
|
|
// Ensure this namespace matches your actual service namespace
|
|
// Ensure this namespace matches your actual service namespace
|
|
using Domain.Entities;
|
|
using Infrastructure.Services.Encryption;
|
|
|
|
#nullable disable
|
|
|
|
namespace Infrastructure.Migrations;
|
|
|
|
/// <inheritdoc />
|
|
public partial class SeedAdminTable : Migration{
|
|
|
|
private readonly IConfiguration _configuration;
|
|
|
|
public SeedAdminTable()
|
|
{
|
|
var builder = new ConfigurationBuilder()
|
|
.SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), "../API"))
|
|
.AddJsonFile("appsettings.json");
|
|
|
|
_configuration = builder.Build();
|
|
|
|
// Build the service provider
|
|
var serviceProvider = new ServiceCollection()
|
|
.AddSingleton<IEncryptionService, EncryptionService>()
|
|
.BuildServiceProvider();
|
|
}
|
|
protected override void Up(MigrationBuilder migrationBuilder)
|
|
{
|
|
var adminName = _configuration["AdminSettings:Name"];
|
|
var adminEmail = _configuration["AdminSettings:Email"];
|
|
var adminPassword = _configuration["AdminSettings:Password"];
|
|
|
|
var adminUser = new Admin();
|
|
adminUser.SetName(adminName);
|
|
adminUser.SetEmail(adminEmail);
|
|
adminUser.SetPassword(ComputeSha256Hash(adminPassword));
|
|
|
|
migrationBuilder.InsertData(
|
|
table: "Admins",
|
|
columns: new[] { "Id", "Name", "Email", "Password" },
|
|
values: new object[] { adminUser.Id, adminUser.Name, adminUser.Email, adminUser.Password }
|
|
);
|
|
}
|
|
|
|
private static string ComputeSha256Hash(string rawData)
|
|
{
|
|
// Create a SHA256
|
|
using (SHA256 sha256Hash = SHA256.Create())
|
|
{
|
|
// ComputeHash - returns byte array
|
|
byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(rawData));
|
|
|
|
// Convert byte array to a string
|
|
StringBuilder builder = new StringBuilder();
|
|
for (int i = 0; i < bytes.Length; i++)
|
|
{
|
|
builder.Append(bytes[i].ToString("x2"));
|
|
}
|
|
return builder.ToString();
|
|
}
|
|
}
|
|
|
|
protected override void Down(MigrationBuilder migrationBuilder)
|
|
{
|
|
var adminEmail = _configuration["AdminSettings:Email"];
|
|
migrationBuilder.DeleteData(
|
|
table: "Admins",
|
|
keyColumn: "Email",
|
|
keyValue: adminEmail
|
|
);
|
|
}
|
|
}
|
|
|