Generator Changes at 9/27/2025 11:50:52 PM

This commit is contained in:
MeysamMoghaddam
2025-09-27 23:59:05 +03:30
parent ec6ab8258a
commit 6fd9472f2b
11 changed files with 165 additions and 1 deletions

View File

@@ -0,0 +1,5 @@
namespace CMSMicroservice.Application.Common.Interfaces;
public interface IGenerateJwtToken
{
Task<string> GenerateJwtToken(User user);
}

View File

@@ -0,0 +1,7 @@
namespace CMSMicroservice.Application.UserCQ.Queries.GetJwtToken;
public record GetJwtTokenQuery : IRequest<GetJwtTokenResponseDto>
{
//شناسه
public long Id { get; init; }
}

View File

@@ -0,0 +1,22 @@
namespace CMSMicroservice.Application.UserCQ.Queries.GetJwtToken;
public class GetJwtTokenQueryHandler : IRequestHandler<GetJwtTokenQuery, GetJwtTokenResponseDto>
{
private readonly IApplicationDbContext _context;
private readonly IGenerateJwtToken _generateJwt;
public GetJwtTokenQueryHandler(IApplicationDbContext context, IGenerateJwtToken generateJwt)
{
_context = context;
_generateJwt = generateJwt;
}
public async Task<GetJwtTokenResponseDto> Handle(GetJwtTokenQuery request, CancellationToken cancellationToken)
{
var user = await _context.Users
.FirstOrDefaultAsync(x => x.Id == request.Id, cancellationToken) ?? throw new NotFoundException(nameof(User), request.Id);
return new GetJwtTokenResponseDto()
{
Token = await _generateJwt.GenerateJwtToken(user),
};
}
}

View File

@@ -0,0 +1,16 @@
namespace CMSMicroservice.Application.UserCQ.Queries.GetJwtToken;
public class GetJwtTokenQueryValidator : AbstractValidator<GetJwtTokenQuery>
{
public GetJwtTokenQueryValidator()
{
RuleFor(model => model.Id)
.NotNull();
}
public Func<object, string, Task<IEnumerable<string>>> ValidateValue => async (model, propertyName) =>
{
var result = await ValidateAsync(ValidationContext<GetJwtTokenQuery>.CreateWithOptions((GetJwtTokenQuery)model, x => x.IncludeProperties(propertyName)));
if (result.IsValid)
return Array.Empty<string>();
return result.Errors.Select(e => e.ErrorMessage);
};
}

View File

@@ -0,0 +1,7 @@
namespace CMSMicroservice.Application.UserCQ.Queries.GetJwtToken;
public class GetJwtTokenResponseDto
{
//توکن
public string Token { get; set; }
}

View File

