Commit 8deabac6 authored by Almouhannad's avatar Almouhannad

(B) Add seed for users, fix constant values issues

parent 0df5c192
...@@ -14,7 +14,7 @@ public class SeedAdminUserHelper ...@@ -14,7 +14,7 @@ public class SeedAdminUserHelper
{ {
using (var serviceScope = applicationBuilder.ApplicationServices.CreateScope()) using (var serviceScope = applicationBuilder.ApplicationServices.CreateScope())
{ {
var seedAdminUser = serviceScope.ServiceProvider.GetRequiredService<ISeedAdminUser>(); var seedAdminUser = serviceScope.ServiceProvider.GetRequiredService<ISeedUsers>();
await seedAdminUser.Seed(); await seedAdminUser.Seed();
} }
} }
......
...@@ -25,7 +25,7 @@ public class SeedHelper ...@@ -25,7 +25,7 @@ public class SeedHelper
var seedMedicineForms = serviceScope.ServiceProvider.GetRequiredService<ISeed<MedicineForm>>(); var seedMedicineForms = serviceScope.ServiceProvider.GetRequiredService<ISeed<MedicineForm>>();
await seedMedicineForms.Seed(); await seedMedicineForms.Seed();
var seedUserRoles = serviceScope.ServiceProvider.GetRequiredService<ISeed<Role>>(); var seedUserRoles = serviceScope.ServiceProvider.GetRequiredService<ISeed<UserRole>>();
await seedUserRoles.Seed(); await seedUserRoles.Seed();
} }
} }
......
...@@ -38,7 +38,7 @@ public class LoginCommandHandler : CommandHandlerBase<LoginCommand, LoginRespons ...@@ -38,7 +38,7 @@ public class LoginCommandHandler : CommandHandlerBase<LoginCommand, LoginRespons
#region 2. Generate Response #region 2. Generate Response
#region 2.1. Admin #region 2.1. Admin
if (user.Role == Roles.Admin) if (user.Role == UsersRoles.Admin)
{ {
var token = _jwtProvider.Generate(user); var token = _jwtProvider.Generate(user);
return LoginResponse.GetResponse(token); return LoginResponse.GetResponse(token);
...@@ -46,7 +46,7 @@ public class LoginCommandHandler : CommandHandlerBase<LoginCommand, LoginRespons ...@@ -46,7 +46,7 @@ public class LoginCommandHandler : CommandHandlerBase<LoginCommand, LoginRespons
#endregion #endregion
#region 2.2. Doctor #region 2.2. Doctor
if (user.Role == Roles.Doctor) if (user.Role == UsersRoles.Doctor)
{ {
var doctorUserResult = await _userRepository.GetDoctorUserByUserNameFullAsync(user.UserName); var doctorUserResult = await _userRepository.GetDoctorUserByUserNameFullAsync(user.UserName);
if (doctorUserResult.IsFailure) if (doctorUserResult.IsFailure)
...@@ -58,7 +58,7 @@ public class LoginCommandHandler : CommandHandlerBase<LoginCommand, LoginRespons ...@@ -58,7 +58,7 @@ public class LoginCommandHandler : CommandHandlerBase<LoginCommand, LoginRespons
#endregion #endregion
#region 2.3. Receptionist user #region 2.3. Receptionist user
if (user.Role == Roles.Receptionist) if (user.Role == UsersRoles.Receptionist)
{ {
var receptionistUser = await _userRepository.GetReceptionistUserByUserNameFullAsync(user.UserName); var receptionistUser = await _userRepository.GetReceptionistUserByUserNameFullAsync(user.UserName);
if (receptionistUser.IsFailure) if (receptionistUser.IsFailure)
......
...@@ -2,14 +2,14 @@ ...@@ -2,14 +2,14 @@
namespace Domain.Entities.Identity.UserRoles; namespace Domain.Entities.Identity.UserRoles;
public sealed class Role : Entity public sealed class UserRole : Entity
{ {
#region Private ctor #region Private ctor
private Role(int id) : base(id) private UserRole(int id) : base(id)
{ {
} }
private Role(int id, string name) : base(id) private UserRole(int id, string name) : base(id)
{ {
Name = name; Name = name;
} }
...@@ -22,9 +22,9 @@ public sealed class Role : Entity ...@@ -22,9 +22,9 @@ public sealed class Role : Entity
#region Methods #region Methods
#region Static factory #region Static factory
internal static Role Create(int id, string name) internal static UserRole Create(int id, string name)
{ {
return new Role(id, name); return new UserRole(id, name);
} }
#endregion #endregion
......
namespace Domain.Entities.Identity.UserRoles; namespace Domain.Entities.Identity.UserRoles;
public static class Roles public static class UsersRoles
{ {
#region Constant values #region Constant values
public static int Count => 3; public static int Count => 3;
...@@ -8,13 +8,18 @@ public static class Roles ...@@ -8,13 +8,18 @@ public static class Roles
public const string DoctorName = "doctor"; public const string DoctorName = "doctor";
public const string ReceptionistName = "receptionist"; public const string ReceptionistName = "receptionist";
public static Role Admin => Role.Create(1, AdminName); private static readonly UserRole _admin = UserRole.Create(1, AdminName);
public static Role Doctor => Role.Create(2, DoctorName); public static UserRole Admin => _admin;
public static Role Receptionist => Role.Create(3, ReceptionistName);
public static List<Role> GetAll() private static readonly UserRole _doctor = UserRole.Create(2, DoctorName);
public static UserRole Doctor => _doctor;
private static readonly UserRole _receptionist = UserRole.Create(3, ReceptionistName);
public static UserRole Receptionist => _receptionist;
public static List<UserRole> GetAll()
{ {
List<Role> roles = new(); List<UserRole> roles = new();
roles.Add(Admin); roles.Add(Admin);
roles.Add(Doctor); roles.Add(Doctor);
roles.Add(Receptionist); roles.Add(Receptionist);
......
...@@ -37,7 +37,7 @@ public sealed class DoctorUser : Entity ...@@ -37,7 +37,7 @@ public sealed class DoctorUser : Entity
if (doctorResult.IsFailure) if (doctorResult.IsFailure)
return Result.Failure<DoctorUser>(doctorResult.Error); return Result.Failure<DoctorUser>(doctorResult.Error);
Result<User> userResult = User.Create(username, hashedPassword, Roles.Doctor.Name); Result<User> userResult = User.Create(username, hashedPassword, UsersRoles.Doctor.Name);
if (userResult.IsFailure) if (userResult.IsFailure)
return Result.Failure<DoctorUser>(userResult.Error); return Result.Failure<DoctorUser>(userResult.Error);
......
...@@ -37,7 +37,7 @@ public sealed class ReceptionistUser : Entity ...@@ -37,7 +37,7 @@ public sealed class ReceptionistUser : Entity
if (personalInfoResult.IsFailure) if (personalInfoResult.IsFailure)
return Result.Failure<ReceptionistUser>(personalInfoResult.Error); return Result.Failure<ReceptionistUser>(personalInfoResult.Error);
Result<User> userResult = User.Create(userName, hashedPassword, Roles.Receptionist.Name); Result<User> userResult = User.Create(userName, hashedPassword, UsersRoles.Receptionist.Name);
if (userResult.IsFailure) if (userResult.IsFailure)
return Result.Failure<ReceptionistUser>(userResult.Error); return Result.Failure<ReceptionistUser>(userResult.Error);
......
...@@ -12,7 +12,7 @@ public sealed class User : Entity ...@@ -12,7 +12,7 @@ public sealed class User : Entity
{ {
} }
private User(int id, string userName, string hashedPassword, Role role) : base(id) private User(int id, string userName, string hashedPassword, UserRole role) : base(id)
{ {
UserName = userName; UserName = userName;
HashedPassword = hashedPassword; HashedPassword = hashedPassword;
...@@ -23,7 +23,7 @@ public sealed class User : Entity ...@@ -23,7 +23,7 @@ public sealed class User : Entity
#region Properties #region Properties
public string UserName { get; private set; } = null!; public string UserName { get; private set; } = null!;
public string HashedPassword { get; private set; } = null!; public string HashedPassword { get; private set; } = null!;
public Role Role { get; private set; } = null!; public UserRole Role { get; private set; } = null!;
#endregion #endregion
#region Methods #region Methods
...@@ -37,9 +37,9 @@ public sealed class User : Entity ...@@ -37,9 +37,9 @@ public sealed class User : Entity
} }
#region Check role #region Check role
Result<Role> selectedRole = Result.Failure<Role>(IdentityErrors.InvalidRole); Result<UserRole> selectedRole = Result.Failure<UserRole>(IdentityErrors.InvalidRole);
List<Role> roles = Roles.GetAll(); List<UserRole> roles = UsersRoles.GetAll();
foreach (Role roleItem in roles) foreach (UserRole roleItem in roles)
{ {
if (roleItem.Name == role) if (roleItem.Name == role)
selectedRole = roleItem; selectedRole = roleItem;
......
...@@ -9,38 +9,14 @@ public static class DoctorStatuses ...@@ -9,38 +9,14 @@ public static class DoctorStatuses
public static int Count => 3; public static int Count => 3;
public static DoctorStatus Available private readonly static DoctorStatus _available = DoctorStatus.Create("متاح", 1).Value;
{ public static DoctorStatus Available => _available;
get
{
var result = DoctorStatus.Create("متاح", 1);
if (result.IsFailure)
throw new InvalidValuesDomainException<DoctorStatus>();
return result.Value;
}
}
public static DoctorStatus Working private readonly static DoctorStatus _working = DoctorStatus.Create("لديه مريض", 2).Value;
{ public static DoctorStatus Working => _working;
get
{
var result = DoctorStatus.Create("لديه مريض", 2);
if (result.IsFailure)
throw new InvalidValuesDomainException<DoctorStatus>();
return result.Value;
}
}
public static DoctorStatus Busy private readonly static DoctorStatus _busy = DoctorStatus.Create("مشغول", 3).Value;
{ public static DoctorStatus Busy => _busy;
get
{
var result = DoctorStatus.Create("مشغول", 3);
if (result.IsFailure)
throw new InvalidValuesDomainException<DoctorStatus>();
return result.Value;
}
}
#endregion #endregion
} }
...@@ -7,49 +7,19 @@ public static class FamilyRoles ...@@ -7,49 +7,19 @@ public static class FamilyRoles
#region Constant id values #region Constant id values
public static int Count => 4; public static int Count => 4;
public static FamilyRole Husband
{ public readonly static FamilyRole _husband = FamilyRole.Create("زوج", 1).Value;
get public static FamilyRole Husband => _husband;
{
var result = FamilyRole.Create("زوج", 1); public readonly static FamilyRole _wife = FamilyRole.Create("زوجة", 2).Value;
if (result.IsFailure) public static FamilyRole Wife => _wife;
throw new InvalidValuesDomainException<FamilyRole>();
return result.Value; public readonly static FamilyRole _son = FamilyRole.Create("ابن", 3).Value;
} public static FamilyRole Son => _son;
}
public readonly static FamilyRole _daughter = FamilyRole.Create("ابنة", 4).Value;
public static FamilyRole Wife public static FamilyRole Daughter => _daughter;
{
get
{
var result = FamilyRole.Create("زوجة", 2);
if (result.IsFailure)
throw new InvalidValuesDomainException<FamilyRole>();
return result.Value;
}
}
public static FamilyRole Son
{
get
{
var result = FamilyRole.Create("ابن", 3);
if (result.IsFailure)
throw new InvalidValuesDomainException<FamilyRole>();
return result.Value;
}
}
public static FamilyRole Daughter
{
get
{
var result = FamilyRole.Create("ابنة", 4);
if (result.IsFailure)
throw new InvalidValuesDomainException<FamilyRole>();
return result.Value;
}
}
#endregion #endregion
} }
...@@ -4,11 +4,11 @@ using Microsoft.EntityFrameworkCore.Metadata.Builders; ...@@ -4,11 +4,11 @@ using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Persistence.Configurations.Identity.Roles; namespace Persistence.Configurations.Identity.Roles;
public class RoleConfiguration : IEntityTypeConfiguration<Role> public class RoleConfiguration : IEntityTypeConfiguration<UserRole>
{ {
public void Configure(EntityTypeBuilder<Role> builder) public void Configure(EntityTypeBuilder<UserRole> builder)
{ {
builder.ToTable(nameof(Role)); builder.ToTable(nameof(UserRole));
builder.Property(role => role.Id).ValueGeneratedNever(); builder.Property(role => role.Id).ValueGeneratedNever();
......
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Persistence.Migrations
{
/// <inheritdoc />
public partial class Update_User_Roles : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_User_Role_RoleId",
table: "User");
migrationBuilder.DropTable(
name: "Role");
migrationBuilder.CreateTable(
name: "UserRole",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false),
Name = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_UserRole", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_UserRole_Name",
table: "UserRole",
column: "Name",
unique: true);
migrationBuilder.AddForeignKey(
name: "FK_User_UserRole_RoleId",
table: "User",
column: "RoleId",
principalTable: "UserRole",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_User_UserRole_RoleId",
table: "User");
migrationBuilder.DropTable(
name: "UserRole");
migrationBuilder.CreateTable(
name: "Role",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false),
Name = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Role", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_Role_Name",
table: "Role",
column: "Name",
unique: true);
migrationBuilder.AddForeignKey(
name: "FK_User_Role_RoleId",
table: "User",
column: "RoleId",
principalTable: "Role",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
}
}
...@@ -22,7 +22,7 @@ namespace Persistence.Migrations ...@@ -22,7 +22,7 @@ namespace Persistence.Migrations
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("Domain.Entities.Identity.UserRoles.Role", b => modelBuilder.Entity("Domain.Entities.Identity.UserRoles.UserRole", b =>
{ {
b.Property<int>("Id") b.Property<int>("Id")
.HasColumnType("int"); .HasColumnType("int");
...@@ -37,7 +37,7 @@ namespace Persistence.Migrations ...@@ -37,7 +37,7 @@ namespace Persistence.Migrations
b.HasIndex("Name") b.HasIndex("Name")
.IsUnique(); .IsUnique();
b.ToTable("Role", (string)null); b.ToTable("UserRole", (string)null);
}); });
modelBuilder.Entity("Domain.Entities.Identity.Users.DoctorUser", b => modelBuilder.Entity("Domain.Entities.Identity.Users.DoctorUser", b =>
...@@ -763,7 +763,7 @@ namespace Persistence.Migrations ...@@ -763,7 +763,7 @@ namespace Persistence.Migrations
modelBuilder.Entity("Domain.Entities.Identity.Users.User", b => modelBuilder.Entity("Domain.Entities.Identity.Users.User", b =>
{ {
b.HasOne("Domain.Entities.Identity.UserRoles.Role", "Role") b.HasOne("Domain.Entities.Identity.UserRoles.UserRole", "Role")
.WithMany() .WithMany()
.HasForeignKey("RoleId") .HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
......

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();
}
}
}
...@@ -4,7 +4,7 @@ using Persistence.Context; ...@@ -4,7 +4,7 @@ using Persistence.Context;
namespace Persistence.SeedDatabase; namespace Persistence.SeedDatabase;
public class UserRoles : ISeed<Role> public class UserRoles : ISeed<UserRole>
{ {
#region CTOR DI #region CTOR DI
private readonly ClinicsDbContext _context; private readonly ClinicsDbContext _context;
...@@ -16,19 +16,19 @@ public class UserRoles : ISeed<Role> ...@@ -16,19 +16,19 @@ public class UserRoles : ISeed<Role>
#endregion #endregion
public async Task Seed() public async Task Seed()
{ {
DbSet<Role> roles = _context.Set<Role>(); DbSet<UserRole> roles = _context.Set<UserRole>();
var current = await roles.ToListAsync(); var current = await roles.ToListAsync();
// TODO: perform deep check on all seed operations // TODO: perform deep check on all seed operations
if (current.Count != Roles.Count) if (current.Count != UsersRoles.Count)
{ {
roles.RemoveRange(current); roles.RemoveRange(current);
roles.Add(Roles.Admin); roles.Add(UsersRoles.Admin);
roles.Add(Roles.Doctor); roles.Add(UsersRoles.Doctor);
roles.Add(Roles.Receptionist); roles.Add(UsersRoles.Receptionist);
await _context.SaveChangesAsync(); await _context.SaveChangesAsync();
} }
......
namespace Persistence.SeedDatabase.AdminUser; namespace Persistence.SeedDatabase.AdminUser;
public interface ISeedAdminUser public interface ISeedUsers
{ {
public Task Seed(); public Task Seed();
} }

using Domain.Entities.Identity.UserRoles;
using Domain.Entities.Identity.Users;
using Domain.Shared;
using Microsoft.EntityFrameworkCore;
using Persistence.Context;
using Persistence.Identity.PasswordsHashing;
namespace Persistence.SeedDatabase.AdminUser;
public class SeedUsers : ISeedUsers
{
#region CTOR DI
private readonly ClinicsDbContext _context;
private readonly IPasswordHasher _passwordHasher;
public SeedUsers(ClinicsDbContext context, IPasswordHasher passwordHasher)
{
_context = context;
_passwordHasher = passwordHasher;
}
#endregion
public async Task Seed()
{
var currentCount = _context.Set<User>().ToList().Count;
if (currentCount == 0)
{
#region Seed admin
Result<User> adminUserResult = User.Create(
"admin",
_passwordHasher.Hash("123"),
UsersRoles.Admin.Name
);
if (adminUserResult.IsFailure)
throw new Exception("Unable to seed admin user");
var adminUser = adminUserResult.Value;
_context.Entry(adminUser.Role).State = EntityState.Unchanged;
_context.Set<User>().Add(adminUserResult.Value);
#endregion
#region Seed doctor
var doctorUserCreateResult = DoctorUser.Create(
"doctor",
_passwordHasher.Hash("123"),
"محمد",
"صالح",
"التركي"
);
if (doctorUserCreateResult.IsFailure)
throw new Exception("Unable to seed doctor user");
var doctorUser = doctorUserCreateResult.Value;
_context.Entry(doctorUser.User.Role).State = EntityState.Unchanged;
_context.Entry(doctorUser.Doctor.Status).State = EntityState.Unchanged;
_context.Set<DoctorUser>().Add(doctorUser);
#endregion
#region Seed receptionist
var receptionistUserCreateResult = ReceptionistUser.Create(
"receptionist",
_passwordHasher.Hash("123"),
"موفق",
"سامي",
"الحسين"
);
if (receptionistUserCreateResult.IsFailure)
throw new Exception("Unable to seed receptionist user");
var receptionistUser = receptionistUserCreateResult.Value;
_context.Entry(receptionistUser.User.Role).State = EntityState.Unchanged;
_context.Set<ReceptionistUser>().Add(receptionistUser);
#endregion
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