Commit f3f4bf51 authored by Almouhannad's avatar Almouhannad

(B) Seed admin user

parent 45a07430
......@@ -73,6 +73,7 @@ var app = builder.Build();
#region Seed database
await SeedHelper.Seed(app);
await SeedAdminUserHelper.Seed(app);
#endregion
// Configure the HTTP request pipeline.
......
using Domain.Entities.Identity.UserRoles;
using Domain.Entities.Medicals.Medicines.MedicineFormValues;
using Domain.Entities.People.Doctors.Shared.Constants.DoctorStatusValues;
using Domain.Entities.People.Employees.Relations.EmployeeFamilyMembers.FamilyRoleValues;
using Domain.Entities.People.Shared.GenderValues;
using Persistence.SeedDatabase;
using Persistence.SeedDatabase.AdminUser;
namespace API.SeedDatabaseHelper;
public class SeedAdminUserHelper
{
public static async Task Seed(IApplicationBuilder applicationBuilder)
{
using (var serviceScope = applicationBuilder.ApplicationServices.CreateScope())
{
var seedAdminUser = serviceScope.ServiceProvider.GetRequiredService<ISeedAdminUser>();
await seedAdminUser.Seed();
}
}
}
namespace Persistence.SeedDatabase.AdminUser;
public interface ISeedAdminUser
{
public Task Seed();
}

using Domain.Entities.Identity.UserRoles;
using Domain.Entities.Identity.Users;
using Domain.Exceptions.InvalidValue;
using Domain.Shared;
using Microsoft.EntityFrameworkCore;
using Persistence.Context;
using Persistence.Identity.PasswordsHashing;
namespace Persistence.SeedDatabase.AdminUser;
public class SeedAdminUser : ISeedAdminUser
{
#region CTOR DI
private readonly ClinicsDbContext _context;
private readonly IPasswordHasher _passwordHasher;
public SeedAdminUser(ClinicsDbContext context, IPasswordHasher passwordHasher)
{
_context = context;
_passwordHasher = passwordHasher;
}
#endregion
public async Task Seed()
{
DbSet<User> users = _context.Set<User>();
Result<User> adminUserResult = User.Create(
"admin",
_passwordHasher.Hash("123"),
Roles.Admin.Name
);
if (adminUserResult.IsFailure)
throw new Exception("Unable to seed admin user");
if (users.Include(user => user.Role).Where(user => user.Role == Roles.Admin).ToList().Count != 1)
{
var adminUser = adminUserResult.Value;
_context.Entry(adminUser.Role).State = EntityState.Unchanged;
users.Add(adminUserResult.Value);
await _context.SaveChangesAsync();
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment