Skip to content

Commit

Permalink
feat(Migrations): Complete Migrations (#23)
Browse files Browse the repository at this point in the history
* first commit

* Add initial data.

* Complete & Fix Migrations project.

* add permissions.

---------

Co-authored-by: sadq <[email protected]>
  • Loading branch information
msmahdinejad and SwimmingRieux authored Aug 19, 2024
1 parent fba7e29 commit b90c915
Show file tree
Hide file tree
Showing 14 changed files with 137 additions and 57 deletions.
1 change: 0 additions & 1 deletion RelationAnalysis.Migrations/.env.example

This file was deleted.

38 changes: 0 additions & 38 deletions RelationAnalysis.Migrations/ConsoleStartup.cs

This file was deleted.

79 changes: 79 additions & 0 deletions RelationAnalysis.Migrations/InitialRecordsCreator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
using Microsoft.Extensions.Configuration;
using RelationshipAnalysis.Context;
using RelationshipAnalysis.Models.Auth;
using RelationshipAnalysis.Services.UserPanelServices.Abstraction.AuthServices;

namespace RelationAnalysis.Migrations;

public class InitialRecordsCreator(ApplicationDbContext context, IConfiguration configuration)
{
public async Task AddInitialRecords()
{
var roles = new List<Role>()
{
new Role()
{
Name = "Admin",
Permissions =
"'[\"/api/Access/GetPermissions\",\"/api/Admin/GetUser/{id}\",\"/api/Admin/GetAllUser\",\"/api/Admin/GetAllRoles\",\"/api/Admin/UpdateUser/{id}\",\"/api/Admin/UpdatePassword/{id}\",\"/api/Admin/DeleteUser/{id}\",\"/api/Admin/CreateUser\",\"/api/Admin/UpdateRoles/{id}\",\"/api/Auth/Login\", \"/api/User/GetUser\",\"/api/User/UpdateUser\",\"/api/User/UpdatePassword\",\"/api/User/Logout\"]'",
Id = 1
},
new Role()
{
Name = "DataAdmin",
Permissions =
"'[\"/api/Access/GetPermissions\",\"/api/Auth/Login\",\"/api/User/GetUser\",\"/api/User/UpdateUser\",\"/api/User/UpdatePassword\",\"/api/User/Logout\"]'",
Id = 2
},
new Role()
{
Name = "DataAnalyst",
Permissions =
"'[\"/api/Access/GetPermissions\",\"/api/Auth/Login\",\"/api/User/GetUser\",\"/api/User/UpdateUser\",\"/api/User/UpdatePassword\",\"/api/User/Logout\"]'",
Id = 3
}
};
var userRoles = new List<UserRole>()
{
new UserRole()
{
UserId = 1,
RoleId = 1
},
new UserRole()
{
UserId = 1,
RoleId = 2
},
new UserRole()
{
UserId = 1,
RoleId = 3
}
};
var users = new List<User>()
{
new User()
{
Username = "admin",
PasswordHash = new CustomPasswordHasher()
.HashPassword(configuration.GetValue<string>("DefaultPassword")),
FirstName = "FirstName",
LastName = "LastName",
Email = "[email protected]",
Id = 1,
}
};
try
{
await context.Roles.AddRangeAsync(roles);
await context.Users.AddRangeAsync(users);
await context.UserRoles.AddRangeAsync(userRoles);
await context.SaveChangesAsync();
}
catch
{
Console.WriteLine("Data already exists!");
}
}
}
44 changes: 34 additions & 10 deletions RelationAnalysis.Migrations/Program.cs
Original file line number Diff line number Diff line change
@@ -1,24 +1,48 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using DotNetEnv;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using RelationshipAnalysis.Context;

namespace RelationAnalysis.Migrations
{
class Program
{
static void Main(string[] args)
static async Task Main(string[] args)
{
Console.WriteLine("Applying migrations");
var webHost = new WebHostBuilder()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<ConsoleStartup>()
Console.WriteLine("Run console app!");


var host = Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, config) =>
{
config.AddJsonFile("appsettings.json");
config.AddEnvironmentVariables();
})
.ConfigureServices((context, services) =>
{
var configuration = context.Configuration;
var connectionString = configuration.GetValue<string>("CONNECTION_STRING");

services.AddDbContext<ApplicationDbContext>(options =>
options.UseNpgsql(connectionString));

services.AddTransient<InitialRecordsCreator>();
})
.Build();

using (var context = (ApplicationDbContext) webHost.Services.GetService(typeof(ApplicationDbContext)))
var configuration = host.Services.GetRequiredService<IConfiguration>();
Console.WriteLine(configuration.GetValue<string>("CONNECTION_STRING"));

using (var scope = host.Services.CreateScope())
{
context.Database.Migrate();
var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
await dbContext.Database.MigrateAsync();

var myService = scope.ServiceProvider.GetRequiredService<InitialRecordsCreator>();
await myService.AddInitialRecords();
}

Console.WriteLine("Done");
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@
<ItemGroup>
<PackageReference Include="Dotenv" Version="0.0.1.1" />
<PackageReference Include="DotNetEnv" Version="3.1.0" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
</ItemGroup>

<ItemGroup>
Expand All @@ -25,4 +28,10 @@
<ProjectReference Include="..\RelationshipAnalysis\RelationshipAnalysis.csproj" />
</ItemGroup>

<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>

</Project>
3 changes: 3 additions & 0 deletions RelationAnalysis.Migrations/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"DefaultPassword": "admin"
}
2 changes: 1 addition & 1 deletion RelationshipAnalysis/Dto/CreateUserDto.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ public class CreateUserDto
[Required(ErrorMessageResourceName = "PasswordRequired", ErrorMessageResourceType = typeof(Resources))]
[RegularExpression(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$",
ErrorMessageResourceName = "InvalidPasswordMessage", ErrorMessageResourceType = typeof(Resources))]
public string Password { get; set; }
public string? Password { get; set; }

[Required] public string FirstName { get; set; }

Expand Down
2 changes: 1 addition & 1 deletion RelationshipAnalysis/Dto/LoginDto.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@ public class LoginDto
{
[Required] public string Username { get; set; }

[Required] public string Password { get; set; }
[Required] public string? Password { get; set; }
}
4 changes: 2 additions & 2 deletions RelationshipAnalysis/Dto/UserPasswordInfoDto.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ namespace RelationshipAnalysis.Dto;
public class UserPasswordInfoDto
{
[Required(ErrorMessageResourceName = "OldPasswordRequired", ErrorMessageResourceType = typeof(Resources))]
public string OldPassword { get; set; }
public string? OldPassword { get; set; }

[Required(ErrorMessageResourceName = "NewPasswordRequired", ErrorMessageResourceType = typeof(Resources))]
[RegularExpression("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*\\W)(?!.* ).{8,}$",
ErrorMessageResourceName = "InvalidPasswordMessage", ErrorMessageResourceType = typeof(Resources))]
public string NewPassword { get; set; }
public string? NewPassword { get; set; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@

public interface IPasswordHasher
{
string HashPassword(string input);
string HashPassword(string? input);
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@

public interface IPasswordVerifier
{
bool VerifyPasswordHash(string password, string storedHash);
bool VerifyPasswordHash(string? password, string storedHash);
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ namespace RelationshipAnalysis.Services.UserPanelServices.Abstraction.AuthServic

public class CustomPasswordHasher : IPasswordHasher
{
public string HashPassword(string input)
public string HashPassword(string? input)
{
var hashBytes = SHA256.HashData(Encoding.UTF8.GetBytes(input));
var hash = BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ namespace RelationshipAnalysis.Services.UserPanelServices.Abstraction.AuthServic

public class PasswordVerifier(IPasswordHasher passwordHasher) : IPasswordVerifier
{
public bool VerifyPasswordHash(string password, string storedHash)
public bool VerifyPasswordHash(string? password, string storedHash)
{
return passwordHasher.HashPassword(password) == storedHash;
}
Expand Down
4 changes: 4 additions & 0 deletions RelationshipAnalysis/appsettings.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
{
"PasswordHash":
{
"DefaultPassword" : "admin"
},
"Jwt": {
"CookieName" : "jwt",
"Key": "kajbdiuhdqhpjQE89HBSDJIABFCIWSGF89GW3EJFBWEIUBCZNMXCJNLZDKNJKSNJKFBIGW3EASHHDUIASZGCUI",
Expand Down

0 comments on commit b90c915

Please sign in to comment.