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
{
using (var serviceScope = applicationBuilder.ApplicationServices.CreateScope())
{
var seedAdminUser = serviceScope.ServiceProvider.GetRequiredService<ISeedAdminUser>();
var seedAdminUser = serviceScope.ServiceProvider.GetRequiredService<ISeedUsers>();
await seedAdminUser.Seed();
}
}
......
......@@ -25,7 +25,7 @@ public class SeedHelper
var seedMedicineForms = serviceScope.ServiceProvider.GetRequiredService<ISeed<MedicineForm>>();
await seedMedicineForms.Seed();
var seedUserRoles = serviceScope.ServiceProvider.GetRequiredService<ISeed<Role>>();
var seedUserRoles = serviceScope.ServiceProvider.GetRequiredService<ISeed<UserRole>>();
await seedUserRoles.Seed();
}
}
......
......@@ -38,7 +38,7 @@ public class LoginCommandHandler : CommandHandlerBase<LoginCommand, LoginRespons
#region 2. Generate Response
#region 2.1. Admin
if (user.Role == Roles.Admin)
if (user.Role == UsersRoles.Admin)
{
var token = _jwtProvider.Generate(user);
return LoginResponse.GetResponse(token);
......@@ -46,7 +46,7 @@ public class LoginCommandHandler : CommandHandlerBase<LoginCommand, LoginRespons
#endregion
#region 2.2. Doctor
if (user.Role == Roles.Doctor)
if (user.Role == UsersRoles.Doctor)
{
var doctorUserResult = await _userRepository.GetDoctorUserByUserNameFullAsync(user.UserName);
if (doctorUserResult.IsFailure)
......@@ -58,7 +58,7 @@ public class LoginCommandHandler : CommandHandlerBase<LoginCommand, LoginRespons
#endregion
#region 2.3. Receptionist user
if (user.Role == Roles.Receptionist)
if (user.Role == UsersRoles.Receptionist)
{
var receptionistUser = await _userRepository.GetReceptionistUserByUserNameFullAsync(user.UserName);
if (receptionistUser.IsFailure)
......
......@@ -2,14 +2,14 @@
namespace Domain.Entities.Identity.UserRoles;
public sealed class Role : Entity
public sealed class UserRole : Entity
{
#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;
}
......@@ -22,9 +22,9 @@ public sealed class Role : Entity
#region Methods
#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
......
namespace Domain.Entities.Identity.UserRoles;
public static class Roles
public static class UsersRoles
{
#region Constant values
public static int Count => 3;
......@@ -8,13 +8,18 @@ public static class Roles
public const string DoctorName = "doctor";
public const string ReceptionistName = "receptionist";
public static Role Admin => Role.Create(1, AdminName);
public static Role Doctor => Role.Create(2, DoctorName);
public static Role Receptionist => Role.Create(3, ReceptionistName);
private static readonly UserRole _admin = UserRole.Create(1, AdminName);
public static UserRole Admin => _admin;
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(Doctor);
roles.Add(Receptionist);
......
......@@ -37,7 +37,7 @@ public sealed class DoctorUser : Entity
if (doctorResult.IsFailure)
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)
return Result.Failure<DoctorUser>(userResult.Error);
......
......@@ -37,7 +37,7 @@ public sealed class ReceptionistUser : Entity
if (personalInfoResult.IsFailure)
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)
return Result.Failure<ReceptionistUser>(userResult.Error);
......
......@@ -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;
HashedPassword = hashedPassword;
......@@ -23,7 +23,7 @@ public sealed class User : Entity
#region Properties
public string UserName { 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
#region Methods
......@@ -37,9 +37,9 @@ public sealed class User : Entity
}
#region Check role
Result<Role> selectedRole = Result.Failure<Role>(IdentityErrors.InvalidRole);
List<Role> roles = Roles.GetAll();
foreach (Role roleItem in roles)
Result<UserRole> selectedRole = Result.Failure<UserRole>(IdentityErrors.InvalidRole);
List<UserRole> roles = UsersRoles.GetAll();
foreach (UserRole roleItem in roles)
{
if (roleItem.Name == role)
selectedRole = roleItem;
......
......@@ -9,38 +9,14 @@ public static class DoctorStatuses
public static int Count => 3;
public static DoctorStatus Available
{
get
{
var result = DoctorStatus.Create("متاح", 1);
if (result.IsFailure)
throw new InvalidValuesDomainException<DoctorStatus>();
return result.Value;
}
}
private readonly static DoctorStatus _available = DoctorStatus.Create("متاح", 1).Value;
public static DoctorStatus Available => _available;
public static DoctorStatus Working
{
get
{
var result = DoctorStatus.Create("لديه مريض", 2);
if (result.IsFailure)
throw new InvalidValuesDomainException<DoctorStatus>();
return result.Value;
}
}
private readonly static DoctorStatus _working = DoctorStatus.Create("لديه مريض", 2).Value;
public static DoctorStatus Working => _working;
public static DoctorStatus Busy
{
get
{
var result = DoctorStatus.Create("مشغول", 3);
if (result.IsFailure)
throw new InvalidValuesDomainException<DoctorStatus>();
return result.Value;
}
}
private readonly static DoctorStatus _busy = DoctorStatus.Create("مشغول", 3).Value;
public static DoctorStatus Busy => _busy;
#endregion
}
......@@ -7,49 +7,19 @@ public static class FamilyRoles
#region Constant id values
public static int Count => 4;
public static FamilyRole Husband
{
get
{
var result = FamilyRole.Create("زوج", 1);
if (result.IsFailure)
throw new InvalidValuesDomainException<FamilyRole>();
return result.Value;
}
}
public static FamilyRole Wife
{
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;
}
}
public readonly static FamilyRole _husband = FamilyRole.Create("زوج", 1).Value;
public static FamilyRole Husband => _husband;
public readonly static FamilyRole _wife = FamilyRole.Create("زوجة", 2).Value;
public static FamilyRole Wife => _wife;
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 Daughter => _daughter;
#endregion
}
......@@ -4,11 +4,11 @@ using Microsoft.EntityFrameworkCore.Metadata.Builders;
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();
......
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
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("Domain.Entities.Identity.UserRoles.Role", b =>
modelBuilder.Entity("Domain.Entities.Identity.UserRoles.UserRole", b =>
{
b.Property<int>("Id")
.HasColumnType("int");
......@@ -37,7 +37,7 @@ namespace Persistence.Migrations
b.HasIndex("Name")
.IsUnique();
b.ToTable("Role", (string)null);
b.ToTable("UserRole", (string)null);
});
modelBuilder.Entity("Domain.Entities.Identity.Users.DoctorUser", b =>
......@@ -763,7 +763,7 @@ namespace Persistence.Migrations
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()
.HasForeignKey("RoleId")
.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;
namespace Persistence.SeedDatabase;
public class UserRoles : ISeed<Role>
public class UserRoles : ISeed<UserRole>
{
#region CTOR DI
private readonly ClinicsDbContext _context;
......@@ -16,19 +16,19 @@ public class UserRoles : ISeed<Role>
#endregion
public async Task Seed()
{
DbSet<Role> roles = _context.Set<Role>();
DbSet<UserRole> roles = _context.Set<UserRole>();
var current = await roles.ToListAsync();
// TODO: perform deep check on all seed operations
if (current.Count != Roles.Count)
if (current.Count != UsersRoles.Count)
{
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();
}
......
namespace Persistence.SeedDatabase.AdminUser;
public interface ISeedAdminUser
public interface ISeedUsers
{
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