Skip to content

Commit

Permalink
.
Browse files Browse the repository at this point in the history
  • Loading branch information
akbaramd committed Nov 2, 2024
1 parent f7c2ec7 commit 294629e
Show file tree
Hide file tree
Showing 24 changed files with 470 additions and 49 deletions.
22 changes: 11 additions & 11 deletions Nezam.ESS/Nezam.ESS.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,25 +8,25 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="FastEndpoints" Version="5.26.0.20-beta"/>
<PackageReference Include="FastEndpoints.Security" Version="5.26.0.20-beta"/>
<PackageReference Include="FastEndpoints.Swagger" Version="5.26.0.20-beta"/>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.6"/>
<PackageReference Include="FastEndpoints" Version="5.30.0.23-beta" />
<PackageReference Include="FastEndpoints.Security" Version="5.30.0.23-beta" />
<PackageReference Include="FastEndpoints.Swagger" Version="5.30.0.23-beta" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.10" />
<PackageReference Include="PersianDateTime" Version="1.1.5082.36395" />
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.4" />
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.5" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="2.1.28"/>
<PackageReference Include="Microsoft.Data.SqlClient" Version="5.2.0-preview4.23342.2"/>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.0"/>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.0">
<PackageReference Include="Dapper" Version="2.1.35" />
<PackageReference Include="Microsoft.Data.SqlClient" Version="6.0.0-preview2.24304.8" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.10">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.0"/>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.10" />
</ItemGroup>
<ItemGroup>
<Folder Include="Data\"/>
<Folder Include="Data\" />
<Folder Include="wwwroot\uploads\documents\" />
</ItemGroup>

Expand Down
56 changes: 54 additions & 2 deletions Nezam.Modular.ESS.Identity.Application/Auth/AuthService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@ public AuthService(IConfiguration configuration)
public IUserRepository UserRepository =>
LazyServiceProvider.LazyGetRequiredService<IUserRepository>();

public async Task<AuthJwtDto> LoginAsync(AuthLoginDto authLoginDto,
public IUserVerificationTokenRepository VerificationTokenRepository =>
LazyServiceProvider.LazyGetRequiredService<IUserVerificationTokenRepository>();

public async Task<AuthJwtResult> LoginAsync(AuthLoginDto authLoginDto,
CancellationToken cancellationToken = default)
{
var user = await UserRepository.FindOneAsync(x => x.UserName.Equals(authLoginDto.Username));
Expand All @@ -48,7 +51,7 @@ public async Task<AuthJwtDto> LoginAsync(AuthLoginDto authLoginDto,
});


return new AuthJwtDto
return new AuthJwtResult
{
AccessToken = jwtToken,
UserId = user.Id
Expand All @@ -61,5 +64,54 @@ public async Task<BonyanUserDto> CurrentUserProfileAsync(CancellationToken cance

return Mapper.Map<UserEntity, BonyanUserDto>(user ?? throw new InvalidOperationException());
}

public async Task<AuhForgetPasswordResult> ForgetPasswordAsync(AuhForgetPasswordDto forgetPasswordDto,
CancellationToken cancellationToken = default)
{
var user = await UserRepository.FindOneAsync(x => x.UserName.Equals(forgetPasswordDto.Username));

if (user == null)
{
throw new Exception("user not found");
}

var res = user.GenerateVerificationToken(UserVerificationTokenType.ForgetPassword);

await UserRepository.UpdateAsync(user, true);

return new AuhForgetPasswordResult()
{
VerificationToken = res.Token,
VerificationTokenType = res.Type
};
}

public async Task ResetPasswordAsync(AuthResetPasswordDto authResetPassword,
CancellationToken cancellationToken = default)
{
var token = await VerificationTokenRepository.FindOneAsync(x =>
x.Token.Equals(authResetPassword.VerificationToken));
if (token == null)
{
throw new Exception("token not found");
}

var user = token.User;
if (user == null)
{
throw new Exception("user not found");
}

if (authResetPassword.Password != authResetPassword.ConfirmPassword)
{
throw new Exception("password is incorrect");
}

user.SetPassword(authResetPassword.Password);

var res = user.RemoveVerificationToken(token);

await UserRepository.UpdateAsync(user, true);
}
}
}
21 changes: 20 additions & 1 deletion Nezam.Modular.ESS.Identity.Application/Auth/Dto/AuthLoginDto.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Bonyan.UserManagement.Domain.ValueObjects;
using Nezam.Modular.ESS.Identity.Domain.User;

namespace Nezam.Modular.ESS.Identity.Application.Auth.Dto;

Expand All @@ -7,7 +8,25 @@ public class AuthLoginDto
public string Username { get; set; }
public string Password { get; set; }
}
public class AuthJwtDto

