Skip to content

Commit

Permalink
Merge pull request #10 from Ali-YousefiTelori/develop
Browse files Browse the repository at this point in the history
Refactor, Use Serilog
  • Loading branch information
Ali-YousefiTelori authored Dec 5, 2023
2 parents 72e7726 + 67b62ed commit 30b7a78
Show file tree
Hide file tree
Showing 15 changed files with 217 additions and 144 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,27 +7,15 @@ namespace EasyMicroservices.IdentityMicroservice.Database.Contexts
{
public class IdentityContext : RelationalCoreContext
{
IEntityFrameworkCoreDatabaseBuilder _builder;
public IdentityContext(IEntityFrameworkCoreDatabaseBuilder builder) : base(builder)
{
}

//public DbSet<IdentityEntity> 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);



}
}
}
Empty file.
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="EasyMicroservices.Configuration" Version="0.0.0.2" />
<PackageReference Include="EasyMicroservices.Configuration" Version="0.0.0.3" />
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="EasyMicroservices.ContentsMicroservice.Clients" Version="0.0.0.18" />
<PackageReference Include="EasyMicroservices.Cores.AspEntityFrameworkCoreApi" Version="0.0.0.57" />
<PackageReference Include="EasyMicroservices.ContentsMicroservice.Clients" Version="0.0.0.19" />
<PackageReference Include="EasyMicroservices.Cores.AspEntityFrameworkCoreApi" Version="0.0.0.61" />
<PackageReference Include="EasyMicroservices.Logger" Version="0.0.0.4" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
@@ -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
{
Expand All @@ -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"
};
}
}
}
Original file line number Diff line number Diff line change
@@ -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();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand All @@ -28,12 +29,12 @@ public IConfiguration GetConfiguration()

public IdentityHelper GetIdentityHelper()
{
return new IdentityHelper(GetConfiguration(), GetIJWTManager());
return _service.GetService<IdentityHelper>();
}

public IJWTManager GetIJWTManager()
{
return new JWTManager(GetConfiguration());
return _service.GetService<IJWTManager>();
}

public ClaimManager GetClaimManager()
Expand All @@ -46,29 +47,44 @@ string GetValue(string key)
return GetConfiguration().GetValue<string>(key);
}

T SetToken<T>(HttpContext httpContext, T coreSwaggerClient)
public IHttpContextAccessor GetHttpContextAccessor()
{
return _service.GetService<IHttpContextAccessor>();
}

static HttpClient CurrentHttpClient { get; set; } = new HttpClient();

public static string Token = "";
T InternalLogin<T>(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<ILoggerProvider>();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,36 +4,33 @@
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;

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<string>("RootAddresses:Authentications");
_userClient = new(_authRoot, new System.Net.Http.HttpClient());
_appUnitOfWork = appUnitOfWork;
}


public async Task<MessageContract<RegisterResponseContract>> 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<string>("Authorization:FullAccessPAT"));
var user = await _userClient.AddAsync(new AddUserRequestContract
var user = await client.AddAsync(new AddUserRequestContract
{
UserName = request.UserName,
Password = request.Password
Expand All @@ -47,24 +44,65 @@ public async Task<MessageContract<RegisterResponseContract>> Register(Contracts.

public virtual async Task<MessageContract<LoginResponseContract>> 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<string> GetFullAccessPersonalAccessToken()
{
var ownerPat = _appUnitOfWork.GetConfiguration().GetValue<string>("Authorization:FullAccessPAT");
return GetFullAccessPersonalAccessToken(ownerPat);
}

public async Task<string> 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<ClaimContract> 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<MessageContract<UserResponseContract>> 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
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
}
Loading

0 comments on commit 30b7a78

Please sign in to comment.