using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json; using PSTW_CentralSystem.Models; using System.Text.Json; namespace PSTW_CentralSystem.DBContext { public class AuthDBContext : IdentityDbContext { private readonly IWebHostEnvironment _hostingEnvironment; public AuthDBContext(DbContextOptions options, IWebHostEnvironment hostingEnvironment) : base(options) { _hostingEnvironment = hostingEnvironment; } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity() .Property(e => e.MethodAllowedUserType) .HasConversion( v => JsonConvert.SerializeObject(v), // Convert List to JSON string v => JsonConvert.DeserializeObject>(v)); // Seeding Roles modelBuilder.Entity().HasData( new RoleModel { Id = 1, Name = "SuperAdmin", NormalizedName = "SuperAdmin".ToUpper(), Description = "Can access all pages" }, new RoleModel { Id = 2, Name = "SystemAdmin", NormalizedName = "SystemAdmin".ToUpper(), Description = "Can access some admin pages" }, new RoleModel { Id = 3, Name = "Engineer", NormalizedName = "Engineer".ToUpper(), Description = "Can access operation pages" }, new RoleModel { Id = 4, Name = "Observer", NormalizedName = "Observer".ToUpper(), Description = "Can access data viewer pages" }); var passwordHasher = new PasswordHasher(); var superAdmin = new UserModel { Id = 1, // Use `Guid.NewGuid().ToString()` if the Id is a string. FullName = "MAAdmin", UserName = "admin@pstw.com.my", NormalizedUserName = "ADMIN@PSTW.COM.MY", Email = "admin@pstw.com.my", NormalizedEmail = "ADMIN@PSTW.COM.MY", SecurityStamp = Guid.NewGuid().ToString(), EmailConfirmed = true }; var systemAdmin = new UserModel { Id = 2, // Use `Guid.NewGuid().ToString()` if the Id is a string. FullName = "SysAdmin", UserName = "sysadmin@pstw.com.my", NormalizedUserName = "SYSADMIN@PSTW.COM.MY", Email = "sysadmin@pstw.com.my", NormalizedEmail = "SYSADMIN@PSTW.COM.MY", SecurityStamp = Guid.NewGuid().ToString(), EmailConfirmed = true }; // Hash the password superAdmin.PasswordHash = passwordHasher.HashPassword(superAdmin, "5u@Dmin12345678"); systemAdmin.PasswordHash = passwordHasher.HashPassword(systemAdmin, "5ys@Dmin12345678"); modelBuilder.Entity().HasData(superAdmin, systemAdmin); // Seeding AdminRole modelBuilder.Entity>().HasData( new IdentityUserRole { UserId = 1, RoleId = 1 }); } public new DbSet Users { get; set; } public new DbSet Roles { get; set; } public DbSet ModuleSettings { get; set; } } }