From 10161d5835a86f8f569b82f00b3ceeeee8c6fce2 Mon Sep 17 00:00:00 2001 From: Ali Yousefi Date: Mon, 4 Dec 2023 18:11:38 +0330 Subject: [PATCH 1/2] Refactor, Use Serilog --- .../Database/Contexts/IdentityContext.cs | 12 --- .../Database/Entities/.gitkeep | 0 ...vices.IdentityMicroservice.Database.csproj | 2 +- ...ervices.IdentityMicroservice.Domain.csproj | 5 +- .../Attributes/ApplicationInitializeCheck.cs | 24 ++++-- ...InternalTokenGeneratorBackgroundService.cs | 55 +++++++++++++ .../Helpers/AppUnitOfWork.cs | 46 +++++++---- .../Helpers/ClaimManager.cs | 2 +- .../Helpers/IdentityHelper.cs | 78 ++++++++++++++----- .../Interfaces/IAppUnitOfWork.cs | 10 ++- .../DatabaseBuilder.cs | 12 +-- ...rvices.IdentityMicroservice.StartUp.csproj | 2 +- .../Controllers/AuthenticationController.cs | 63 ++++----------- ...ervices.IdentityMicroservice.WebApi.csproj | 3 + .../Program.cs | 47 ++++++----- 15 files changed, 217 insertions(+), 144 deletions(-) delete mode 100644 src/CSharp/EasyMicroservices.IdentityMicroservice.Database/Database/Entities/.gitkeep create mode 100644 src/CSharp/EasyMicroservices.IdentityMicroservice.Logics/BackgroundServices/InternalTokenGeneratorBackgroundService.cs diff --git a/src/CSharp/EasyMicroservices.IdentityMicroservice.Database/Database/Contexts/IdentityContext.cs b/src/CSharp/EasyMicroservices.IdentityMicroservice.Database/Database/Contexts/IdentityContext.cs index eae4f96..7d157d8 100644 --- a/src/CSharp/EasyMicroservices.IdentityMicroservice.Database/Database/Contexts/IdentityContext.cs +++ b/src/CSharp/EasyMicroservices.IdentityMicroservice.Database/Database/Contexts/IdentityContext.cs @@ -7,27 +7,15 @@ namespace EasyMicroservices.IdentityMicroservice.Database.Contexts { public class IdentityContext : RelationalCoreContext { - IEntityFrameworkCoreDatabaseBuilder _builder; public IdentityContext(IEntityFrameworkCoreDatabaseBuilder builder) : base(builder) { } //public DbSet Identity { get; set; } - - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - if (_builder != null) - _builder.OnConfiguring(optionsBuilder); - base.OnConfiguring(optionsBuilder); - } - protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); - - - } } } \ No newline at end of file diff --git a/src/CSharp/EasyMicroservices.IdentityMicroservice.Database/Database/Entities/.gitkeep b/src/CSharp/EasyMicroservices.IdentityMicroservice.Database/Database/Entities/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/src/CSharp/EasyMicroservices.IdentityMicroservice.Database/EasyMicroservices.IdentityMicroservice.Database.csproj b/src/CSharp/EasyMicroservices.IdentityMicroservice.Database/EasyMicroservices.IdentityMicroservice.Database.csproj index 3511202..27139f8 100644 --- a/src/CSharp/EasyMicroservices.IdentityMicroservice.Database/EasyMicroservices.IdentityMicroservice.Database.csproj +++ b/src/CSharp/EasyMicroservices.IdentityMicroservice.Database/EasyMicroservices.IdentityMicroservice.Database.csproj @@ -11,7 +11,7 @@ - + diff --git a/src/CSharp/EasyMicroservices.IdentityMicroservice.Domain/EasyMicroservices.IdentityMicroservice.Domain.csproj b/src/CSharp/EasyMicroservices.IdentityMicroservice.Domain/EasyMicroservices.IdentityMicroservice.Domain.csproj index fb3adec..82eb396 100644 --- a/src/CSharp/EasyMicroservices.IdentityMicroservice.Domain/EasyMicroservices.IdentityMicroservice.Domain.csproj +++ b/src/CSharp/EasyMicroservices.IdentityMicroservice.Domain/EasyMicroservices.IdentityMicroservice.Domain.csproj @@ -11,7 +11,8 @@ - - + + + diff --git a/src/CSharp/EasyMicroservices.IdentityMicroservice.Logics/Attributes/ApplicationInitializeCheck.cs b/src/CSharp/EasyMicroservices.IdentityMicroservice.Logics/Attributes/ApplicationInitializeCheck.cs index ccb5c82..4a35b9e 100644 --- a/src/CSharp/EasyMicroservices.IdentityMicroservice.Logics/Attributes/ApplicationInitializeCheck.cs +++ b/src/CSharp/EasyMicroservices.IdentityMicroservice.Logics/Attributes/ApplicationInitializeCheck.cs @@ -1,11 +1,9 @@ -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc.Filters; +using EasyMicroservices.ServiceContracts; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; -using System; -using System.Collections.Generic; +using Microsoft.AspNetCore.Mvc.Filters; using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Text.Json; namespace EasyMicroservices.IdentityMicroservice.Attributes { @@ -24,16 +22,26 @@ public void OnAuthorization(AuthorizationFilterContext context) if (!user.Identity.IsAuthenticated) { - context.Result = new UnauthorizedResult(); + context.Result = GetErrorContent(); return; } var hasClaims = ClaimTypes.All(o => user.Claims.Any(x => x.Type == o)); if (!hasClaims) - context.Result = new UnauthorizedResult(); + context.Result = GetErrorContent(); return; } + + ContentResult GetErrorContent() + { + var msg = (MessageContract)(FailedReasonType.SessionAccessDenied, "Please call appinit!"); + return new ContentResult() + { + Content = JsonSerializer.Serialize(msg), + ContentType = "application/json" + }; + } } } diff --git a/src/CSharp/EasyMicroservices.IdentityMicroservice.Logics/BackgroundServices/InternalTokenGeneratorBackgroundService.cs b/src/CSharp/EasyMicroservices.IdentityMicroservice.Logics/BackgroundServices/InternalTokenGeneratorBackgroundService.cs new file mode 100644 index 0000000..5f1e609 --- /dev/null +++ b/src/CSharp/EasyMicroservices.IdentityMicroservice.Logics/BackgroundServices/InternalTokenGeneratorBackgroundService.cs @@ -0,0 +1,55 @@ +using EasyMicroservices.IdentityMicroservice.Helpers; +using EasyMicroservices.IdentityMicroservice.Interfaces; +using EasyMicroservices.Logger.Interfaces; +using Microsoft.Extensions.Hosting; +using System; +using System.Threading; +using System.Threading.Tasks; + +namespace EasyMicroservices.IdentityMicroservice.BackgroundServices; +public class InternalTokenGeneratorBackgroundService : IHostedService, IDisposable +{ + private Timer _timer = null; + readonly IAppUnitOfWork _unitOfWork; + public InternalTokenGeneratorBackgroundService(IAppUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + } + + public Task StartAsync(CancellationToken stoppingToken) + { + _timer = new Timer(DoWork, null, TimeSpan.Zero, + TimeSpan.FromHours(1)); + + return Task.CompletedTask; + } + + private void DoWork(object state) + { + _ = Task.Run(async () => + { + var logger = _unitOfWork.GetLogger(); + try + { + logger.Debug("Try login..."); + AppUnitOfWork.Token = await _unitOfWork.GetIdentityHelper().GetFullAccessPersonalAccessToken(); + logger.Debug($"Login success {AppUnitOfWork.Token}"); + } + catch (Exception ex) + { + logger.Error(ex); + } + }); + } + + public Task StopAsync(CancellationToken stoppingToken) + { + _timer?.Change(Timeout.Infinite, 0); + return Task.CompletedTask; + } + + public void Dispose() + { + _timer?.Dispose(); + } +} \ No newline at end of file diff --git a/src/CSharp/EasyMicroservices.IdentityMicroservice.Logics/Helpers/AppUnitOfWork.cs b/src/CSharp/EasyMicroservices.IdentityMicroservice.Logics/Helpers/AppUnitOfWork.cs index 647ef4f..756702a 100644 --- a/src/CSharp/EasyMicroservices.IdentityMicroservice.Logics/Helpers/AppUnitOfWork.cs +++ b/src/CSharp/EasyMicroservices.IdentityMicroservice.Logics/Helpers/AppUnitOfWork.cs @@ -4,12 +4,13 @@ using EasyMicroservices.Cores.AspEntityFrameworkCoreApi; using EasyMicroservices.Cores.Clients; using EasyMicroservices.IdentityMicroservice.Interfaces; -using EasyMicroservices.IdentityMicroservice.Services; +using EasyMicroservices.Logger.Interfaces; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System; -using System.Linq; +using System.Net.Http; +using System.Text; namespace EasyMicroservices.IdentityMicroservice.Helpers { @@ -28,12 +29,12 @@ public IConfiguration GetConfiguration() public IdentityHelper GetIdentityHelper() { - return new IdentityHelper(GetConfiguration(), GetIJWTManager()); + return _service.GetService(); } public IJWTManager GetIJWTManager() { - return new JWTManager(GetConfiguration()); + return _service.GetService(); } public ClaimManager GetClaimManager() @@ -46,29 +47,44 @@ string GetValue(string key) return GetConfiguration().GetValue(key); } - T SetToken(HttpContext httpContext, T coreSwaggerClient) + public IHttpContextAccessor GetHttpContextAccessor() + { + return _service.GetService(); + } + + static HttpClient CurrentHttpClient { get; set; } = new HttpClient(); + + public static string Token = ""; + T InternalLogin(T client) where T : CoreSwaggerClientBase { - if (httpContext.Request.Headers.Authorization.Count > 0) - { - coreSwaggerClient.SetBearerToken(httpContext.Request.Headers.Authorization.First()); - } - return coreSwaggerClient; + client.SetBearerToken(Token); + return client; } public LanguageClient GetLanguageClient() { - return new LanguageClient(GetValue("RootAddresses:Contents"), new System.Net.Http.HttpClient()); + return InternalLogin(new LanguageClient(GetValue("RootAddresses:Contents"), CurrentHttpClient)); + } + + public UserClient GetUserClient() + { + return InternalLogin(new UserClient(GetValue("RootAddresses:Authentications"), CurrentHttpClient)); + } + + public RoleClient GetRoleClient() + { + return InternalLogin(new RoleClient(GetValue("RootAddresses:Authentications"), CurrentHttpClient)); } - public UserClient GetUserClient(HttpContext httpContext) + public PersonalAccessTokenClient GetPersonalAccessTokenClientClient() { - return SetToken(httpContext, new UserClient(GetValue("RootAddresses:Authentications"), new System.Net.Http.HttpClient())); + return InternalLogin(new PersonalAccessTokenClient(GetValue("RootAddresses:Authentications"), CurrentHttpClient)); } - public RoleClient GetRoleClient(HttpContext httpContext) + public ILoggerProvider GetLogger() { - return SetToken(httpContext, new RoleClient(GetValue("RootAddresses:Authentications"), new System.Net.Http.HttpClient())); + return ServiceProvider.GetService(); } } } diff --git a/src/CSharp/EasyMicroservices.IdentityMicroservice.Logics/Helpers/ClaimManager.cs b/src/CSharp/EasyMicroservices.IdentityMicroservice.Logics/Helpers/ClaimManager.cs index 317ca2d..4f3ef00 100644 --- a/src/CSharp/EasyMicroservices.IdentityMicroservice.Logics/Helpers/ClaimManager.cs +++ b/src/CSharp/EasyMicroservices.IdentityMicroservice.Logics/Helpers/ClaimManager.cs @@ -19,7 +19,7 @@ public ClaimManager(IHttpContextAccessor httpContext) _httpContext = httpContext; - var token = _httpContext.HttpContext.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last(); + var token = _httpContext.HttpContext?.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last(); if (token != null) { diff --git a/src/CSharp/EasyMicroservices.IdentityMicroservice.Logics/Helpers/IdentityHelper.cs b/src/CSharp/EasyMicroservices.IdentityMicroservice.Logics/Helpers/IdentityHelper.cs index d21d9f9..5d06097 100644 --- a/src/CSharp/EasyMicroservices.IdentityMicroservice.Logics/Helpers/IdentityHelper.cs +++ b/src/CSharp/EasyMicroservices.IdentityMicroservice.Logics/Helpers/IdentityHelper.cs @@ -4,6 +4,9 @@ using EasyMicroservices.IdentityMicroservice.Interfaces; using EasyMicroservices.ServiceContracts; using Microsoft.Extensions.Configuration; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; using System.Threading.Tasks; using FailedReasonType = EasyMicroservices.ServiceContracts.FailedReasonType; @@ -11,29 +14,23 @@ namespace EasyMicroservices.IdentityMicroservice.Helpers { public class IdentityHelper { - private readonly IConfiguration _config; - private readonly UserClient _userClient; - private readonly IJWTManager _jwtManager; - private readonly string _authRoot; + IAppUnitOfWork _appUnitOfWork; - public IdentityHelper(IConfiguration config, IJWTManager jwtManager) + public IdentityHelper(IAppUnitOfWork appUnitOfWork) { - _config = config; - _jwtManager = jwtManager; - _authRoot = _config.GetValue("RootAddresses:Authentications"); - _userClient = new(_authRoot, new System.Net.Http.HttpClient()); + _appUnitOfWork = appUnitOfWork; } public async Task> Register(Contracts.Requests.AddUserRequestContract request) { - var usersRecords = await _userClient.GetUserByUserNameAsync(new GetUserByUserNameRequestContract { Username = request.UserName.ToLower() }); - - if (usersRecords.IsSuccess) - return (ServiceContracts.FailedReasonType.Duplicate, "User already exists!"); + var client = _appUnitOfWork.GetUserClient(); + var usersRecords = await client.GetUserByUserNameAsync(new GetUserByUserNameRequestContract + { + Username = request.UserName.ToLower() + }).AsCheckedResult(x => x.Result); - _userClient.SetBearerToken(_config.GetValue("Authorization:FullAccessPAT")); - var user = await _userClient.AddAsync(new AddUserRequestContract + var user = await client.AddAsync(new AddUserRequestContract { UserName = request.UserName, Password = request.Password @@ -47,24 +44,65 @@ public async Task> Register(Contracts. public virtual async Task> Login(Contracts.Common.UserSummaryContract cred) { - var user = await _userClient.VerifyUserIdentityAsync(new Authentications.GeneratedServices.UserSummaryContract { UserName = cred.UserName, Password = cred.Password }); - if (!user.IsSuccess) - return (ServiceContracts.FailedReasonType.Incorrect, "Username or password is invalid."); //"Username or password is invalid." + var client = _appUnitOfWork.GetUserClient(); + var user = await client.VerifyUserIdentityAsync(new Authentications.GeneratedServices.UserSummaryContract + { + UserName = cred.UserName, + Password = cred.Password + }).AsCheckedResult(x => x.Result); return new LoginResponseContract { - UserId = user.Result.Id + UserId = user.Id }; } + public Task GetFullAccessPersonalAccessToken() + { + var ownerPat = _appUnitOfWork.GetConfiguration().GetValue("Authorization:FullAccessPAT"); + return GetFullAccessPersonalAccessToken(ownerPat); + } + + public async Task GetFullAccessPersonalAccessToken(string personalAccessToken) + { + var user = await _appUnitOfWork.GetUserClient().GetUserByPersonalAccessTokenAsync(new Authentications.GeneratedServices.PersonalAccessTokenRequestContract() + { + Value = personalAccessToken + }).AsCheckedResult(x => x.Result); + + var roles = await _appUnitOfWork.GetRoleClient().GetRolesByUserIdAsync(new Authentications.GeneratedServices.Int64GetIdRequestContract + { + Id = user.Id + }).AsCheckedResult(x => x.Result); + + List claims = new(); + var _claimManager = _appUnitOfWork.GetClaimManager(); + _claimManager.SetCurrentLanguage(_claimManager.CurrentLanguage, claims); + if (!_claimManager.HasId()) + { + _claimManager.SetId(user.Id, claims); + _claimManager.SetUniqueIdentity(user.UniqueIdentity, claims); + _claimManager.SetRole(roles.Select(x => new ClaimContract() + { + Name = ClaimTypes.Role, + Value = x.Name + }).ToList(), claims); + } + + var response = await _appUnitOfWork.GetIJWTManager() + .GenerateTokenWithClaims(claims) + .AsCheckedResult(); + return response.Token; + } + public virtual async Task> GenerateToken(UserClaimContract userClaim) { var loginResponse = await Login(userClaim); if (!loginResponse) return (FailedReasonType.Incorrect, "Incorrect user credential provided."); - var token = await _jwtManager.GenerateTokenWithClaims(userClaim.Claims); + var token = await _appUnitOfWork.GetIJWTManager().GenerateTokenWithClaims(userClaim.Claims); return new UserResponseContract { diff --git a/src/CSharp/EasyMicroservices.IdentityMicroservice.Logics/Interfaces/IAppUnitOfWork.cs b/src/CSharp/EasyMicroservices.IdentityMicroservice.Logics/Interfaces/IAppUnitOfWork.cs index 0c5a081..074985b 100644 --- a/src/CSharp/EasyMicroservices.IdentityMicroservice.Logics/Interfaces/IAppUnitOfWork.cs +++ b/src/CSharp/EasyMicroservices.IdentityMicroservice.Logics/Interfaces/IAppUnitOfWork.cs @@ -10,17 +10,21 @@ using EasyMicroservices.IdentityMicroservice.Helpers; using Authentications.GeneratedServices; using Contents.GeneratedServices; +using EasyMicroservices.Logger.Interfaces; namespace EasyMicroservices.IdentityMicroservice.Interfaces { public interface IAppUnitOfWork : IUnitOfWork { + public IHttpContextAccessor GetHttpContextAccessor(); public IJWTManager GetIJWTManager(); public IConfiguration GetConfiguration(); + public ILoggerProvider GetLogger(); public IdentityHelper GetIdentityHelper(); - public LanguageClient GetLanguageClient(); public ClaimManager GetClaimManager(); - public UserClient GetUserClient(HttpContext httpContext); - public RoleClient GetRoleClient(HttpContext httpContext); + public LanguageClient GetLanguageClient(); + public UserClient GetUserClient(); + public RoleClient GetRoleClient(); + public PersonalAccessTokenClient GetPersonalAccessTokenClientClient(); } } diff --git a/src/CSharp/EasyMicroservices.IdentityMicroservice.StartUp/DatabaseBuilder.cs b/src/CSharp/EasyMicroservices.IdentityMicroservice.StartUp/DatabaseBuilder.cs index 922e090..722566f 100644 --- a/src/CSharp/EasyMicroservices.IdentityMicroservice.StartUp/DatabaseBuilder.cs +++ b/src/CSharp/EasyMicroservices.IdentityMicroservice.StartUp/DatabaseBuilder.cs @@ -1,12 +1,6 @@ -using EasyMicroservices.IdentityMicroservice.Database; -using EasyMicroservices.Cores.Relational.EntityFrameworkCore.Intrerfaces; +using EasyMicroservices.Cores.Relational.EntityFrameworkCore.Intrerfaces; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace EasyMicroservices.IdentityMicroservice { @@ -20,8 +14,8 @@ public DatabaseBuilder(IConfiguration configuration) public void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { - optionsBuilder.UseInMemoryDatabase("IdentityDatabase"); - //optionsBuilder.UseSqlServer(_configuration.GetConnectionString("local")); + //optionsBuilder.UseInMemoryDatabase("IdentityDatabase"); + optionsBuilder.UseSqlServer(_configuration.GetConnectionString("local")); } } } diff --git a/src/CSharp/EasyMicroservices.IdentityMicroservice.StartUp/EasyMicroservices.IdentityMicroservice.StartUp.csproj b/src/CSharp/EasyMicroservices.IdentityMicroservice.StartUp/EasyMicroservices.IdentityMicroservice.StartUp.csproj index 6695189..5e97ac1 100644 --- a/src/CSharp/EasyMicroservices.IdentityMicroservice.StartUp/EasyMicroservices.IdentityMicroservice.StartUp.csproj +++ b/src/CSharp/EasyMicroservices.IdentityMicroservice.StartUp/EasyMicroservices.IdentityMicroservice.StartUp.csproj @@ -6,8 +6,8 @@ - + diff --git a/src/CSharp/EasyMicroservices.IdentityMicroservice.WebApi/Controllers/AuthenticationController.cs b/src/CSharp/EasyMicroservices.IdentityMicroservice.WebApi/Controllers/AuthenticationController.cs index 9a358cf..00f192d 100644 --- a/src/CSharp/EasyMicroservices.IdentityMicroservice.WebApi/Controllers/AuthenticationController.cs +++ b/src/CSharp/EasyMicroservices.IdentityMicroservice.WebApi/Controllers/AuthenticationController.cs @@ -4,11 +4,9 @@ using EasyMicroservices.IdentityMicroservice.Contracts.Common; using EasyMicroservices.IdentityMicroservice.Contracts.Requests; using EasyMicroservices.IdentityMicroservice.Contracts.Responses; -using EasyMicroservices.IdentityMicroservice.Helpers; using EasyMicroservices.IdentityMicroservice.Interfaces; using EasyMicroservices.ServiceContracts; using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System.Security.Claims; @@ -20,18 +18,11 @@ namespace EasyMicroservices.IdentityMicroservice.WebApi.Controllers [AllowAnonymous] public class AuthenticationController : ControllerBase { - private readonly IJWTManager _jwtManager; - private readonly IdentityHelper _identityHelper; private readonly IAppUnitOfWork _appUnitOfWork; - private readonly ClaimManager _claimManager; - private readonly string _authRoot; public AuthenticationController(IAppUnitOfWork appUnitOfWork) { _appUnitOfWork = appUnitOfWork; - _identityHelper = _appUnitOfWork.GetIdentityHelper(); - _jwtManager = _appUnitOfWork.GetIJWTManager(); - _claimManager = _appUnitOfWork.GetClaimManager(); } private void SetCookie(string key, string value) @@ -54,7 +45,7 @@ private void SetCookie(string key, string value) [HttpPost] public async Task VerifyUserName(VerifyUserRequestContract request) { - var _userClient = _appUnitOfWork.GetUserClient(HttpContext); + var _userClient = _appUnitOfWork.GetUserClient(); var user = await _userClient.GetByIdAsync(new Authentications.GeneratedServices.Int64GetIdRequestContract { Id = request.UserId }); if (!user.IsSuccess) @@ -80,32 +71,29 @@ await _userClient.UpdateAsync(new Authentications.GeneratedServices.UserContract } [HttpPost] - [ApplicationInitializeCheck] public async Task> Register(Contracts.Requests.AddUserRequestContract request) { + var _identityHelper = _appUnitOfWork.GetIdentityHelper(); return await _identityHelper.Register(request); } [HttpPost] - [ApplicationInitializeCheck] public async Task> Login(Contracts.Common.UserSummaryContract request) { + var _identityHelper = _appUnitOfWork.GetIdentityHelper(); var response = await _identityHelper.Login(request); if (!response.IsSuccess) return response.ToContract(); - UserClient _userClient = _appUnitOfWork.GetUserClient(HttpContext); - - _userClient.SetBearerToken(_appUnitOfWork.GetConfiguration().GetValue("Authorization:FullAccessPAT")); - - var user = await _userClient.GetByIdAsync(new Authentications.GeneratedServices.Int64GetIdRequestContract { Id = response.Result.UserId }).AsCheckedResult(x => x.Result); - var roles = await _appUnitOfWork.GetRoleClient(HttpContext).GetRolesByUserIdAsync(new Authentications.GeneratedServices.Int64GetIdRequestContract + var user = await _appUnitOfWork.GetUserClient().GetByIdAsync(new Authentications.GeneratedServices.Int64GetIdRequestContract { Id = response.Result.UserId }).AsCheckedResult(x => x.Result); + var roles = await _appUnitOfWork.GetRoleClient().GetRolesByUserIdAsync(new Authentications.GeneratedServices.Int64GetIdRequestContract { Id = response.Result.UserId }).AsCheckedResult(x => x.Result); List claims = new(); + var _claimManager = _appUnitOfWork.GetClaimManager(); _claimManager.SetCurrentLanguage(_claimManager.CurrentLanguage, claims); if (!_claimManager.HasId()) { @@ -133,6 +121,7 @@ public async Task> Login(Contrac [ApplicationInitializeCheck] public async Task> GenerateToken(UserClaimContract request) { + var _identityHelper = _appUnitOfWork.GetIdentityHelper(); var response = await _identityHelper.GenerateToken(request); return response; @@ -142,10 +131,11 @@ public async Task> GenerateToken(UserClaim [CustomAuthorizeCheck] public async Task> RegenerateToken(RegenerateTokenContract request) { - var _userClient = _appUnitOfWork.GetUserClient(HttpContext); + var _userClient = _appUnitOfWork.GetUserClient(); _userClient.SetBearerToken(_appUnitOfWork.GetConfiguration().GetValue("Authorization:FullAccessPAT")); + var _claimManager = _appUnitOfWork.GetClaimManager(); var user = await _userClient.GetByIdAsync(new Authentications.GeneratedServices.Int64GetIdRequestContract { Id = _claimManager.Id @@ -164,6 +154,7 @@ public async Task> RegenerateToken(Regener Claims = request.Claims }; + var _identityHelper = _appUnitOfWork.GetIdentityHelper(); var response = await _identityHelper.GenerateToken(req); return new UserResponseContract @@ -188,7 +179,7 @@ public async Task> Applic return (ServiceContracts.FailedReasonType.NotFound, "Language not found."); List claims = new(); - + var _claimManager = _appUnitOfWork.GetClaimManager(); _claimManager.SetCurrentLanguage(request.Language, claims); if (_claimManager.HasId()) { @@ -206,35 +197,13 @@ public async Task> Applic [HttpPost] public async Task> LoginByPersonalAccessToken(LoginByPersonalAccessTokenRequestContract request) { - var user = await _appUnitOfWork.GetUserClient(HttpContext).GetUserByPersonalAccessTokenAsync(new Authentications.GeneratedServices.PersonalAccessTokenRequestContract() - { - Value = request.PersonalAccessToken - }).AsCheckedResult(x => x.Result); - - var roles = await _appUnitOfWork.GetRoleClient(HttpContext).GetRolesByUserIdAsync(new Authentications.GeneratedServices.Int64GetIdRequestContract - { - Id = user.Id - }).AsCheckedResult(x => x.Result); + var token = await _appUnitOfWork.GetIdentityHelper().GetFullAccessPersonalAccessToken(request.PersonalAccessToken); + SetCookie("token", token); - List claims = new(); - - _claimManager.SetCurrentLanguage(_claimManager.CurrentLanguage, claims); - if (!_claimManager.HasId()) + return new UserResponseContract() { - _claimManager.SetId(user.Id, claims); - _claimManager.SetUniqueIdentity(user.UniqueIdentity, claims); - _claimManager.SetRole(roles.Select(x => new ClaimContract() - { - Name = ClaimTypes.Role, - Value = x.Name - }).ToList(), claims); - } - - var response = await _jwtManager.GenerateTokenWithClaims(claims); - - SetCookie("token", response.Result.Token); - - return response; + Token = token, + }; } } } diff --git a/src/CSharp/EasyMicroservices.IdentityMicroservice.WebApi/EasyMicroservices.IdentityMicroservice.WebApi.csproj b/src/CSharp/EasyMicroservices.IdentityMicroservice.WebApi/EasyMicroservices.IdentityMicroservice.WebApi.csproj index 731ab30..ca8a4e4 100644 --- a/src/CSharp/EasyMicroservices.IdentityMicroservice.WebApi/EasyMicroservices.IdentityMicroservice.WebApi.csproj +++ b/src/CSharp/EasyMicroservices.IdentityMicroservice.WebApi/EasyMicroservices.IdentityMicroservice.WebApi.csproj @@ -6,10 +6,13 @@ + + all runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/src/CSharp/EasyMicroservices.IdentityMicroservice.WebApi/Program.cs b/src/CSharp/EasyMicroservices.IdentityMicroservice.WebApi/Program.cs index 1080dda..591c91f 100644 --- a/src/CSharp/EasyMicroservices.IdentityMicroservice.WebApi/Program.cs +++ b/src/CSharp/EasyMicroservices.IdentityMicroservice.WebApi/Program.cs @@ -1,10 +1,15 @@ -using EasyMicroservices.IdentityMicroservice.Database.Contexts; using EasyMicroservices.Cores.AspEntityFrameworkCoreApi; using EasyMicroservices.Cores.Relational.EntityFrameworkCore.Intrerfaces; -using EasyMicroservices.IdentityMicroservice; -using EasyMicroservices.IdentityMicroservice.Interfaces; +using EasyMicroservices.IdentityMicroservice.BackgroundServices; +using EasyMicroservices.IdentityMicroservice.Database.Contexts; using EasyMicroservices.IdentityMicroservice.Helpers; -using Microsoft.OpenApi.Models; +using EasyMicroservices.IdentityMicroservice.Interfaces; +using EasyMicroservices.IdentityMicroservice.Services; +using EasyMicroservices.Logger.Interfaces; +using EasyMicroservices.Logger.Options; +using EasyMicroservices.Logger.Serilog.Providers; +using Microsoft.Extensions.DependencyInjection; +using Serilog; namespace EasyMicroservices.IdentityMicroservice.WebApi { @@ -15,40 +20,32 @@ public static async Task Main(string[] args) var app = CreateBuilder(args); var build = await app.Build(true); build.MapControllers(); - build.Run(); + var scope = build.Services.CreateScope(); + await build.RunAsync(); } static WebApplicationBuilder CreateBuilder(string[] args) { var app = StartUpExtensions.Create(args); - app.Services.Builder(options => + app.Services.AddLogger((options) => { - options.AddSecurityRequirement(new OpenApiSecurityRequirement - { - { - new OpenApiSecurityScheme - { - Reference = new OpenApiReference - { - Type = ReferenceType.SecurityScheme, - Id = "Bearer" - }, - //Scheme = "oauth2", - Name = "Bearer", - In = ParameterLocation.Header - }, - new List() - } - }); - }).UseDefaultSwaggerOptions(); + options.UseSerilog(new Serilog.LoggerConfiguration() + .WriteTo.File("serilog.txt") + .MinimumLevel.Is(Serilog.Events.LogEventLevel.Verbose)); + }); + app.Services.Builder().UseDefaultSwaggerOptions(); app.Services.AddTransient((serviceProvider) => new UnitOfWork(serviceProvider)); app.Services.AddTransient(serviceProvider => new IdentityContext(serviceProvider.GetService())); app.Services.AddTransient(); app.Services.AddTransient(); app.Services.AddTransient((serviceProvider) => new ClaimManager(serviceProvider.GetService())); + app.Services.AddTransient(); + app.Services.AddTransient(); + app.Services.AddHostedService(); StartUpExtensions.AddWhiteLabel("Identity", "RootAddresses:WhiteLabel"); return app; } + public static async Task Run(string[] args, Action use) { @@ -56,7 +53,7 @@ public static async Task Run(string[] args, Action use) use?.Invoke(app.Services); var build = await app.Build(); build.MapControllers(); - build.Run(); + await build.RunAsync(); } } } \ No newline at end of file From 67b62ed86b5216225ac864e38025144dd188ca77 Mon Sep 17 00:00:00 2001 From: Github Actions Date: Mon, 4 Dec 2023 14:42:37 +0000 Subject: [PATCH 2/2] chore: Automated dotnet-format update --- .../EasyMicroservices.IdentityMicroservice.WebApi/Program.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/CSharp/EasyMicroservices.IdentityMicroservice.WebApi/Program.cs b/src/CSharp/EasyMicroservices.IdentityMicroservice.WebApi/Program.cs index 591c91f..04a2546 100644 --- a/src/CSharp/EasyMicroservices.IdentityMicroservice.WebApi/Program.cs +++ b/src/CSharp/EasyMicroservices.IdentityMicroservice.WebApi/Program.cs @@ -41,11 +41,11 @@ static WebApplicationBuilder CreateBuilder(string[] args) app.Services.AddTransient((serviceProvider) => new ClaimManager(serviceProvider.GetService())); app.Services.AddTransient(); app.Services.AddTransient(); - app.Services.AddHostedService(); + app.Services.AddHostedService(); StartUpExtensions.AddWhiteLabel("Identity", "RootAddresses:WhiteLabel"); return app; } - + public static async Task Run(string[] args, Action use) {