@@ -8,6 +8,7 @@ using Microsoft.AspNetCore.Http;
using System.Diagnostics;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using CMSMicroservice.Infrastructure.Services;
namespace Microsoft.Extensions.DependencyInjection;
@@ -17,6 +18,7 @@ public static class ConfigureServices
{
services.AddScoped<AuditableEntitySaveChangesInterceptor>();
services.AddScoped<ApplicationDbContextInitialiser>();
services.AddScoped<IGenerateJwtToken, GenerateJwtTokenService>();
services.AddScoped<IApplicationDbContext>(p => p.GetRequiredService<ApplicationDbContext>());
if (configuration.GetValue<bool>("UseInMemoryDatabase"))
{

View File

@@ -0,0 +1,67 @@
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace CMSMicroservice.Infrastructure.Services;
public class GenerateJwtTokenService : IGenerateJwtToken
{
private readonly IConfiguration _configuration;
public GenerateJwtTokenService(IConfiguration configuration)
{
_configuration = configuration;
}
public async Task<string> GenerateJwtToken(User user)
{
var lastModified = user.LastModified ?? user.Created;
var claims = new List<Claim>
{
new(ClaimTypes.NameIdentifier, user.Id.ToString()),
new(ClaimTypes.MobilePhone, user.Mobile),
new("ReferralCode", user.ReferralCode),
new(ClaimTypes.Name, $"{user.FirstName} {user.LastName}")
};
if (!string.IsNullOrWhiteSpace(user.FirstName))
claims.Add(new Claim("FirstName", user.FirstName));
if (!string.IsNullOrWhiteSpace(user.LastName))
claims.Add(new Claim("LastName", user.LastName));
if (user.UserRoles != null && user.UserRoles.Any())
{
foreach (var userRole in user.UserRoles)
{
claims.Add(new Claim(ClaimTypes.Role, userRole.Role.Name));
}
if (user.UserRoles.Max(x => x.Created) > lastModified)
lastModified = user.UserRoles.Max(x => x.Created);
if (user.UserRoles.Where(x => x.LastModified != null).Max(x => x.LastModified) > lastModified)
lastModified = user.UserRoles.Where(x => x.LastModified != null).Max(x => x.Created);
}
claims.Add(new Claim("LastModified", lastModified.ToString()));
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JwtSecurityKey"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var expiry = DateTime.Now.AddDays(Convert.ToInt32(_configuration["JwtExpiryInDays"]));
var token = new JwtSecurityToken(
_configuration["JwtIssuer"],
_configuration["JwtAudience"],
claims,
expires: expiry,
signingCredentials: creds
);
var _token = new JwtSecurityTokenHandler().WriteToken(token);
return _token;
}
}

View File

@@ -4,7 +4,7 @@
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<Version>0.0.112</Version>
<Version>0.0.113</Version>
<DebugType>None</DebugType>
<DebugSymbols>False</DebugSymbols>
<GeneratePackageOnBuild>False</GeneratePackageOnBuild>

View File

@@ -43,6 +43,12 @@ service UserContract
};
};
rpc GetJwtToken(GetJwtTokenRequest) returns (GetJwtTokenResponse){
option (google.api.http) = {
get: "/GetJwtToken"
};
};
}
message CreateNewUserRequest
{
@@ -123,3 +129,11 @@ message GetAllUserByFilterResponseModel
bool is_mobile_verified = 9;
google.protobuf.Timestamp mobile_verified_at = 10;
}
message GetJwtTokenRequest
{
int64 id = 1;
}
message GetJwtTokenResponse
{
string token = 1;
}

View File

@@ -0,0 +1,19 @@
using FluentValidation;
using CMSMicroservice.Protobuf.Protos.User;
namespace CMSMicroservice.Protobuf.Validator.User;
public class GetJwtTokenRequestValidator : AbstractValidator<GetJwtTokenRequest>
{
public GetJwtTokenRequestValidator()
{
RuleFor(model => model.Id)
.NotNull();
}
public Func<object, string, Task<IEnumerable<string>>> ValidateValue => async (model, propertyName) =>
{
var result = await ValidateAsync(ValidationContext<GetJwtTokenRequest>.CreateWithOptions((GetJwtTokenRequest)model, x => x.IncludeProperties(propertyName)));
if (result.IsValid)
return Array.Empty<string>();
return result.Errors.Select(e => e.ErrorMessage);
};
}

View File

@@ -5,6 +5,7 @@ using CMSMicroservice.Application.UserCQ.Commands.UpdateUser;
using CMSMicroservice.Application.UserCQ.Commands.DeleteUser;
using CMSMicroservice.Application.UserCQ.Queries.GetUser;
using CMSMicroservice.Application.UserCQ.Queries.GetAllUserByFilter;
using CMSMicroservice.Application.UserCQ.Queries.GetJwtToken;
namespace CMSMicroservice.WebApi.Services;
public class UserService : UserContract.UserContractBase
{
@@ -34,4 +35,8 @@ public class UserService : UserContract.UserContractBase
{
return await _dispatchRequestToCQRS.Handle<GetAllUserByFilterRequest, GetAllUserByFilterQuery, GetAllUserByFilterResponse>(request, context);
}
public override async Task<GetJwtTokenResponse> GetJwtToken(GetJwtTokenRequest request, ServerCallContext context)
{
return await _dispatchRequestToCQRS.Handle<GetJwtTokenRequest, GetJwtTokenQuery, GetJwtTokenResponse>(request, context);
}
}