public class AuhForgetPasswordDto
{
public string Username { get; set; }
}
public class AuhForgetPasswordResult
{
public string VerificationToken { get; set; }
public UserVerificationTokenType VerificationTokenType { get; set; }
}

public class AuthResetPasswordDto
{
public string VerificationToken { get; set; }
public string Password { get; set; }
public string ConfirmPassword { get; set; }
}

public class AuthJwtResult
{
public string AccessToken { get; set; }
public UserId UserId { get; set; }
Expand Down
8 changes: 7 additions & 1 deletion Nezam.Modular.ESS.Identity.Application/Auth/IAuthService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,16 @@ namespace Nezam.Modular.ESS.Identity.Application.Auth;

public interface IAuthService : IApplicationService
{
public Task<AuthJwtDto>
public Task<AuthJwtResult>
LoginAsync(AuthLoginDto authLoginDto,CancellationToken cancellationToken = default);


public Task<BonyanUserDto>
CurrentUserProfileAsync(CancellationToken cancellationToken = default);

public Task<AuhForgetPasswordResult>
ForgetPasswordAsync(AuhForgetPasswordDto forgetPasswordDto,CancellationToken cancellationToken = default);

public Task
ResetPasswordAsync(AuthResetPasswordDto authResetPassword,CancellationToken cancellationToken = default);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
using System.Data.SqlClient;
using System.Threading;
using System.Threading.Tasks;
using Bonyan.AspNetCore.Job;
using Dapper;
using Microsoft.Extensions.Logging;
using Nezam.Modular.ESS.Identity.Domain.User;
using Nezam.Modular.ESS.Identity.Domain.Employer;
using Bonyan.Layer.Domain.ValueObjects;
using Bonyan.UnitOfWork;
using Bonyan.UserManagement.Domain.Enumerations;
using Bonyan.UserManagement.Domain.ValueObjects;
using Microsoft.Data.SqlClient;
using Nezam.Modular.ESS.Identity.Domain.Employer;
using Nezam.Modular.ESS.Identity.Domain.Roles;

namespace Nezam.Modular.ESS.Identity.Application.Employers.Jobs
{
public class EmployerSynchronizerJob : IJob
{
private readonly IEmployerRepository _employerRepository;
private readonly IUserRepository _userRepository;
private readonly IRoleRepository _roleRepository;
private readonly IUnitOfWorkManager _workManager;
private readonly ILogger<EmployerSynchronizerJob> _logger;

public EmployerSynchronizerJob(
IEmployerRepository employerRepository,
IUserRepository userRepository,
IUnitOfWorkManager workManager,
ILogger<EmployerSynchronizerJob> logger, IRoleRepository roleRepository)
{
_employerRepository = employerRepository;
_userRepository = userRepository;
_workManager = workManager;
_logger = logger;
_roleRepository = roleRepository;
}

[UnitOfWork]
public async Task ExecuteAsync(CancellationToken cancellationToken = new CancellationToken())
{
var enginerRole = await _roleRepository.FindOneAsync(x => x.Name.Equals("employer"));

if (enginerRole==null)
{
enginerRole = new RoleEntity(RoleId.CreateNew(), "employer", "Employer");
await _roleRepository.AddAsync(enginerRole);
}

// Connection string to the database
const string connectionString =
"Data Source=85.185.6.4;Initial Catalog=map;User ID=new_site_user;Password=111qqqAAAn;Trust Server Certificate=True;";

await using (var connection = new SqlConnection(connectionString))
{
// Query all employers from tbl_employers
var employers = await connection.QueryAsync<KarbaranDataDto>(
@$"select
tbl_karbaran.kname as UserName ,
tbl_karbaran.pwd as Password ,
tbl_karbaran.comment as FullName
from tbl_karbaran where is_personel = 1");

int processedCount = 0;
var employerDtos = employers.ToList();
var count = employerDtos.Count();
foreach (var employerDto in employerDtos)
{
var username =
employerDto.UserName;

if (username == null)
{
_logger.LogWarning(
"Employer with Username: {username} has a null Username and will be skipped.",
employerDto.UserName);
continue;
}

try
{
// Check if the user already exists based on registration number or unique field
var existingUser =
await _userRepository.FindOneAsync(x => x.UserName == username);

UserEntity userEntity;
if (existingUser == null)
{
// Create a new user if not exists
userEntity = new UserEntity(UserId.CreateNew(), username);
userEntity.SetPassword(employerDto.Password is { Length: >= 3 }
? employerDto.Password
: employerDto.UserName);
userEntity.ChangeStatus(UserStatus.PendingApproval);
userEntity.TryAssignRole(enginerRole);
await _userRepository.AddAsync(userEntity,true);
}
else
{
userEntity = existingUser;
userEntity.SetPassword(employerDto.Password is { Length: >= 3 }
? employerDto.Password
: employerDto?.UserName ?? string.Empty);

userEntity.TryAssignRole(enginerRole);
await _userRepository.UpdateAsync(userEntity,true);
}

// Check if the employer entity already exists
var existingEmployer = await _employerRepository.FindOneAsync(x => x.UserId == userEntity.Id);
if (existingEmployer == null)
{
// Create and add a new employer entity
var newEmployer = new EmployerEntity(EmployerId.CreateNew(), userEntity, employerDto?.FullName,
string.Empty);
await _employerRepository.AddAsync(newEmployer,true);
}

processedCount++;

_logger.LogInformation("Processed {processedCount} employers from {count}.", processedCount, count);
}
catch (Exception e)
{
_logger.LogError(e, "An error occurred while processing employer with OzviyatNo {OzviyatNo}.",
employerDto.UserName);
}
}

_logger.LogInformation("Synchronization completed. Total processed: {TotalCount}", processedCount);
}
}
}

// DTO for Dapper query
public class KarbaranDataDto
{
public string? UserName { get; set; }
public string? Password { get; set; }
public string? FullName { get; set; }

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ public EngineerSynchronizerJob(
_roleRepository = roleRepository;
}

[UnitOfWork]
public async Task ExecuteAsync(CancellationToken cancellationToken = new CancellationToken())
{
var enginerRole = await _roleRepository.FindOneAsync(x => x.Name.Equals("engineer"));
Expand All @@ -48,13 +49,13 @@ public EngineerSynchronizerJob(

// Connection string to the database
const string connectionString =
"Data Source=192.168.200.17;Initial Catalog=map;User ID=new_site_user;Password=111qqqAAAn;Trust Server Certificate=True;";
"Data Source=85.185.6.4;Initial Catalog=map;User ID=new_site_user;Password=111qqqAAAn;Trust Server Certificate=True;";

await using (var connection = new SqlConnection(connectionString))
{
// Query all engineers from tbl_engineers
var engineers = await connection.QueryAsync<EngineerDto>(
@$"SELECT
@$"SELECT Top 1000
id AS Id,
name AS Name,
fname AS Fname,
Expand Down Expand Up @@ -84,7 +85,6 @@ FROM tbl_engineers
continue;
}

using var uow = _workManager.Begin();
try
{
// Check if the user already exists based on registration number or unique field
Expand Down Expand Up @@ -132,7 +132,6 @@ FROM tbl_engineers
await _engineerRepository.AddAsync(newEngineer,true);
}

await uow.CompleteAsync(cancellationToken);
processedCount++;

_logger.LogInformation("Processed {processedCount} engineers from {count}.", processedCount, count);
Expand All @@ -141,7 +140,6 @@ FROM tbl_engineers
{
_logger.LogError(e, "An error occurred while processing engineer with OzviyatNo {OzviyatNo}.",
engineerDto.OzviyatNo);
await uow.RollbackAsync(cancellationToken);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Bonyan.AspNetCore.Job" Version="1.1.2-pre6" />
<PackageReference Include="Bonyan.Layer.Application" Version="1.1.2-pre6" />
<PackageReference Include="Bonyan.UserManagement.Application" Version="1.1.2-pre6" />
<PackageReference Include="Bonyan.AspNetCore.Job" Version="1.1.2-pre7" />
<PackageReference Include="Bonyan.Layer.Application" Version="1.1.2-pre7" />
<PackageReference Include="Bonyan.UserManagement.Application" Version="1.1.2-pre7" />
<PackageReference Include="Dapper" Version="2.1.35" />
<PackageReference Include="Microsoft.Data.SqlClient" Version="5.2.2" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="7.1.2" />
<PackageReference Include="FastEndpoints.Security" Version="5.30.0.22-beta" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.1.2" />
<PackageReference Include="FastEndpoints.Security" Version="5.30.0.23-beta" />
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using Bonyan.UserManagement.Application;
using Microsoft.Extensions.DependencyInjection;
using Nezam.Modular.ESS.Identity.Application.Auth;
using Nezam.Modular.ESS.Identity.Application.Employers.Jobs;
using Nezam.Modular.ESS.Identity.Application.Engineers.Jobs;
using Nezam.Modular.ESS.Identity.Domain;
using Nezam.Modular.ESS.Identity.Domain.User;
Expand All @@ -24,7 +25,8 @@ public override Task OnConfigureAsync(ServiceConfigurationContext context)

context.Services.Configure<BonyanAutoMapperOptions>(c => { c.AddProfile<AuthProfile>(); });

context.AddJob<EngineerSynchronizerJob>();
// context.AddJob<EngineerSynchronizerJob>();
context.AddJob<EmployerSynchronizerJob>();

return base.OnConfigureAsync(context);
}
Expand Down
Loading

0 comments on commit 294629e

Please sign in to comment.